diff --git a/dist/CHANGELOG.md b/dist/CHANGELOG.md new file mode 100644 index 0000000..ffb22bd --- /dev/null +++ b/dist/CHANGELOG.md @@ -0,0 +1,7 @@ +# Change Log + +All notable changes to this project will be documented in this file. + +## v1.0.0 + +- Initial release. diff --git a/dist/LICENSE b/dist/LICENSE new file mode 100644 index 0000000..56ee3c8 --- /dev/null +++ b/dist/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/dist/MANIFEST.txt b/dist/MANIFEST.txt new file mode 100644 index 0000000..1ef79e7 --- /dev/null +++ b/dist/MANIFEST.txt @@ -0,0 +1,38 @@ + +-----BEGIN PGP SIGNED MESSAGE----- +Hash: SHA512 + +{ + "manifestVersion": "2.0.0", + "signatureType": "grafana", + "signedByOrg": "grafana", + "signedByOrgName": "Grafana Labs", + "plugin": "grafana-es-open-distro-datasource", + "version": "1.0.0", + "time": 1617201728271, + "keyId": "7e4d0c6a708866e7", + "files": { + "gpx_es-open-distro-datasource_linux_arm64": "0f4b1bda247a92fe69a9c7aa7d0500aeb2e541116b96ff77e9ce81bec0d90e38", + "gpx_es-open-distro-datasource_darwin_amd64": "4fe90ac42d6c40cf23ec17205923c9eca8aa6df321847121052d0f5788c3d093", + "gpx_es-open-distro-datasource_linux_arm": "14e9a9abe4a257e935fe315bd14d55c2d10f62073c4b761db6b40f881a6f5d4e", + "module.js": "3bf33ce6f5e7feb2ffec0ec93020806ee75c56b492c7f623a5e53f0f0591cb0a", + "module.js.LICENSE.txt": "0d8f66cd4afb566cb5b7e1540c68f43b939d3eba12ace290f18abc4f4cb53ed0", + "module.js.map": "67dc41717f229e346c38ee31444b189fe7e4585d732ab3b1428263fc32aa1170", + "plugin.json": "b672475095ddda84db3659b04ba4a52ff5c8e42364af15266b66a0b0627df38b", + "LICENSE": "7339fa418c9ad3e8e12e74ad0fd26a9cc4be8703f9c110728a992b193be85cb2", + "README.md": "1a3ecf72010ffc3dede13adb46422f367be035d6da0d1c13f6a9d0207dce8787", + "CHANGELOG.md": "843f34524edc1b8b3898d48836c62dd863c83ad2f96734dc8a97c6451b94fcde", + "partials/annotations.editor.html": "29d09f8186c5620d166f2b9c4c593cffcbc257dfd47191b2e90e6c7acc696a9f", + "img/logo.svg": "00f2d5508d37e01a8a38b60dc5cacd10465c44f28ec3fc8c372068dcc7099417" + } +} +-----BEGIN PGP SIGNATURE----- +Version: OpenPGP.js v4.10.1 +Comment: https://openpgpjs.org + +wqIEARMKAAYFAmBkikAACgkQfk0ManCIZudPAAIJAfJPufqTw5xIWrwYTEzH +dd276Ao83TA0mBgixqnz6q5BYT1chg8/rSHS3c35heOmkvuKxdXFJu2CB/Ll +uubw4jKKAgkBhRDdqIWTMpwWL6Ep0pXrkbJDNVw20dDAwhWJStTVe+jCrrOQ +ZTPB3qJgUFCwZwL9878zy1Ad1nufA1a9QSpriMo= +=YS3y +-----END PGP SIGNATURE----- diff --git a/dist/README.md b/dist/README.md new file mode 100644 index 0000000..bda34e8 --- /dev/null +++ b/dist/README.md @@ -0,0 +1,3 @@ +# Open Distro for Elasticsearch Data Source + +The Open Distro for Elasticsearch data source plugin provides a support for [Open Distro for Elasticsearch](https://opendistro.github.io/for-elasticsearch/). diff --git a/dist/gpx_es-open-distro-datasource_darwin_amd64 b/dist/gpx_es-open-distro-datasource_darwin_amd64 new file mode 100755 index 0000000..410e3b5 Binary files /dev/null and b/dist/gpx_es-open-distro-datasource_darwin_amd64 differ diff --git a/dist/gpx_es-open-distro-datasource_linux_amd64 b/dist/gpx_es-open-distro-datasource_linux_amd64 new file mode 100755 index 0000000..9beaab9 Binary files /dev/null and b/dist/gpx_es-open-distro-datasource_linux_amd64 differ diff --git a/dist/gpx_es-open-distro-datasource_linux_arm b/dist/gpx_es-open-distro-datasource_linux_arm new file mode 100755 index 0000000..d50fdac Binary files /dev/null and b/dist/gpx_es-open-distro-datasource_linux_arm differ diff --git a/dist/gpx_es-open-distro-datasource_linux_arm64 b/dist/gpx_es-open-distro-datasource_linux_arm64 new file mode 100755 index 0000000..4bb941c Binary files /dev/null and b/dist/gpx_es-open-distro-datasource_linux_arm64 differ diff --git a/dist/gpx_es-open-distro-datasource_windows_amd64.exe b/dist/gpx_es-open-distro-datasource_windows_amd64.exe new file mode 100755 index 0000000..bd1ff63 Binary files /dev/null and b/dist/gpx_es-open-distro-datasource_windows_amd64.exe differ diff --git a/dist/img/logo.svg b/dist/img/logo.svg new file mode 100644 index 0000000..e0c314e --- /dev/null +++ b/dist/img/logo.svg @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + diff --git a/dist/module.js b/dist/module.js new file mode 100644 index 0000000..13323ed --- /dev/null +++ b/dist/module.js @@ -0,0 +1,3 @@ +/*! For license information please see module.js.LICENSE.txt */ +define(["react","@grafana/ui","@grafana/data","emotion","lodash","@grafana/runtime","rxjs","prismjs"],(function(e,t,n,r,a,i,o,l){return function(e){var t={};function n(r){if(t[r])return t[r].exports;var a=t[r]={i:r,l:!1,exports:{}};return e[r].call(a.exports,a,a.exports,n),a.l=!0,a.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var a in e)n.d(r,a,function(t){return e[t]}.bind(null,a));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="/",n(n.s=10)}([function(t,n){t.exports=e},function(e,n){e.exports=t},function(e,t){e.exports=n},function(e,t){e.exports=r},function(e,t){e.exports=a},function(e,t){e.exports=i},function(e,t){e.exports=o},function(e,t){e.exports=l},function(e,t,n){"use strict";e.exports=n(9)},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r={DataSource:{TestData:{QueryTab:{scenarioSelectContainer:"Test Data Query scenario select container",scenarioSelect:"Test Data Query scenario select",max:"TestData max",min:"TestData min",noise:"TestData noise",seriesCount:"TestData series count",spread:"TestData spread",startValue:"TestData start value"}}},Panels:{Panel:{title:function(e){return"Panel header title item "+e},headerItems:function(e){return"Panel header item "+e},containerByTitle:function(e){return"Panel container title "+e},headerCornerInfo:function(e){return"Panel header "+e}},Visualization:{Graph:{VisualizationTab:{legendSection:"Legend section"},Legend:{legendItemAlias:function(e){return"gpl alias "+e},showLegendSwitch:"gpl show legend"},xAxis:{labels:function(){return"div.flot-x-axis > div.flot-tick-label"}}},BarGauge:{value:"Bar gauge value"},Text:{container:function(){return".markdown-html"}}}},Drawer:{General:{title:function(e){return"Drawer title "+e},expand:"Drawer expand",contract:"Drawer contract",close:"Drawer close",rcContentWrapper:function(){return".drawer-content-wrapper"}}},PanelEditor:{General:{content:"Panel editor content"},OptionsPane:{content:"Panel editor option pane content",close:"Page toolbar button Close options pane",open:"Page toolbar button Open options pane",select:"Panel editor option pane select",tab:function(e){return"Panel editor option pane tab "+e}},DataPane:{content:"Panel editor data pane content"},FieldOptions:{propertyEditor:function(e){return e+" field property editor"}}},PanelInspector:{Data:{content:"Panel inspector Data content"},Stats:{content:"Panel inspector Stats content"},Json:{content:"Panel inspector Json content"},Query:{content:"Panel inspector Query content",refreshButton:"Panel inspector Query refresh button",jsonObjectKeys:function(){return".json-formatter-key"}}},Tab:{title:function(e){return"Tab "+e},active:function(){return'[class*="-activeTabStyle"]'}},RefreshPicker:{runButton:"RefreshPicker run button"},QueryTab:{content:"Query editor tab content",queryInspectorButton:"Query inspector button",addQuery:"Query editor add query button"},QueryEditorRows:{rows:"Query editor row"},QueryEditorRow:{actionButton:function(e){return e+" query operation action"},title:function(e){return"Query editor row title "+e}},AlertTab:{content:"Alert editor tab content"},Alert:{alert:function(e){return"Alert "+e}},TransformTab:{content:"Transform editor tab content",newTransform:function(e){return"New transform "+e},transformationEditor:function(e){return"Transformation editor "+e},transformationEditorDebugger:function(e){return"Transformation editor debugger "+e}},Transforms:{card:function(e){return"New transform "+e},Reduce:{modeLabel:"Transform mode label",calculationsLabel:"Transform calculations label"},searchInput:"search transformations"},PageToolbar:{container:function(){return".page-toolbar"},item:function(e){return"Page toolbar button "+e}},QueryEditorToolbarItem:{button:function(e){return"QueryEditor toolbar item button "+e}},BackButton:{backArrow:"Go Back button"},OptionsGroup:{toggle:function(e){return e?"Options group "+e:"Options group"}},PluginVisualization:{item:function(e){return"Plugin visualization item "+e},current:function(){return'[class*="-currentVisualizationItem"]'}},Select:{option:"Select option",input:function(){return'input[id*="react-select-"]'},singleValue:function(){return'div[class*="-singleValue"]'}},FieldConfigEditor:{content:"Field config editor content"},OverridesConfigEditor:{content:"Field overrides editor content"},FolderPicker:{container:"Folder picker select container"},DataSourcePicker:{container:"Data source picker select container"},TimeZonePicker:{container:"Time zone picker select container"},TraceViewer:{spanBar:function(){return'[data-test-id="SpanBar--wrapper"]'}},QueryField:{container:"Query field"},ValuePicker:{button:"Value picker add button",select:function(e){return"Value picker select "+e}},Search:{section:"Search section",items:"Search items"},DashboardLinks:{container:"Dashboard link container",dropDown:"Dashboard link dropdown",link:"Dashboard link"},CallToActionCard:{button:function(e){return"Call to action button "+e}},DataLinksContextMenu:{singleLink:"Data link"}},a={pages:{Login:{url:"/login",username:"Username input field",password:"Password input field",submit:"Login button",skip:"Skip change password button"},Home:{url:"/"},DataSource:{name:"Data source settings page name input field",delete:"Data source settings page Delete button",saveAndTest:"Data source settings page Save and Test button",alert:"Data source settings page Alert"},DataSources:{url:"/datasources",dataSources:function(e){return"Data source list item "+e}},AddDataSource:{url:"/datasources/new",dataSourcePlugins:function(e){return"Data source plugin item "+e}},ConfirmModal:{delete:"Confirm Modal Danger Button"},AddDashboard:{url:"/dashboard/new",addNewPanel:"Add new panel"},Dashboard:{url:function(e){return"/d/"+e},SubMenu:{submenuItem:"Dashboard template variables submenu item",submenuItemLabels:function(e){return"Dashboard template variables submenu Label "+e},submenuItemValueDropDownValueLinkTexts:function(e){return"Dashboard template variables Variable Value DropDown value link text "+e},submenuItemValueDropDownDropDown:"Dashboard template variables Variable Value DropDown DropDown",submenuItemValueDropDownOptionTexts:function(e){return"Dashboard template variables Variable Value DropDown option text "+e}},Settings:{General:{deleteDashBoard:"Dashboard settings page delete dashboard button",sectionItems:function(e){return"Dashboard settings section item "+e},saveDashBoard:"Dashboard settings aside actions Save button",saveAsDashBoard:"Dashboard settings aside actions Save As button",timezone:"Time zone picker select container",title:"Dashboard settings page title"},Annotations:{List:{addAnnotationCTA:r.CallToActionCard.button("Add Annotation Query")}},Variables:{List:{addVariableCTA:r.CallToActionCard.button("Add variable"),newButton:"Variable editor New variable button",table:"Variable editor Table",tableRowNameFields:function(e){return"Variable editor Table Name field "+e},tableRowDefinitionFields:function(e){return"Variable editor Table Definition field "+e},tableRowArrowUpButtons:function(e){return"Variable editor Table ArrowUp button "+e},tableRowArrowDownButtons:function(e){return"Variable editor Table ArrowDown button "+e},tableRowDuplicateButtons:function(e){return"Variable editor Table Duplicate button "+e},tableRowRemoveButtons:function(e){return"Variable editor Table Remove button "+e}},Edit:{General:{headerLink:"Variable editor Header link",modeLabelNew:"Variable editor Header mode New",modeLabelEdit:"Variable editor Header mode Edit",generalNameInput:"Variable editor Form Name field",generalTypeSelect:"Variable editor Form Type select",generalLabelInput:"Variable editor Form Label field",generalHideSelect:"Variable editor Form Hide select",selectionOptionsMultiSwitch:"Variable editor Form Multi switch",selectionOptionsIncludeAllSwitch:"Variable editor Form IncludeAll switch",selectionOptionsCustomAllInput:"Variable editor Form IncludeAll field",previewOfValuesOption:"Variable editor Preview of Values option",submitButton:"Variable editor Submit button"},QueryVariable:{queryOptionsDataSourceSelect:r.DataSourcePicker.container,queryOptionsRefreshSelect:"Variable editor Form Query Refresh select",queryOptionsRegExInput:"Variable editor Form Query RegEx field",queryOptionsSortSelect:"Variable editor Form Query Sort select",queryOptionsQueryInput:"Variable editor Form Default Variable Query Editor textarea",valueGroupsTagsEnabledSwitch:"Variable editor Form Query UseTags switch",valueGroupsTagsTagsQueryInput:"Variable editor Form Query TagsQuery field",valueGroupsTagsTagsValuesQueryInput:"Variable editor Form Query TagsValuesQuery field"},ConstantVariable:{constantOptionsQueryInput:"Variable editor Form Constant Query field"},TextBoxVariable:{textBoxOptionsQueryInput:"Variable editor Form TextBox Query field"}}}}},Dashboards:{url:"/dashboards",dashboards:function(e){return"Dashboard search item "+e}},SaveDashboardAsModal:{newName:"Save dashboard title field",save:"Save dashboard button"},SaveDashboardModal:{save:"Dashboard settings Save Dashboard Modal Save button",saveVariables:"Dashboard settings Save Dashboard Modal Save variables checkbox",saveTimerange:"Dashboard settings Save Dashboard Modal Save timerange checkbox"},SharePanelModal:{linkToRenderedImage:"Link to rendered image"},Explore:{url:"/explore",General:{container:"Explore",graph:"Explore Graph",table:"Explore Table",scrollBar:function(){return".scrollbar-view"}},Toolbar:{navBar:function(){return".explore-toolbar"}}},SoloPanel:{url:function(e){return"/d-solo/"+e}},PluginsList:{page:"Plugins list page",list:"Plugins list",listItem:"Plugins list item",signatureErrorNotice:"Unsigned plugins notice"},PluginPage:{page:"Plugin page",signatureInfo:"Plugin signature info"}},components:r};t.selectors=a},function(e,t,n){"use strict";n.r(t);var r=n(2),a=function(e,t){return(a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])})(e,t)};function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}a(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}var o=function(){return(o=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&a[a.length-1])||6!==i[0]&&2!==i[0])){o=0;continue}if(3===i[0]&&(!a||i[1]>a[0]&&i[1]=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function d(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,a,i=n.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(r=i.next()).done;)o.push(r.value)}catch(e){a={error:e}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(a)throw a.error}}return o}function p(){for(var e=[],t=0;t?|<|>)?|>[>=]?|\\b(?:"+["by","group_left","group_right","ignoring","on","offset","without"].join("|")+")\\b","i"),punctuation:/[{};()`,.]/};var L=function(e){function t(t,n){var r=e.call(this)||this;return r.datasource=t,Object.assign(r,n),r}return i(t,e),t.prototype.importQueries=function(e,t){return"prometheus"===t||"loki"===t?e.map((function(e){return{isLogsQuery:!0,query:function(e){var t,n,r=[];try{for(var a=c(e),i=a.next();!i.done;i=a.next()){var o=i.value;switch(o[1]){case"=":r.push(o[0]+":"+o[2]);break;case"!=":r.push("NOT "+o[0]+":"+o[2]);break;case"=~":r.push(o[0]+":/"+o[2].substring(1,o[2].length-1)+"/");break;case"!~":r.push("NOT "+o[0]+":/"+o[2].substring(1,o[2].length-1)+"/")}}}catch(e){t={error:e}}finally{try{i&&!i.done&&(n=a.return)&&n.call(a)}finally{if(t)throw t.error}}return r.join(" AND ")}(function(e){var t=[];if(!e||0===e.length)return t;var n=V.a.tokenize(e,M),r=function(e,t){var n="";for(var r in t)if("string"==typeof t[r]){n=t[r];break}return n}(0,n);for(var a in r&&r.length>0&&t.push(["__name__","=",'"'+r+'"']),n)if(n[a]instanceof q.Token){var i=n[a];if("context-labels"===i.type){var o="",l="",s="",u=i.content;for(var c in u)if("string"==typeof u[c]){var d;"="!==(d=u[c])&&"!="!==d&&"=~"!==d&&"!~"!==d||(s=d)}else if(u[c]instanceof q.Token)switch(u[c].type){case"label-key":o=u[c].content;break;case"label-value":l=u[c].content,t.push([o,s,l])}}}return t}(e.expr)),refId:e.refId}})):e.map((function(e){return{isLogsQuery:!0,query:"",refId:e.refId}}))},t}(r.LanguageProvider);function N(e,t){var n=(t=t||{}).delimiter||".",r=t.maxDepth||3,a=1,i={};return function e(o,l){Object.keys(o).forEach((function(s){var u=o[s],c=(null==t?void 0:t.safe)&&Array.isArray(u),d="[object Object]"===Object.prototype.toString.call(u),p=l?l+n+s:s;if((null==t?void 0:t.maxDepth)||(r=a+1),!c&&d&&Object.keys(u).length&&an)||-(t0&&r.processHits(a.hits,t,i),a.aggregations){var o=a.aggregations,l=r.targets[n],s=[],u=new X;u.refId=l.refId,r.processBuckets(o,l,s,u,{},0),r.trimDatapoints(s,l),r.nameSeries(s,l);for(var c=0;c0&&t.push(u)}}return{data:t,key:null===(e=r.targets[0])||void 0===e?void 0:e.refId}},this.processPPLResponseToSeries=function(){var e,t=r.targets[0],n=r.response,a=[];if(n.datarows.length>0){if(n.error)throw r.getErrorFromElasticResponse(r.response,n.error);var i=oe(n),o=i.datapoints,l=i.targetVal;if(i.invalidTS)throw r.getInvalidPPLQuery(r.response);var s={datapoints:o,props:n.schema,refId:t.refId,target:l};a.push(s)}return{data:a,key:null===(e=r.targets[0])||void 0===e?void 0:e.refId}},this.targets=e,this.response=t,this.targetType=n}return e.prototype.processMetrics=function(e,t,n,r){for(var a,i=0;i1&&(B(j)&&(V+=" "+j.field),"bucket_script"===j.type&&(V=(null===(f=j.settings)||void 0===f?void 0:f.script)||"")),y(S,V,E[j.id].value)}}}catch(e){p={error:e}}finally{try{P&&!P.done&&(m=F.return)&&m.call(F)}finally{if(p)throw p.error}}r.rows.push(S)}}catch(e){l={error:e}}finally{try{w&&!w.done&&(s=x.return)&&s.call(x)}finally{if(l)throw l.error}}},e.prototype.processBuckets=function(e,t,n,r,a,i){var o,l,s,u,c=t.bucketAggs.length-1;for(u in e)if(l=v.a.find(t.bucketAggs,{id:u}),s=e[u],l)if(i===c)"date_histogram"===l.type?this.processMetrics(s,t,n,a):this.processAggregationDocs(s,l,t,r,a);else for(var d in s.buckets)o=s.buckets[d],a=v.a.clone(a),void 0!==o.key?a[l.field]=o.key:a.filter=d,o.key_as_string&&(a[l.field]=o.key_as_string),this.processBuckets(o,t,n,r,a,i+1)},e.prototype.getMetricName=function(e){var t=Object.entries(U).filter((function(t){return d(t,1)[0]===e})).map((function(e){var t=d(e,2);t[0];return t[1]}))[0];if(t)return t.label;var n=W.find((function(t){return t.value===e}));return n?n.label:e},e.prototype.getSeriesName=function(e,t,n){var r,a,i=this.getMetricName(e.metric);if(t.alias){return t.alias.replace(/\{\{([\s\S]+?)\}\}/g,(function(t,n,r){var a=n||r;return 0===a.indexOf("term ")?e.props[a.substring(5)]:void 0!==e.props[a]?e.props[a]:"metric"===a?i:"field"===a?e.field||"":t}))}if(e.metric in H)if(e.metric&&function(e){return!!U[e].supportsMultipleBucketPaths}(e.metric)){var o=v.a.find(t.metrics,{id:e.metricId});if(o&&o.settings.script){i=o.settings.script;try{for(var l=c(o.pipelineVariables),s=l.next();!s.done;s=l.next()){var u=s.value;(d=v.a.find(t.metrics,{id:u.pipelineAgg}))&&(i=i.replace("params."+u.name,te(d)))}}catch(e){r={error:e}}finally{try{s&&!s.done&&(a=l.return)&&a.call(l)}finally{if(r)throw r.error}}}else i="Unset"}else{var d;(d=v.a.find(t.metrics,{id:e.field}))?i+=" "+te(d):i="Unset"}else e.field&&(i+=" "+e.field);if(0===v.a.keys(e.props).length)return i;var p="";for(var m in e.props)p+=e.props[m]+" ";return 1===n?p.trim():p.trim()+" "+i},e.prototype.nameSeries=function(e,t){for(var n=v.a.uniq(v.a.map(e,"metric")).length,r=0;r2*r&&(i.datapoints=i.datapoints.slice(r,i.datapoints.length-r))}}},e.prototype.getErrorFromElasticResponse=function(e,t){var n={};return n.data=JSON.stringify(t,null,4),t.root_cause&&t.root_cause.length>0&&t.root_cause[0].reason?n.message=t.root_cause[0].reason:n.message=t.reason||"Unknown elastic error response",e.$$config&&(n.config=e.$$config),n},e.prototype.getInvalidPPLQuery=function(e){var t={message:"Invalid time series query"};return e.$$config&&(t.config=e.$$config),t},e.prototype.getTimeSeries=function(){return this.targetType===K.PPL?this.processPPLResponseToSeries():this.targets.some((function(e){var t;return null===(t=e.metrics)||void 0===t?void 0:t.some((function(e){return"raw_data"===e.type}))}))?this.processResponseToDataFrames(!1):this.processResponseToSeries()},e.prototype.getLogs=function(e,t){return this.targetType===K.PPL?this.processPPLResponseToDataFrames(!0,e,t):this.processResponseToDataFrames(!0,e,t)},e.prototype.getTable=function(){return this.processPPLResponseToDataFrames(!1)},e.prototype.processResponseToDataFrames=function(e,t,n){for(var a,i,o,l=[],s=0;s0){var d=ae(u.hits.hits),p=d.propNames,m=d.docs;if(m.length>0){var f=le(p,this.targets[0].timeField,e,this.targetType,t,n);try{for(var v=(a=void 0,c(m)),g=v.next();!g.done;g=v.next()){var h=g.value;n&&(h.level=h[n]),f.add(h)}}catch(e){a={error:e}}finally{try{g&&!g.done&&(i=v.return)&&i.call(v)}finally{if(a)throw a.error}}e&&(f=se(f,"logs"));var b=this.targets[s];f.refId=b.refId,l.push(f)}}if(u.aggregations){var y=u.aggregations,_=(b=this.targets[s],[]),x=new X;if(this.processBuckets(y,b,_,x,{},0),this.trimDatapoints(_,b),this.nameSeries(_,b),x.rows.length>0)(f=Object(r.toDataFrame)(x)).refId=b.refId,l.push(f);for(var w=0;w<_.length;w++){f=Object(r.toDataFrame)(_[w]);e&&(f=se(f,"graph")),f.refId=b.refId,l.push(f)}}}return{data:l,key:null===(o=this.targets[0])||void 0===o?void 0:o.refId}},e.prototype.processPPLResponseToDataFrames=function(e,t,n){var r,a,i;if(this.response.error)throw this.getErrorFromElasticResponse(this.response,this.response.error);var o=[],l=this.response.schema.map((function(e){return e.name})),s=v.a.map(this.response.datarows,(function(e){return v.a.zipObject(l,e)})),u=ie(s),d=u.flattenSchema,p=u.docs;if(s.length>0){var m=le(d,this.targets[0].timeField,e,this.targetType,t,n);try{for(var f=c(p),g=f.next();!g.done;g=f.next()){var h=g.value;n&&(h.level=h[n]),m.add(h)}}catch(e){r={error:e}}finally{try{g&&!g.done&&(a=f.return)&&a.call(f)}finally{if(r)throw r.error}}e&&(m=se(m,"logs"));var b=this.targets[0];m.refId=b.refId,o.push(m)}return{data:o,key:null===(i=this.targets[0])||void 0===i?void 0:i.refId}},e}(),ae=function(e){var t,n,r,a,i=[],l=[];try{for(var s=c(e),u=s.next();!u.done;u=s.next()){var d=u.value,p=d._source?N(d._source):{},m=o({_id:d._id,_type:d._type,_index:d._index,_source:o({},p)},p);try{for(var f=(r=void 0,c(Object.keys(m))),v=f.next();!v.done;v=f.next()){var g=v.value;-1===l.indexOf(g)&&l.push(g)}}catch(e){r={error:e}}finally{try{v&&!v.done&&(a=f.return)&&a.call(f)}finally{if(r)throw r.error}}i.push(m)}}catch(e){t={error:e}}finally{try{u&&!u.done&&(n=s.return)&&n.call(s)}finally{if(t)throw t.error}}return l.sort(),{docs:i,propNames:l}},ie=function(e){var t,n,r,a,i=[],o=[];try{for(var l=c(e),s=l.next();!s.done;s=l.next()){var u=N(s.value);try{for(var d=(r=void 0,c(Object.keys(u))),p=d.next();!p.done;p=d.next()){var m=p.value;-1===o.indexOf(m)&&o.push(m)}}catch(e){r={error:e}}finally{try{p&&!p.done&&(a=d.return)&&a.call(d)}finally{if(r)throw r.error}}i.push(u)}}catch(e){t={error:e}}finally{try{s&&!s.done&&(n=l.return)&&n.call(l)}finally{if(t)throw t.error}}return{docs:i,flattenSchema:o}},oe=function(e){var t,n=!1,a=v.a.findIndex(e.schema,(function(e){return"timestamp"===e.type||"datetime"===e.type||"date"===e.type})),i=0===a?1:0;return-1!==a&&2===e.datarows[0].length&&"number"==typeof e.datarows[0][i]||(n=!0),{datapoints:v.a.map(e.datarows,(function(e){var t=v.a.clone(e),n=d(t.splice(a,1),1)[0];return t.push(1e3*Object(r.dateTime)(n).unix()),t})),targetVal:null===(t=e.schema[i])||void 0===t?void 0:t.name,invalidTS:n}},le=function(e,t,n,a,i,o){var l,s,u=new r.MutableDataFrame({fields:[]});(a===K.Lucene||n)&&u.addField({config:{filterable:!0},name:t,type:r.FieldType.time}),i&&(u.addField({name:i,type:r.FieldType.string}).parse=function(e){return e||""}),o&&(u.addField({name:"level",type:r.FieldType.string}).parse=function(e){return e||""});var d=u.fields.map((function(e){return e.name}));try{for(var p=c(e),m=p.next();!m.done;m=p.next()){var f=m.value;d.includes(f)||(n||"_source"!==f)&&(u.addField({config:{filterable:!0},name:f,type:r.FieldType.string}).parse=function(e){return e||""})}}catch(e){l={error:e}}finally{try{m&&!m.done&&(s=p.return)&&s.call(p)}finally{if(l)throw l.error}}return u},se=function(e,t){var n=e;return n.meta?n.meta.preferredVisualisationType=t:n.meta={preferredVisualisationType:t},n},ue={Hourly:{startOf:"hour",amount:"hours"},Daily:{startOf:"day",amount:"days"},Weekly:{startOf:"isoWeek",amount:"weeks"},Monthly:{startOf:"month",amount:"months"},Yearly:{startOf:"year",amount:"years"}},ce=function(){function e(e,t){this.pattern=e,this.interval=t,this.dateLocale="en"}return e.prototype.getIndexForToday=function(){return this.interval?Object(r.toUtc)().locale(this.dateLocale).format(this.pattern):this.pattern},e.prototype.getIndexList=function(e,t){if(!this.interval)return this.pattern;for(var n=ue[this.interval],a=Object(r.dateTime)(e||Object(r.dateTime)(t).add(-7,n.amount)).utc().startOf(n.startOf),i=Object(r.dateTime)(t||Object(r.dateTime)(e).add(7,n.amount)).utc().startOf(n.startOf).valueOf(),o=[];a.valueOf()<=i;)o.push(a.locale(this.dateLocale).format(this.pattern)),a.add(1,n.amount);return o},e.prototype.getPPLIndexPattern=function(){if(!this.interval)return this.pattern;var e=this.pattern.match(/\[(.*?)\]/)[1];return this.pattern.startsWith("[")?e+="*":this.pattern.endsWith("]")&&(e="*"+e),e},e}();function de(){var e=Object(r.dateTime)();return{from:Object(r.dateTime)(e).subtract(6,"hour"),to:e,raw:{from:"now-6h",to:"now"}}}var pe=function(){function e(e){this.timeField=e.timeField,this.esVersion=e.esVersion}return e.prototype.getRangeFilter=function(){var e={};return e[this.timeField]={gte:"$timeFrom",lte:"$timeTo",format:"epoch_millis"},e},e.prototype.buildTermsAgg=function(e,t,n){var r,a,i,o;if(t.terms={field:e.field},!e.settings)return t;var l=(null===(i=e.settings)||void 0===i?void 0:i.size)?parseInt(e.settings.size,10):500;if(t.terms.size=0===l?500:l,void 0!==e.settings.orderBy&&(t.terms.order={},"_term"===e.settings.orderBy&&this.esVersion>=60?t.terms.order._key=e.settings.order:t.terms.order[e.settings.orderBy]=e.settings.order,o=parseInt(e.settings.orderBy,10),!isNaN(o)))try{for(var s=c(n.metrics||[]),u=s.next();!u.done;u=s.next()){var d=u.value;if(d.id===e.settings.orderBy){t.aggs={},t.aggs[d.id]={},B(d)&&(t.aggs[d.id][d.type]={field:d.field});break}}}catch(e){r={error:e}}finally{try{u&&!u.done&&(a=s.return)&&a.call(s)}finally{if(r)throw r.error}}return void 0!==e.settings.min_doc_count&&(t.terms.min_doc_count=parseInt(e.settings.min_doc_count,10),isNaN(t.terms.min_doc_count)&&(t.terms.min_doc_count=e.settings.min_doc_count)),e.settings.missing&&(t.terms.missing=e.settings.missing),t},e.prototype.getDateHistogramAgg=function(e){var t={},n=e.settings||{};return t.interval=n.interval,t.field=this.timeField,t.min_doc_count=n.min_doc_count||0,t.extended_bounds={min:"$timeFrom",max:"$timeTo"},t.format="epoch_millis",""!==n.offset&&(t.offset=n.offset),"auto"===t.interval&&(t.interval="$__interval"),t},e.prototype.getHistogramAgg=function(e){var t={},n=e.settings||{};return t.interval=n.interval,t.field=e.field,t.min_doc_count=n.min_doc_count||0,t},e.prototype.getFiltersAgg=function(e){var t,n,r,a={};try{for(var i=c((null===(r=e.settings)||void 0===r?void 0:r.filters)||[]),o=i.next();!o.done;o=i.next()){var l=o.value,s=l.query;a[l.label||s]={query_string:{query:s,analyze_wildcard:!0}}}}catch(e){t={error:e}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(t)throw t.error}}return a},e.prototype.documentQuery=function(e,t){return e.size=t,e.sort={},e.sort[this.timeField]={order:"desc",unmapped_type:"boolean"},this.esVersion<5&&(e.fields=["*","_source"]),e.script_fields={},e},e.prototype.addAdhocFilters=function(e,t){var n,r,a,i;if(t)for(n=0;n":a[r.key]={gt:r.value},e.query.bool.filter.push({range:a});break;case"=~":e.query.bool.filter.push({regexp:a});break;case"!~":e.query.bool.filter.push({bool:{must_not:{regexp:a}}})}},e.prototype.build=function(e,t,n){var r,a,i,l,s,u,c,d,p,m,f;e.metrics=e.metrics||[Y()],e.bucketAggs=e.bucketAggs||[G()],e.timeField=this.timeField,e.queryType=K.Lucene;var v={size:0,query:{bool:{filter:[{range:this.getRangeFilter()},{query_string:{analyze_wildcard:!0,query:n}}]}}};if(this.addAdhocFilters(v,t),0===e.bucketAggs.length&&(!(f=e.metrics[0])||"raw_document"!==f.type&&"raw_data"!==f.type))throw{message:"Invalid query"};if("raw_document"===(null===(a=null===(r=e.metrics)||void 0===r?void 0:r[0])||void 0===a?void 0:a.type)||"raw_data"===(null===(l=null===(i=e.metrics)||void 0===i?void 0:i[0])||void 0===l?void 0:l.type)){var g=(null===(s=(f=e.metrics[0]).settings)||void 0===s?void 0:s.size)?parseInt(f.settings.size,10):500;return this.documentQuery(v,g||500)}for(m=v,c=0;c=60?"_key":"_term";t.aggs[1].terms.order[l]=o;break;case"doc_count":t.aggs[1].terms.order._count=o;break;default:throw{message:"Invalid query sort type "+a}}return t},e.prototype.getLogsQuery=function(e,t,n){var r={size:0,query:{bool:{filter:[{range:this.getRangeFilter()}]}}};return this.addAdhocFilters(r,t),e.query&&r.query.bool.filter.push({query_string:{analyze_wildcard:!0,query:n}}),r=this.documentQuery(r,500),o(o({},r),{aggs:this.build(e,null,n).aggs})},e.prototype.addPPLAdhocFilters=function(e,t){var n,a,i;for(n=0;n0?" and "+i:" | where "+i}return e},e.prototype.buildPPLQuery=function(e,t,n){e.format=e.format||"table",e.queryType=K.PPL,e.isLogsQuery="logs"===e.format,t&&(n=this.addPPLAdhocFilters(n,t));var r=" where $timestamp >= timestamp('$timeFrom') and $timestamp <= timestamp('$timeTo')";if(n){var a=n.indexOf("|");n=-1===a?[n.trimEnd(),r].join(" |"):[n.slice(0,a).trimEnd(),r,n.slice(a+1)].join(" |")}return{query:n}},e}(),me=n(5),fe={terms:{label:"Terms",requiresField:!0,defaultSettings:{min_doc_count:"0",size:"10",order:"desc",orderBy:"_term"}},filters:{label:"Filters",requiresField:!1,defaultSettings:{filters:[{label:"",query:"*"}]}},geohash_grid:{label:"Geo Hash Grid",requiresField:!0,defaultSettings:{precision:"3"}},date_histogram:{label:"Date Histogram",requiresField:!0,defaultSettings:{interval:"auto",min_doc_count:"0",trimEdges:"0"}},histogram:{label:"Histogram",requiresField:!0,defaultSettings:{interval:"1000",min_doc_count:"0"}}},ve=[{label:"Top",value:"desc"},{label:"Bottom",value:"asc"}],ge=[{label:"No limit",value:"0"},{label:"1",value:"1"},{label:"2",value:"2"},{label:"3",value:"3"},{label:"5",value:"5"},{label:"10",value:"10"},{label:"15",value:"15"},{label:"20",value:"20"}],he=[{label:"Term value",value:"_term"},{label:"Doc Count",value:"_count"}],be=[{label:"auto",value:"auto"},{label:"10s",value:"10s"},{label:"1m",value:"1m"},{label:"5m",value:"5m"},{label:"10m",value:"10m"},{label:"20m",value:"20m"},{label:"1h",value:"1h"},{label:"1d",value:"1d"}],ye=function(e){return fe[e.type].requiresField};function _e(e){return(_e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}var xe=["_index","_type","_id","_source","_size","_field_names","_ignored","_routing","_meta"],we=function(e){function t(t){var n,r,a=e.call(this,t)||this;a.basicAuth=t.basicAuth,a.withCredentials=t.withCredentials,a.url=t.url,a.name=t.name;var i=t.jsonData||{};return a.index=null!==(n=i.database)&&void 0!==n?n:"",a.timeField=i.timeField,a.esVersion=i.esVersion,a.indexPattern=new ce(a.index,i.interval),a.interval=i.timeInterval,a.maxConcurrentShardRequests=i.maxConcurrentShardRequests,a.queryBuilder=new pe({timeField:a.timeField,esVersion:a.esVersion}),a.logMessageField=i.logMessageField||"",a.logLevelField=i.logLevelField||"",a.dataLinks=i.dataLinks||[],""===a.logMessageField&&(a.logMessageField=void 0),""===a.logLevelField&&(a.logLevelField=void 0),a.languageProvider=new L(a),a.pplEnabled=null===(r=i.pplEnabled)||void 0===r||r,a}return i(t,e),t.prototype.request=function(e,t,n){var r={url:this.url+"/"+t,method:e,data:n};return(this.basicAuth||this.withCredentials)&&(r.withCredentials=!0),this.basicAuth&&(r.headers={Authorization:this.basicAuth}),Object(me.getBackendSrv)().datasourceRequest(r).catch((function(e){if(e.data&&e.data.error)throw{message:"Elasticsearch error: "+e.data.error.reason+". "+e.data.error.details,error:e.data.error};throw e}))},t.prototype.importQueries=function(e,t){return s(this,void 0,Promise,(function(){return u(this,(function(n){return[2,this.languageProvider.importQueries(e,t.id)]}))}))},t.prototype.get=function(e,t){void 0===t&&(t=de());var n=this.indexPattern.getIndexList(t.from,t.to);return v.a.isArray(n)&&n.length?this.requestAllIndices(n,e).then((function(e){return e.data.$$config=e.config,e.data})):this.request("GET",this.indexPattern.getIndexForToday()+e).then((function(e){return e.data.$$config=e.config,e.data}))},t.prototype.requestAllIndices=function(e,t){return s(this,void 0,Promise,(function(){var n,r,a,i;return u(this,(function(o){switch(o.label){case 0:n=7,r=e.length,a=0,o.label=1;case 1:if(!(a0&&(r=e.map((function(e){var r,a,i,l,s,u;u=e.queryType===K.PPL?n.interpolatePPLQuery(e.query||"",t):n.interpolateLuceneQuery(e.query||"",t);var d=o(o({},e),{datasource:n.name,query:u});try{for(var p=c(e.bucketAggs||[]),m=p.next();!m.done;m=p.next()){var f=m.value;if("filters"===f.type)try{for(var v=(i=void 0,c((null===(s=f.settings)||void 0===s?void 0:s.filters)||[])),g=v.next();!g.done;g=v.next()){var h=g.value;h.query=n.interpolateLuceneQuery(h.query,t)}}catch(e){i={error:e}}finally{try{g&&!g.done&&(l=v.return)&&l.call(v)}finally{if(i)throw i.error}}}}catch(e){r={error:e}}finally{try{m&&!m.done&&(a=p.return)&&a.call(p)}finally{if(r)throw r.error}}return d}))),r},t.prototype.testDatasource=function(){var e=this;return this.getFields("date").then((function(t){return v.a.find(t,{text:e.timeField})?{status:"success",message:"Index OK. Time field name OK."}:{status:"error",message:"No date field named "+e.timeField+" found"}}),(function(e){return e.message?{status:"error",message:e.message}:{status:"error",message:e.status}}))},t.prototype.getQueryHeader=function(e,t,n){var r={search_type:e,ignore_unavailable:!0,index:this.indexPattern.getIndexList(t,n)};return this.esVersion>=56&&this.esVersion<70&&(r.max_concurrent_shard_requests=this.maxConcurrentShardRequests),JSON.stringify(r)},t.prototype.getQueryDisplayText=function(e){var t=e.metrics,n=e.bucketAggs,r="";return e.query&&(r+="Query: "+e.query+", "),r+="Metrics: ",r+=null==t?void 0:t.reduce((function(e,t){var n,r,a=U[t.type].label+"(";return B(t)&&(a+=t.field),Q(t)&&(a+=null===(r=null===(n=t.settings)||void 0===n?void 0:n.script)||void 0===r?void 0:r.replace(new RegExp("params.","g"),"")),e+" "+(a+="), ")}),""),r+=null==n?void 0:n.reduce((function(e,t,n){var r="";return 0===n&&(r+=" Group by: "),r+=fe[t.type].label+"(",ye(t)&&(r+=t.field),e+" "+r+"), "}),""),e.alias&&(r+="Alias: "+e.alias),r},t.prototype.query=function(e){var t,n,a=this.interpolateVariablesInQueries(v.a.cloneDeep(e.targets),e.scopedVars),i=[],o=[];try{for(var l=c(a),s=l.next();!s.done;s=l.next()){var u=s.value;if(!u.hide)switch(u.queryType){case K.PPL:o.push(u);break;case K.Lucene:default:i.push(u)}}}catch(e){t={error:e}}finally{try{s&&!s.done&&(n=l.return)&&n.call(l)}finally{if(t)throw t.error}}var d=[];if(i.length){var m=this.executeLuceneQueries(i,e);d.push(m)}if(o.length){var f=this.executePPLQueries(o,e);d.push(f)}return 0===d.length?Object(g.of)({data:[],state:r.LoadingState.Done}):g.merge.apply(void 0,p(d))},t.prototype.executeLuceneQueries=function(e,t){var n,r,a=this,i="";try{for(var o=c(e),l=o.next();!l.done;l=o.next()){var s=l.value;i+=this.createLuceneQuery(s,t)}}catch(e){n={error:e}}finally{try{l&&!l.done&&(r=o.return)&&r.call(o)}finally{if(n)throw n.error}}return i=(i=i.replace(/"\$timeFrom"/g,t.range.from.valueOf().toString())).replace(/"\$timeTo"/g,t.range.to.valueOf().toString()),i=Object(me.getTemplateSrv)().replace(i,t.scopedVars),Object(g.from)(this.post(this.getMultiSearchUrl(),i)).pipe(I((function(t){var n,r,i=new re(e,t);if(e.some((function(e){return e.isLogsQuery}))){var o=i.getLogs(a.logMessageField,a.logLevelField);try{for(var l=c(o.data),s=l.next();!s.done;s=l.next()){Ee(s.value,a.dataLinks)}}catch(e){n={error:e}}finally{try{s&&!s.done&&(r=l.return)&&r.call(l)}finally{if(n)throw n.error}}return o}return i.getTimeSeries()})))},t.prototype.executePPLQueries=function(e,t){var n,a,i=this,o=[],l=function(n){var a=s.createPPLQuery(n,t),l=Object(r.dateTime)(t.range.from.valueOf()).format("YYYY-MM-DD HH:mm:ss"),u=Object(r.dateTime)(t.range.to.valueOf()).format("YYYY-MM-DD HH:mm:ss");a=(a=(a=a.replace(/\$timeTo/g,u)).replace(/\$timeFrom/g,l)).replace(/\$timestamp/g,"`"+s.timeField+"`"),o.push(Object(g.from)(s.post(s.getPPLUrl(),a)).pipe(I((function(t){var r,a,o=new re([n],t,K.PPL);if(e.some((function(e){return e.isLogsQuery}))){var l=o.getLogs(i.logMessageField,i.logLevelField);try{for(var s=(r=void 0,c(l.data)),u=s.next();!u.done;u=s.next()){Ee(u.value,i.dataLinks)}}catch(e){r={error:e}}finally{try{u&&!u.done&&(a=s.return)&&a.call(s)}finally{if(r)throw r.error}}return l}return e.some((function(e){return"table"===e.format}))?o.getTable():o.getTimeSeries()}))))},s=this;try{for(var u=c(e),d=u.next();!d.done;d=u.next()){l(d.value)}}catch(e){n={error:e}}finally{try{d&&!d.done&&(a=u.return)&&a.call(u)}finally{if(n)throw n.error}}return g.merge.apply(void 0,p(o))},t.prototype.createLuceneQuery=function(e,t){var n,r=Object(me.getTemplateSrv)().replace(e.query,t.scopedVars,"lucene"),a=Object(me.getTemplateSrv)().getAdhocFilters(this.name);r&&""!==r||(r="*"),e.isLogsQuery||function(e,t){return e&&e.metrics&&e.metrics.some((function(e){return e.type===t}))}(e,"logs")?(e.bucketAggs=[G()],e.metrics=[],e.isLogsQuery=!0,n=this.queryBuilder.getLogsQuery(e,a,r)):(e.alias&&(e.alias=Object(me.getTemplateSrv)().replace(e.alias,t.scopedVars,"lucene")),n=this.queryBuilder.build(e,a,r));var i=JSON.stringify(n),o=0===n.size&&this.esVersion<5?"count":"query_then_fetch";return this.getQueryHeader(o,t.range.from,t.range.to)+"\n"+i+"\n"},t.prototype.createPPLQuery=function(e,t){var n,r=Object(me.getTemplateSrv)().replace(e.query,t.scopedVars,"pipe"),a=Object(me.getTemplateSrv)().getAdhocFilters(this.name);return r||(r="source=`"+this.indexPattern.getPPLIndexPattern()+"`"),n=this.queryBuilder.buildPPLQuery(e,a,r),JSON.stringify(n)},t.prototype.isMetadataField=function(e){return xe.includes(e)},t.prototype.getFields=function(e,t){return s(this,void 0,Promise,(function(){var n,r=this;return u(this,(function(a){return n=this.esVersion,[2,this.get("/_mapping",t).then((function(t){var a={float:"number",double:"number",integer:"number",long:"number",date:"date",date_nanos:"date",string:"string",text:"string",scaled_float:"number",nested:"nested"},i=function(t,n){return!r.isMetadataField(n)&&(!e||(e===t.type||e===a[t.type]))},o=[],l={};function s(e){for(var t in e){var n=e[t];if(v.a.isObject(n.properties)&&(o.push(t),s(n.properties)),v.a.isObject(n.fields)&&(o.push(t),s(n.fields)),v.a.isString(n.type)){var r=o.concat(t).join(".");i(n,t)&&(l[r]={text:r,type:n.type})}}o.pop()}for(var u in t){var c=t[u];if(c&&c.mappings){var d=c.mappings;if(n<70)for(var p in d){s(d[p].properties)}else s(d.properties)}}return v.a.map(l,(function(e){return e}))}))]}))}))},t.prototype.getTerms=function(e,t){void 0===t&&(t=de());var n=this.esVersion>=5?"query_then_fetch":"count",r=this.getQueryHeader(n,t.from,t.to),a=JSON.stringify(this.queryBuilder.getTermsQuery(e));a=r+"\n"+(a=(a=a.replace(/\$timeFrom/g,t.from.valueOf().toString())).replace(/\$timeTo/g,t.to.valueOf().toString()))+"\n";var i=this.getMultiSearchUrl();return this.post(i,a).then((function(e){if(!e.responses[0].aggregations)return[];var t=e.responses[0].aggregations[1].buckets;return v.a.map(t,(function(e){return{text:e.key_as_string||e.key,value:e.key}}))}))},t.prototype.getMultiSearchUrl=function(){return this.esVersion>=70&&this.maxConcurrentShardRequests?"_msearch?max_concurrent_shard_requests="+this.maxConcurrentShardRequests:"_msearch"},t.prototype.getPPLUrl=function(){return"_opendistro/_ppl"},t.prototype.metricFindQuery=function(e,t){var n=null==t?void 0:t.range,r=JSON.parse(e);if(e){if("fields"===r.find)return r.field=Object(me.getTemplateSrv)().replace(r.field,{},"lucene"),this.getFields(e,n);if("terms"===r.find)return r.field=Object(me.getTemplateSrv)().replace(r.field,{},"lucene"),r.query=Object(me.getTemplateSrv)().replace(r.query||"*",{},"lucene"),this.getTerms(e,n)}return Promise.resolve([])},t.prototype.getTagKeys=function(){return this.getFields()},t.prototype.getTagValues=function(e){return this.getTerms({field:e.key,query:"*"})},t.prototype.targetContainsTemplate=function(e){var t,n,r,a;if(Object(me.getTemplateSrv)().variableExists(e.query)||Object(me.getTemplateSrv)().variableExists(e.alias))return!0;try{for(var i=c(e.bucketAggs),o=i.next();!o.done;o=i.next()){var l=o.value;if(Object(me.getTemplateSrv)().variableExists(l.field)||this.objectContainsTemplate(l.settings))return!0}}catch(e){t={error:e}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(t)throw t.error}}try{for(var s=c(e.metrics),u=s.next();!u.done;u=s.next()){var d=u.value;if(Object(me.getTemplateSrv)().variableExists(d.field)||this.objectContainsTemplate(d.settings)||this.objectContainsTemplate(d.meta))return!0}}catch(e){r={error:e}}finally{try{u&&!u.done&&(a=s.return)&&a.call(s)}finally{if(r)throw r.error}}return!1},t.prototype.isPrimitive=function(e){return null==e||!!["string","number","boolean"].some((function(e){return e===_e(!0)}))},t.prototype.objectContainsTemplate=function(e){var t,n,r,a;if(!e)return!1;try{for(var i=c(Object.keys(e)),o=i.next();!o.done;o=i.next()){var l=o.value;if(this.isPrimitive(e[l])){if(Object(me.getTemplateSrv)().variableExists(e[l]))return!0}else if(Array.isArray(e[l]))try{for(var s=(r=void 0,c(e[l])),u=s.next();!u.done;u=s.next()){var d=u.value;if(this.objectContainsTemplate(d))return!0}}catch(e){r={error:e}}finally{try{u&&!u.done&&(a=s.return)&&a.call(s)}finally{if(r)throw r.error}}else if(this.objectContainsTemplate(e[l]))return!0}}catch(e){t={error:e}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(t)throw t.error}}return!1},t.prototype.getSupportedQueryTypes=function(){return p([K.Lucene],this.pplEnabled?[K.PPL]:[])},t}(r.DataSourceApi);function Ee(e,t){var n,r,a,i=Object(me.getDataSourceSrv)();if(t.length){var o=function(e){var n=t.find((function(t){return e.name&&e.name.match(t.field)}));if(!n)return"continue";var r=void 0;if(n.datasourceUid){var o=i.getInstanceSettings(n.datasourceUid);r={title:"",url:"",internal:{query:{query:n.url},datasourceUid:n.datasourceUid,datasourceName:null!==(a=null==o?void 0:o.name)&&void 0!==a?a:"Data source not found"}}}else r={title:"",url:n.url};e.config=e.config||{},e.config.links=p(e.config.links||[],[r])};try{for(var l=c(e.fields),s=l.next();!s.done;s=l.next()){o(s.value)}}catch(e){n={error:e}}finally{try{s&&!s.done&&(r=l.return)&&r.call(l)}finally{if(n)throw n.error}}}}var Se=n(0),Te=n.n(Se),ke=n(1),Oe=ke.LegacyForms.Select,Fe=ke.LegacyForms.Input,Pe=ke.LegacyForms.FormField,je=ke.LegacyForms.Switch,Ie=[{label:"No pattern",value:"none"},{label:"Hourly",value:"Hourly",example:"[logstash-]YYYY.MM.DD.HH"},{label:"Daily",value:"Daily",example:"[logstash-]YYYY.MM.DD"},{label:"Weekly",value:"Weekly",example:"[logstash-]GGGG.WW"},{label:"Monthly",value:"Monthly",example:"[logstash-]YYYY.MM"},{label:"Yearly",value:"Yearly",example:"[logstash-]YYYY"}],De=[{label:"2.x",value:2},{label:"5.x",value:5},{label:"5.6+",value:56},{label:"6.0+",value:60},{label:"7.0+",value:70}],Ce=function(e){var t,n,r=e.value,a=e.onChange;return Te.a.createElement(Te.a.Fragment,null,Te.a.createElement("h3",{className:"page-heading"},"Elasticsearch details"),Te.a.createElement("div",{className:"gf-form-group"},Te.a.createElement("div",{className:"gf-form-inline"},Te.a.createElement("div",{className:"gf-form"},Te.a.createElement(Pe,{labelWidth:10,inputWidth:15,label:"Index name",value:r.jsonData.database||"",onChange:qe("database",r,a),placeholder:"es-index-name",required:!0})),Te.a.createElement("div",{className:"gf-form"},Te.a.createElement(Pe,{labelWidth:10,label:"Pattern",inputEl:Te.a.createElement(Oe,{options:Ie,onChange:Ae(r,a),value:Ie.find((function(e){return e.value===(void 0===r.jsonData.interval?"none":r.jsonData.interval)}))})}))),Te.a.createElement("div",{className:"gf-form max-width-25"},Te.a.createElement(Pe,{labelWidth:10,inputWidth:15,label:"Time field name",value:r.jsonData.timeField||"",onChange:qe("timeField",r,a),required:!0})),Te.a.createElement("div",{className:"gf-form"},Te.a.createElement(Pe,{labelWidth:10,label:"Version",inputEl:Te.a.createElement(Oe,{options:De,onChange:function(e){var t=function(e,t){if(5===e&&t<70)return 256;if(256===e&&t>=70)return 5;return e||Me(t)}(r.jsonData.maxConcurrentShardRequests,e.value);a(o(o({},r),{jsonData:o(o({},r.jsonData),{esVersion:e.value,maxConcurrentShardRequests:t})}))},value:De.find((function(e){return e.value===r.jsonData.esVersion}))})})),r.jsonData.esVersion>=56&&Te.a.createElement("div",{className:"gf-form max-width-30"},Te.a.createElement(Pe,{"aria-label":"Max concurrent Shard Requests input",labelWidth:15,label:"Max concurrent Shard Requests",value:r.jsonData.maxConcurrentShardRequests||"",onChange:qe("maxConcurrentShardRequests",r,a)})),Te.a.createElement("div",{className:"gf-form-inline"},Te.a.createElement("div",{className:"gf-form"},Te.a.createElement(Pe,{labelWidth:10,label:"Min time interval",inputEl:Te.a.createElement(Fe,{className:"width-6",value:r.jsonData.timeInterval||"",onChange:qe("timeInterval",r,a),placeholder:"10s",validationEvents:(t={},t[ke.EventsWithValidation.onBlur]=[Object(ke.regexValidation)(/^\d+(ms|[Mwdhmsy])$/,"Value is not valid, you can use number with time unit specifier: y, M, w, d, h, m, s")],t)}),tooltip:Te.a.createElement(Te.a.Fragment,null,"A lower limit for the auto group by time interval. Recommended to be set to write frequency, for example ",Te.a.createElement("code",null,"1m")," if your data is written every minute.")}))),Te.a.createElement("div",{className:"gf-form"},Te.a.createElement(je,{label:"PPL enabled",labelClass:"width-10",tooltip:"Allow Piped Processing Language as an alternative query syntax in the Elasticsearch query editor.",checked:null===(n=r.jsonData.pplEnabled)||void 0===n||n,onChange:Ve("pplEnabled",r,a)}))))},qe=function(e,t,n){return function(r){var a;n(o(o({},t),{jsonData:o(o({},t.jsonData),(a={},a[e]=r.currentTarget.value,a))}))}},Ve=function(e,t,n){return function(r){var a;n(o(o({},t),{jsonData:o(o({},t.jsonData),(a={},a[e]=r.currentTarget.checked,a))}))}},Ae=function(e,t){return function(n){var r,a=e.database,i="none"===n.value?void 0:n.value;if(!a||0===a.length||a.startsWith("[logstash-]")){var l="";if(void 0!==i){var s=Ie.find((function(e){return e.value===i}));s&&(l=null!==(r=s.example)&&void 0!==r?r:"")}t(o(o({},e),{database:l,jsonData:o(o({},e.jsonData),{interval:i})}))}else t(o(o({},e),{jsonData:o(o({},e.jsonData),{interval:i})}))}};function Me(e){return e>=70?5:256}var Le=ke.LegacyForms.FormField,Ne=function(e){var t=e.value,n=e.onChange,r=function(e){return function(r){var a;n(o(o({},t),((a={})[e]=r.currentTarget.value,a)))}};return Te.a.createElement(Te.a.Fragment,null,Te.a.createElement("h3",{className:"page-heading"},"Logs"),Te.a.createElement("div",{className:"gf-form-group"},Te.a.createElement("div",{className:"gf-form max-width-30"},Te.a.createElement(Le,{labelWidth:11,label:"Message field name",value:t.logMessageField,onChange:r("logMessageField"),placeholder:"_source"})),Te.a.createElement("div",{className:"gf-form max-width-30"},Te.a.createElement(Le,{labelWidth:11,label:"Level field name",value:t.logLevelField,onChange:r("logLevelField")}))))},Be=n(3),Re=function(e){var t=Object(Se.useRef)();return Object(Se.useEffect)((function(){t.current=e})),t.current},Qe=n(8),ze=function(e){var t=e.status,n=l(e,["status"]),a=function(e){e||(e=r.PluginSignatureStatus.invalid);switch(e){case r.PluginSignatureStatus.internal:return{text:"Core",icon:"cube",color:"blue",tooltip:"Core plugin that is bundled with Grafana"};case r.PluginSignatureStatus.valid:return{text:"Signed",icon:"lock",color:"green",tooltip:"Signed and verified plugin"};case r.PluginSignatureStatus.invalid:return{text:"Invalid signature",icon:"exclamation-triangle",color:"red",tooltip:"Invalid plugin signature"};case r.PluginSignatureStatus.modified:return{text:"Modified signature",icon:"exclamation-triangle",color:"red",tooltip:"Valid signature but content has been modified"};case r.PluginSignatureStatus.missing:return{text:"Missing signature",icon:"exclamation-triangle",color:"red",tooltip:"Missing plugin signature"}}return{text:"Unsigned",icon:"exclamation-triangle",color:"red",tooltip:"Unsigned external plugin"}}(t);return Te.a.createElement(ke.Badge,o({text:a.text,color:a.color,icon:a.icon,tooltip:a.tooltip},n))};ze.displayName="PluginSignatureBadge";var Ue,He,We,$e,Ye,Ge=function(e){function t(t){var n=e.call(this,t)||this;return n.dataSourceSrv=Object(me.getDataSourceSrv)(),n.state={},n.onChange=function(e){var t=n.dataSourceSrv.getInstanceSettings(e.value);t&&(n.props.onChange(t),n.setState({error:void 0}))},n}return i(t,e),t.prototype.componentDidMount=function(){var e=this.props.current;this.dataSourceSrv.getInstanceSettings(e)||this.setState({error:"Could not find data source "+e})},t.prototype.getCurrentValue=function(){var e=this.props,t=e.current,n=e.hideTextValue,r=e.noDefault;if(!t&&r)return null;var a=this.dataSourceSrv.getInstanceSettings(t);return a?{label:a.name.substr(0,37),value:a.name,imgUrl:a.meta.info.logos.small,hideText:n,meta:a.meta}:{label:(null!=t?t:"no name")+" - not found",value:t,imgUrl:"",hideText:n}},t.prototype.getDataSourceOptions=function(){var e=this.props,t=e.tracing,n=e.metrics,r=e.mixed,a=e.dashboard,i=e.variables,o=e.annotations,l=e.pluginId;return this.dataSourceSrv.getList({tracing:t,metrics:n,dashboard:a,mixed:r,variables:i,annotations:o,pluginId:l}).map((function(e){return{value:e.name,label:e.name+(e.isDefault?" (default)":""),imgUrl:e.meta.info.logos.small,meta:e.meta}}))},t.prototype.render=function(){var e=this.props,t=e.autoFocus,n=e.onBlur,a=e.openMenuOnFocus,i=e.placeholder,o=this.state.error,l=this.getDataSourceOptions(),s=this.getCurrentValue();return Te.a.createElement("div",{"aria-label":Qe.selectors.components.DataSourcePicker.container},Te.a.createElement(ke.Select,{className:"ds-picker select-container",isMulti:!1,isClearable:!1,backspaceRemovesValue:!1,onChange:this.onChange,options:l,autoFocus:t,onBlur:n,openMenuOnFocus:a,maxMenuHeight:500,menuPlacement:"bottom",placeholder:i,noOptionsMessage:"No datasources found",value:s,invalid:!!o,getOptionLabel:function(e){return e.meta&&((t=e.meta.signature)&&t!==r.PluginSignatureStatus.valid&&t!==r.PluginSignatureStatus.internal)&&e!==s?Te.a.createElement(ke.HorizontalGroup,{align:"center",justify:"space-between"},Te.a.createElement("span",null,e.label)," ",Te.a.createElement(ze,{status:e.meta.signature})):e.label||"";var t}}))},t.defaultProps={autoFocus:!1,openMenuOnFocus:!1,placeholder:"Select datasource"},t}(Se.PureComponent),Je=ke.LegacyForms.FormField,Ke=ke.LegacyForms.Switch,Ze=Object(ke.stylesFactory)((function(){return{firstRow:Object(Be.css)(Ue||(Ue=m(["\n display: flex;\n "],["\n display: flex;\n "]))),nameField:Object(Be.css)(He||(He=m(["\n flex: 2;\n "],["\n flex: 2;\n "]))),regexField:Object(Be.css)(We||(We=m(["\n flex: 3;\n "],["\n flex: 3;\n "]))),row:Object(Be.css)($e||($e=m(["\n display: flex;\n align-items: baseline;\n "],["\n display: flex;\n align-items: baseline;\n "])))}})),Xe=function(e){var t,n=e.value,r=e.onChange,a=e.onDelete,i=e.suggestions,l=e.className,s=Ze(),u=d(function(e){var t=d(Object(Se.useState)(!!e),2),n=t[0],r=t[1],a=Re(e);return Object(Se.useEffect)((function(){a||!e||n||r(!0),a&&!e&&n&&r(!1)}),[a,e,n]),[n,r]}(n.datasourceUid),2),c=u[0],p=u[1];return Te.a.createElement("div",{className:l},Te.a.createElement("div",{className:s.firstRow+" gf-form"},Te.a.createElement(Je,{className:s.nameField,labelWidth:6,inputWidth:null,label:"Field",type:"text",value:n.field,tooltip:"Can be exact field name or a regex pattern that will match on the field name.",onChange:(t="field",function(e){var a;r(o(o({},n),((a={})[t]=e.currentTarget.value,a)))})}),Te.a.createElement(ke.Button,{variant:"destructive",title:"Remove field",icon:"times",onClick:function(e){e.preventDefault(),a()}})),Te.a.createElement("div",{className:"gf-form"},Te.a.createElement(Je,{label:c?"Query":"URL",labelWidth:6,inputEl:Te.a.createElement(ke.DataLinkInput,{placeholder:c?"${__value.raw}":"http://example.com/${__value.raw}",value:n.url||"",onChange:function(e){return r(o(o({},n),{url:e}))},suggestions:i}),className:Object(Be.css)(Ye||(Ye=m(["\n width: 100%;\n "],["\n width: 100%;\n "])))})),Te.a.createElement("div",{className:s.row},Te.a.createElement(Ke,{labelClass:"width-6",label:"Internal link",checked:c,onChange:function(){c&&r(o(o({},n),{datasourceUid:void 0})),p(!c)}}),c&&Te.a.createElement(Ge,{tracing:!0,onChange:function(e){r(o(o({},n),{datasourceUid:e.uid}))},current:n.datasourceUid})))};var et,tt,nt,rt,at,it,ot,lt,st,ut=Object(ke.stylesFactory)((function(e){return{infoText:Object(Be.css)(et||(et=m(["\n padding-bottom: ",";\n color: ",";\n "],["\n padding-bottom: ",";\n color: ",";\n "])),e.spacing.md,e.colors.textWeak),dataLink:Object(Be.css)(tt||(tt=m(["\n margin-bottom: ",";\n "],["\n margin-bottom: ",";\n "])),e.spacing.sm)}})),ct=function(e){var t=e.value,n=e.onChange,a=Object(ke.useTheme)(),i=ut(a);return Te.a.createElement(Te.a.Fragment,null,Te.a.createElement("h3",{className:"page-heading"},"Data links"),Te.a.createElement("div",{className:i.infoText},"Add links to existing fields. Links will be shown in log row details next to the field value."),t&&t.length>0&&Te.a.createElement("div",{className:"gf-form-group"},t.map((function(e,a){return Te.a.createElement(Xe,{className:i.dataLink,key:a,value:e,onChange:function(e){var r=p(t);r.splice(a,1,e),n(r)},onDelete:function(){var e=p(t);e.splice(a,1),n(e)},suggestions:[{value:r.DataLinkBuiltInVars.valueRaw,label:"Raw value",documentation:"Raw value of the field",origin:r.VariableOrigin.Value}]})}))),Te.a.createElement(ke.Button,{variant:"secondary",className:Object(Be.css)(nt||(nt=m(["\n margin-right: 10px;\n "],["\n margin-right: 10px;\n "]))),icon:"plus",onClick:function(e){e.preventDefault();var r=p(t||[],[{field:"",url:""}]);n(r)}},"Add"))},dt=function(e,t,n){return Object(Se.useCallback)((function(r){e(n(t,r))}),[e,t,n])},pt=Object(Se.createContext)(void 0),mt=function(){var e=Object(Se.useContext)(pt);if(!e)throw new Error("Use DispatchContext first.");return e},ft="init",vt=function(e){return{type:"change_query",payload:{query:e}}},gt=function(e,t){switch(t.type){case"change_query":return t.payload.query;case ft:return"";default:return e}},ht=function(e,t){switch(t.type){case"change_alias_pattern":return t.payload.aliasPattern;case ft:return"";default:return e}},bt=function(e,t){switch(t.type){case"@metrics/add":return p(e,[Y(t.payload.id)]);case"@metrics/remove":var n=e.find((function(e){return e.id===t.payload.id})),r=p([n],function e(t,n){var r=n.filter((function(e){var n;return Q(e)?null===(n=e.pipelineVariables)||void 0===n?void 0:n.some((function(e){return e.pipelineAgg===t.id})):B(e)&&t.id===e.field}));return p(r,r.flatMap((function(t){return e(t,n)})))}(n,e)),a=e.filter((function(e){return!r.some((function(t){return t.id===e.id}))}));return 0===a.length?[Y("1")]:a;case"@metrics/change_type":return e.filter((function(e){return!U[t.payload.type].isSingleMetric||e.id===t.payload.id})).map((function(e){return e.id!==t.payload.id?e:o({id:e.id,type:t.payload.type},U[t.payload.type].defaults)}));case"@metrics/change_field":return e.map((function(e){return e.id!==t.payload.id?e:o(o({},e),{field:t.payload.field})}));case"@metrics/toggle_visibility":return e.map((function(e){return e.id!==t.payload.id?e:o(o({},e),{hide:!e.hide})}));case"@metrics/change_setting":return e.map((function(e){var n;if(e.id!==t.payload.metric.id)return e;if(z(e)){var r=ne(o(o({},e.settings),((n={})[t.payload.settingName]=t.payload.newValue,n)));return o(o({},e),{settings:o({},r)})}return e}));case"@metrics/change_meta":return e.map((function(e){var n;return e.id!==t.payload.metric.id?e:function(e){return U[e.type].hasMeta}(e)?o(o({},e),{meta:o(o({},e.meta),(n={},n[t.payload.meta]=t.payload.newValue,n))}):e}));case"@metrics/change_attr":return e.map((function(e){var n;return e.id!==t.payload.metric.id?e:o(o({},e),((n={})[t.payload.attribute]=t.payload.newValue,n))}));case ft:return[Y()];default:return e}},yt=function(e,t){switch(t.type){case"@bucketAggs/add":var n={id:t.payload.id,type:"terms",settings:fe.terms.defaultSettings},r=e[e.length-1];return"date_histogram"===(null==r?void 0:r.type)?p(e.slice(0,e.length-1),[n,r]):p(e,[n]);case"@bucketAggs/remove":return e.filter((function(e){return e.id!==t.payload.id}));case"@bucketAggs/change_type":return e.map((function(e){return e.id!==t.payload.id?e:{id:e.id,type:t.payload.newType,settings:fe[t.payload.newType].defaultSettings}}));case"@bucketAggs/change_field":return e.map((function(e){return e.id!==t.payload.id?e:o(o({},e),{field:t.payload.newField})}));case"@metrics/change_type":return U[t.payload.type].isSingleMetric?[]:0===e.length?[G()]:e;case"@bucketAggs/change_setting":return e.map((function(e){var n;if(e.id!==t.payload.bucketAgg.id)return e;var r=ne(o(o({},e.settings),((n={})[t.payload.settingName]=t.payload.newValue,n)));return o(o({},e),{settings:o({},r)})}));case ft:return[G()];default:return e}},_t=function(e,t){switch(t.type){case"change_query_type":return t.payload.queryType;case ft:return K.Lucene;default:return e}},xt=function(e,t){switch(t.type){case"change_format":return t.payload.format;case ft:return"table";default:return e}},wt=Object(Se.createContext)(void 0),Et=Object(Se.createContext)(void 0),St=function(e){var t,n=e.children,r=e.onChange,a=e.query,i=e.datasource,l=(t={query:gt,queryType:_t,alias:ht,metrics:bt,bucketAggs:yt,format:xt},function(e,n){var r={};for(var a in t)r[a]=t[a](e[a],n);return r}),s=dt((function(e){return r(o(o(o({},a),e),{timeField:i.timeField}))}),a,l);return a.metrics||a.bucketAggs?Te.a.createElement(wt.Provider,{value:i},Te.a.createElement(Et.Provider,{value:a},Te.a.createElement(pt.Provider,{value:s},n))):(s({type:ft}),null)},Tt=function(){var e=Object(Se.useContext)(Et);if(!e)throw new Error("use ElasticsearchProvider first.");return e},kt=function(){var e=Object(Se.useContext)(wt);if(!e)throw new Error("use ElasticsearchProvider first.");return e},Ot=((rt={})[K.Lucene]={label:"Lucene"},rt[K.PPL]={label:"PPL"},rt),Ft=Object(Be.css)(at||(at=m(["\n min-width: 150px;\n"],["\n min-width: 150px;\n"]))),Pt=function(e){var t,n,r=e.value,a=kt(),i=mt();return Te.a.createElement(ke.Segment,{className:Ft,options:(n=a.getSupportedQueryTypes(),Object.entries(Ot).filter((function(e){var t=d(e,2),r=t[0];return t[1],n.includes(r)})).map((function(e){var t=d(e,2),n=t[0];return{label:t[1].label,value:n}}))),onChange:function(e){return i({type:"change_query_type",payload:{queryType:e.value}})},value:(t=r,{label:Ot[t].label,value:t})})},jt=Object(ke.stylesFactory)((function(e,t){return{color:t&&Object(Be.css)(it||(it=m(["\n &,\n &:hover,\n label,\n a {\n color: ",";\n }\n "],["\n &,\n &:hover,\n label,\n a {\n color: ",";\n }\n "])),t?e.colors.textFaint:e.colors.text)}})),It=function(e,t){return{type:"@metrics/change_field",payload:{id:e,field:t}}},Dt=function(e,t,n){return{type:"@metrics/change_setting",payload:{metric:e,settingName:t,newValue:n}}},Ct=Object(Be.css)(ot||(ot=m(["\n clip: rect(0 0 0 0);\n clip-path: inset(50%);\n height: 1px;\n overflow: hidden;\n position: absolute;\n white-space: nowrap;\n width: 1px;\n"],["\n clip: rect(0 0 0 0);\n clip-path: inset(50%);\n height: 1px;\n overflow: hidden;\n position: absolute;\n white-space: nowrap;\n width: 1px;\n"]))),qt=function(e){var t=e.iconName,n=e.onClick,r=e.className,a=e.label,i=l(e,["iconName","onClick","className","label"]);return Te.a.createElement("button",o({className:Object(Be.cx)("gf-form-label gf-form-label--btn query-part",r),onClick:n},i),Te.a.createElement("span",{className:Ct},a),Te.a.createElement(ke.Icon,{name:t,"aria-hidden":"true"}))},Vt=function(e){var t=e.index,n=e.onAdd,r=e.onRemove,a=e.elements;return Te.a.createElement("div",{className:Object(Be.css)(lt||(lt=m(["\n display: flex;\n "],["\n display: flex;\n "])))},0===t&&Te.a.createElement(qt,{iconName:"plus",onClick:n,label:"add"}),a.length>=2&&Te.a.createElement(qt,{iconName:"minus",onClick:r,label:"remove"}))},At=Object(Be.css)(st||(st=m(["\n white-space: nowrap;\n"],["\n white-space: nowrap;\n"]))),Mt=function(e){return{label:te(e),value:e}},Lt=function(e){var t,n=e.options,r=e.onChange,a=e.className,i=e.value;return Te.a.createElement(ke.Segment,{className:Object(Be.cx)(a,At),options:(t=n,t.map(Mt)),onChange:r,placeholder:"Select Metric",value:i?Mt(n.find((function(e){return e.id===i}))):null})},Nt=function(e,t){switch(void 0===e&&(e=[]),t.type){case"@pipelineVariables/add":return p(e,[{name:"var1",pipelineAgg:""}]);case"@pipelineVariables/remove":return e.slice(0,t.payload.index).concat(e.slice(t.payload.index+1));case"@pipelineVariables/rename":return e.map((function(e,n){return n!==t.payload.index?e:o(o({},e),{name:t.payload.newName})}));case"@pipelineVariables/change_metric":return e.map((function(e,n){return n!==t.payload.index?e:o(o({},e),{pipelineAgg:t.payload.newMetric})}));default:return e}};function Bt(e){var t=e.label,n=e.settingName,r=e.metric,a=e.placeholder,i=e.tooltip,o=mt(),l=d(Object(Se.useState)(Object(f.uniqueId)("es-field-id-")),1)[0],s=r.settings;return Te.a.createElement(ke.InlineField,{label:t,labelWidth:16,tooltip:i},Te.a.createElement(ke.Input,{id:l,placeholder:a,onBlur:function(e){return o(Dt(r,n,e.target.value))},defaultValue:null==s?void 0:s[n]}))}var Rt,Qt,zt,Ut,Ht,Wt,$t,Yt,Gt,Jt,Kt,Zt,Xt,en,tn,nn=function(e){var t=e.value,n=e.previousMetrics,r=mt(),a=dt((function(e){return r({type:"@metrics/change_attr",payload:{metric:t,attribute:"pipelineVariables",newValue:e}})}),t.pipelineVariables,Nt);return Object(Se.useEffect)((function(){var e;(null===(e=t.pipelineVariables)||void 0===e?void 0:e.length)||a({type:"@pipelineVariables/add"})}),[]),Te.a.createElement(Te.a.Fragment,null,Te.a.createElement("div",{className:Object(Be.css)(Rt||(Rt=m(["\n display: flex;\n "],["\n display: flex;\n "])))},Te.a.createElement(ke.InlineLabel,{width:16},"Variables"),Te.a.createElement("div",{className:Object(Be.css)(Qt||(Qt=m(["\n display: grid;\n grid-template-columns: 1fr auto;\n row-gap: 4px;\n margin-bottom: 4px;\n "],["\n display: grid;\n grid-template-columns: 1fr auto;\n row-gap: 4px;\n margin-bottom: 4px;\n "])))},t.pipelineVariables.map((function(e,r){return Te.a.createElement(Se.Fragment,{key:e.name},Te.a.createElement("div",{className:Object(Be.css)(zt||(zt=m(["\n display: grid;\n column-gap: 4px;\n grid-template-columns: auto auto;\n "],["\n display: grid;\n column-gap: 4px;\n grid-template-columns: auto auto;\n "])))},Te.a.createElement(ke.Input,{defaultValue:e.name,placeholder:"Variable Name",onBlur:function(e){return a(function(e,t){return{type:"@pipelineVariables/rename",payload:{index:t,newName:e}}}(e.target.value,r))}}),Te.a.createElement(Lt,{onChange:function(e){return a(function(e,t){return{type:"@pipelineVariables/change_metric",payload:{index:t,newMetric:e}}}(e.value.id,r))},options:n,value:e.pipelineAgg})),Te.a.createElement(Vt,{index:r,elements:t.pipelineVariables||[],onAdd:function(){return a({type:"@pipelineVariables/add"})},onRemove:function(){return a(function(e){return{type:"@pipelineVariables/remove",payload:{index:e}}}(r))}}))})))),Te.a.createElement(Bt,{label:"Script",metric:t,settingName:"script",tooltip:"Elasticsearch v5.0 and above: Scripting language is Painless. Use params. to reference a variable. Elasticsearch pre-v5.0: Scripting language is per default Groovy if not changed. For Groovy use to reference a variable.",placeholder:"params.var1 / params.var2"}))},rn=Object(ke.stylesFactory)((function(e,t){return{wrapper:Object(Be.css)(Ut||(Ut=m(["\n display: flex;\n flex-direction: column;\n "],["\n display: flex;\n flex-direction: column;\n "]))),settingsWrapper:Object(Be.css)(Ht||(Ht=m(["\n padding-top: ",";\n "],["\n padding-top: ",";\n "])),e.spacing.xs),icon:Object(Be.css)(Wt||(Wt=m(["\n margin-right: ",";\n "],["\n margin-right: ",";\n "])),e.spacing.xs),button:Object(Be.css)(Yt||(Yt=m(["\n justify-content: start;\n ","\n "],["\n justify-content: start;\n ","\n "])),t&&Object(Be.css)($t||($t=m(["\n color: ",";\n "],["\n color: ",";\n "])),e.colors.textFaint))}})),an=function(e){var t=e.label,n=e.children,r=e.hidden,a=void 0!==r&&r,i=d(Object(Se.useState)(!1),2),o=i[0],l=i[1],s=rn(Object(ke.useTheme)(),a);return Te.a.createElement("div",{className:Object(Be.cx)(s.wrapper)},Te.a.createElement("button",{className:Object(Be.cx)("gf-form-label query-part",s.button,Ft),onClick:function(){return l(!o)},"aria-expanded":o},Te.a.createElement(ke.Icon,{name:o?"angle-down":"angle-right","aria-hidden":"true",className:s.icon}),t),o&&Te.a.createElement("div",{className:s.settingsWrapper},n))},on=function(e){var t,n,r,a,i,l,s,u,c,d,p,m,f,v,g,h,b,y,_,x,w,E=e.metric,S=mt();return Te.a.createElement(Te.a.Fragment,null,Te.a.createElement(ke.InlineField,{label:"Model"},Te.a.createElement(ke.Select,{onChange:function(e){return S(Dt(E,"model",e.value))},options:$,value:null===(t=E.settings)||void 0===t?void 0:t.model})),Te.a.createElement(ke.InlineField,{label:"Window"},Te.a.createElement(ke.Input,{onBlur:function(e){return S(Dt(E,"window",parseInt(e.target.value,10)))},defaultValue:null===(n=E.settings)||void 0===n?void 0:n.window})),Te.a.createElement(ke.InlineField,{label:"Predict"},Te.a.createElement(ke.Input,{onBlur:function(e){return S(Dt(E,"predict",parseInt(e.target.value,10)))},defaultValue:null===(r=E.settings)||void 0===r?void 0:r.predict})),function(e){var t;return"ewma"===(null===(t=e.settings)||void 0===t?void 0:t.model)}(E)&&Te.a.createElement(Te.a.Fragment,null,Te.a.createElement(ke.InlineField,{label:"Alpha"},Te.a.createElement(ke.Input,{onBlur:function(e){return S(Dt(E,"alpha",parseInt(e.target.value,10)))},defaultValue:null===(a=E.settings)||void 0===a?void 0:a.alpha})),Te.a.createElement(ke.InlineField,{label:"Minimize"},Te.a.createElement(ke.Switch,{onChange:function(e){return S(Dt(E,"minimize",e.target.checked))},checked:!!(null===(i=E.settings)||void 0===i?void 0:i.minimize)}))),function(e){var t;return"holt"===(null===(t=e.settings)||void 0===t?void 0:t.model)}(E)&&Te.a.createElement(Te.a.Fragment,null,Te.a.createElement(ke.InlineField,{label:"Alpha"},Te.a.createElement(ke.Input,{onBlur:function(e){var t;return S(Dt(E,"settings",o(o({},null===(t=E.settings)||void 0===t?void 0:t.settings),{alpha:parseInt(e.target.value,10)})))},defaultValue:null===(s=null===(l=E.settings)||void 0===l?void 0:l.settings)||void 0===s?void 0:s.alpha})),Te.a.createElement(ke.InlineField,{label:"Beta"},Te.a.createElement(ke.Input,{onBlur:function(e){var t;return S(Dt(E,"settings",o(o({},null===(t=E.settings)||void 0===t?void 0:t.settings),{beta:parseInt(e.target.value,10)})))},defaultValue:null===(c=null===(u=E.settings)||void 0===u?void 0:u.settings)||void 0===c?void 0:c.beta})),Te.a.createElement(ke.InlineField,{label:"Minimize"},Te.a.createElement(ke.Switch,{onChange:function(e){return S(Dt(E,"minimize",e.target.checked))},checked:!!(null===(d=E.settings)||void 0===d?void 0:d.minimize)}))),function(e){var t;return"holt_winters"===(null===(t=e.settings)||void 0===t?void 0:t.model)}(E)&&Te.a.createElement(Te.a.Fragment,null,Te.a.createElement(ke.InlineField,{label:"Alpha"},Te.a.createElement(ke.Input,{onBlur:function(e){var t;return S(Dt(E,"settings",o(o({},null===(t=E.settings)||void 0===t?void 0:t.settings),{alpha:parseInt(e.target.value,10)})))},defaultValue:null===(m=null===(p=E.settings)||void 0===p?void 0:p.settings)||void 0===m?void 0:m.alpha})),Te.a.createElement(ke.InlineField,{label:"Beta"},Te.a.createElement(ke.Input,{onBlur:function(e){var t;return S(Dt(E,"settings",o(o({},null===(t=E.settings)||void 0===t?void 0:t.settings),{beta:parseInt(e.target.value,10)})))},defaultValue:null===(v=null===(f=E.settings)||void 0===f?void 0:f.settings)||void 0===v?void 0:v.beta})),Te.a.createElement(ke.InlineField,{label:"Gamma"},Te.a.createElement(ke.Input,{onBlur:function(e){var t;return S(Dt(E,"settings",o(o({},null===(t=E.settings)||void 0===t?void 0:t.settings),{gamma:parseInt(e.target.value,10)})))},defaultValue:null===(h=null===(g=E.settings)||void 0===g?void 0:g.settings)||void 0===h?void 0:h.gamma})),Te.a.createElement(ke.InlineField,{label:"Period"},Te.a.createElement(ke.Input,{onBlur:function(e){var t;return S(Dt(E,"settings",o(o({},null===(t=E.settings)||void 0===t?void 0:t.settings),{period:parseInt(e.target.value,10)})))},defaultValue:null===(y=null===(b=E.settings)||void 0===b?void 0:b.settings)||void 0===y?void 0:y.period})),Te.a.createElement(ke.InlineField,{label:"Pad"},Te.a.createElement(ke.Switch,{onChange:function(e){var t;return S(Dt(E,"settings",o(o({},null===(t=E.settings)||void 0===t?void 0:t.settings),{pad:e.target.checked})))},checked:!!(null===(x=null===(_=E.settings)||void 0===_?void 0:_.settings)||void 0===x?void 0:x.pad)})),Te.a.createElement(ke.InlineField,{label:"Minimize"},Te.a.createElement(ke.Switch,{onChange:function(e){return S(Dt(E,"minimize",e.target.checked))},checked:!!(null===(w=E.settings)||void 0===w?void 0:w.minimize)}))))},ln={labelWidth:16},sn=function(e){var t,n,r,a,i,l=e.metric,s=e.previousMetrics,u=mt(),c=function(e){var t,n,r,a,i,o;switch(e.type){case"cardinality":return"Precision threshold: "+((null===(t=e.settings)||void 0===t?void 0:t.precision_threshold)||"");case"percentiles":return(null===(n=e.settings)||void 0===n?void 0:n.percents)&&(null===(a=null===(r=e.settings)||void 0===r?void 0:r.percents)||void 0===a?void 0:a.length)>=1?"Values: "+(null===(i=e.settings)||void 0===i?void 0:i.percents):"Percents: Default";case"extended_stats":var l=Object.entries(e.meta||{}).map((function(e){var t,n=d(e,2),r=n[0];return n[1]&&(null===(t=W.find(function(e){return function(t){return t.value===e}}(r)))||void 0===t?void 0:t.label)})).filter(Boolean);return"Stats: "+(l.length>0?l.join(", "):"None selected");case"raw_document":case"raw_data":return"Size: "+((null===(o=e.settings)||void 0===o?void 0:o.size)||500);default:return"Options"}}(l);return Te.a.createElement(an,{label:c,hidden:l.hide},"derivative"===l.type&&Te.a.createElement(Bt,{label:"Unit",metric:l,settingName:"unit"}),"cumulative_sum"===l.type&&Te.a.createElement(Bt,{label:"Format",metric:l,settingName:"format"}),"moving_avg"===l.type&&Te.a.createElement(on,{metric:l}),"moving_fn"===l.type&&Te.a.createElement(Te.a.Fragment,null,Te.a.createElement(Bt,{label:"Window",metric:l,settingName:"window"}),Te.a.createElement(Bt,{label:"Script",metric:l,settingName:"script"}),Te.a.createElement(Bt,{label:"Shift",metric:l,settingName:"shift"})),"bucket_script"===l.type&&Te.a.createElement(nn,{value:l,previousMetrics:s}),("raw_data"===l.type||"raw_document"===l.type)&&Te.a.createElement(ke.InlineField,o({label:"Size"},ln),Te.a.createElement(ke.Input,{onBlur:function(e){return u(Dt(l,"size",e.target.value))},defaultValue:null!==(n=null===(t=l.settings)||void 0===t?void 0:t.size)&&void 0!==n?n:null===(r=U.raw_data.defaults.settings)||void 0===r?void 0:r.size})),"cardinality"===l.type&&Te.a.createElement(Bt,{label:"Precision Threshold",metric:l,settingName:"precision_threshold"}),"extended_stats"===l.type&&Te.a.createElement(Te.a.Fragment,null,W.map((function(e){var t,n,r;return Te.a.createElement(un,{key:e.value,stat:e,onChange:function(t){return u(function(e,t,n){return{type:"@metrics/change_meta",payload:{metric:e,meta:t,newValue:n}}}(l,e.value,t))},value:void 0!==(null===(t=l.meta)||void 0===t?void 0:t[e.value])?!!(null===(n=l.meta)||void 0===n?void 0:n[e.value]):!!(null===(r=U.extended_stats.defaults.meta)||void 0===r?void 0:r[e.value])})})),Te.a.createElement(Bt,{label:"Sigma",metric:l,settingName:"sigma",placeholder:"3"})),"percentiles"===l.type&&Te.a.createElement(ke.InlineField,o({label:"Percentiles"},ln),Te.a.createElement(ke.Input,{onBlur:function(e){return u(Dt(l,"percents",e.target.value.split(",").filter(Boolean)))},defaultValue:(null===(a=l.settings)||void 0===a?void 0:a.percents)||(null===(i=U.percentiles.defaults.settings)||void 0===i?void 0:i.percents),placeholder:"1,5,25,50,75,95,99"})),function(e){return U[e.type].supportsInlineScript}(l)&&Te.a.createElement(Bt,{label:"Script",metric:l,settingName:"script",placeholder:"_value * 1"}),function(e){return U[e.type].supportsMissing}(l)&&Te.a.createElement(Bt,{label:"Missing",metric:l,settingName:"missing",tooltip:"The missing parameter defines how documents that are missing a value should be treated. By default\n they will be ignored but it is also possible to treat them as if they had a value"}))},un=function(e){var t=e.stat,n=e.onChange,r=e.value,a=d(Object(Se.useState)(Object(f.uniqueId)("es-field-id-")),1)[0];return Te.a.createElement(ke.InlineField,o({label:t.label},ln,{key:t.value}),Te.a.createElement(ke.Switch,{id:a,onChange:function(e){return n(e.target.checked)},value:r}))},cn=function(e){var t=e.value,n=e.text;return{label:n,value:""+(t||n)}},dn=function(e){return!U[e.type].isPipelineAgg},pn=function(e,t){var n=e.some(dn);return Object.entries(U).filter((function(e){var n=d(e,2),r=(n[0],n[1]),a=r.minVersion,i=void 0===a?0:a,o=r.maxVersion;return t>=i&&t<=(void 0===o?t:o)})).filter((function(e){var t=d(e,2),r=(t[0],t[1]);return n||!r.isPipelineAgg})).map((function(e){var t=d(e,2),n=t[0];return{label:t[1].label,value:n}}))},mn=function(e){var t,n=e.value,r=jt(Object(ke.useTheme)(),!!n.hide),a=kt(),i=Tt(),o=mt(),l=i.metrics.slice(0,i.metrics.findIndex((function(e){return e.id===n.id})));return Te.a.createElement(Te.a.Fragment,null,Te.a.createElement(ke.Segment,{className:Object(Be.cx)(r.color,Ft),options:pn(l,a.esVersion),onChange:function(e){return o((t=n.id,r=e.value,{type:"@metrics/change_type",payload:{id:t,type:r}}));var t,r},value:(t=n,{label:U[t.type].label,value:t.type})}),B(n)&&!R(n)&&Te.a.createElement(ke.SegmentAsync,{className:Object(Be.cx)(r.color,Ft),loadOptions:function(){return s(void 0,void 0,void 0,(function(){return u(this,(function(e){switch(e.label){case 0:return[4,function(){return"cardinality"===n.type?a.getFields():a.getFields("number")}()];case 1:return[2,e.sent().map(cn)]}}))}))},onChange:function(e){return o(It(n.id,e.value))},placeholder:"Select Field",value:n.field}),R(n)&&!Q(n)&&Te.a.createElement(Lt,{className:Object(Be.cx)(r.color,Ft),onChange:function(e){var t;return o(It(n.id,null===(t=e.value)||void 0===t?void 0:t.id))},options:l,value:n.field}),z(n)&&Te.a.createElement(sn,{metric:n,previousMetrics:l}))},fn=function(e){var t=e.children,n=e.label,r=e.onRemoveClick,a=e.onHideClick,i=e.hidden,o=void 0!==i&&i,l=e.disableRemove,s=void 0!==l&&l,u=Object(ke.useTheme)(),c=vn(u);return Te.a.createElement(ke.InlineFieldRow,null,Te.a.createElement(ke.InlineSegmentGroup,null,Te.a.createElement(ke.InlineLabel,{width:17,as:"div"},Te.a.createElement("span",null,n),Te.a.createElement("span",{className:c.iconWrapper},a&&Te.a.createElement(ke.IconButton,{name:o?"eye-slash":"eye",onClick:a,surface:"header",size:"sm","aria-pressed":o,"aria-label":"hide metric",className:c.icon}),r&&Te.a.createElement(ke.IconButton,{name:"trash-alt",surface:"header",size:"sm",className:c.icon,onClick:r||f.noop,disabled:s,"aria-label":"remove metric"})))),t)},vn=Object(ke.stylesFactory)((function(e){return{iconWrapper:Object(Be.css)(Gt||(Gt=m(["\n display: flex;\n "],["\n display: flex;\n "]))),icon:Object(Be.css)(Jt||(Jt=m(["\n color: ",";\n margin-left: ",";\n "],["\n color: ",";\n margin-left: ",";\n "])),e.colors.textWeak,e.spacing.xxs)}})),gn=function(e){var t=e.nextId,n=mt(),r=Tt().metrics,a=(null==r?void 0:r.length)||0;return Te.a.createElement(Te.a.Fragment,null,null==r?void 0:r.map((function(e,r){return Te.a.createElement(fn,{key:e.id,label:"Metric ("+e.id+")",hidden:e.hide,onHideClick:function(){return n({type:"@metrics/toggle_visibility",payload:{id:e.id}})},onRemoveClick:function(){return n({type:"@metrics/remove",payload:{id:e.id}})},disableRemove:!(a>1)},Te.a.createElement(mn,{value:e}),!U[e.type].isSingleMetric&&0===r&&Te.a.createElement(qt,{iconName:"plus",onClick:function(){return n({type:"@metrics/add",payload:{id:t}})},label:"add"}))})))},hn=function(e,t,n){return{type:"@bucketAggs/change_setting",payload:{bucketAgg:e,settingName:t,newValue:n}}},bn=function(e,t){return{type:"@bucketAggregations/filter/change",payload:{index:e,filter:t}}},yn=function(e,t){switch(void 0===e&&(e=[]),t.type){case"@bucketAggregations/filter/add":return p(e,[{label:"",query:"*"}]);case"@bucketAggregations/filter/remove":return e.slice(0,t.payload.index).concat(e.slice(t.payload.index+1));case"@bucketAggregations/filter/change":return e.map((function(e,n){return n!==t.payload.index?e:t.payload.filter}))}},_n=function(e){var t,n,r=e.value,a=mt(),i=dt((function(e){return a(hn(r,"filters",e))}),null===(t=r.settings)||void 0===t?void 0:t.filters,yn);return Object(Se.useEffect)((function(){var e,t;(null===(t=null===(e=r.settings)||void 0===e?void 0:e.filters)||void 0===t?void 0:t.length)||i({type:"@bucketAggregations/filter/add"})}),[]),Te.a.createElement(Te.a.Fragment,null,Te.a.createElement("div",{className:Object(Be.css)(Kt||(Kt=m(["\n display: flex;\n flex-direction: column;\n "],["\n display: flex;\n flex-direction: column;\n "])))},null===(n=r.settings)||void 0===n?void 0:n.filters.map((function(e,t){var n;return Te.a.createElement("div",{key:t,className:Object(Be.css)(Zt||(Zt=m(["\n display: flex;\n "],["\n display: flex;\n "])))},Te.a.createElement("div",{className:Object(Be.css)(Xt||(Xt=m(["\n width: 250px;\n "],["\n width: 250px;\n "])))},Te.a.createElement(ke.InlineField,{label:"Query",labelWidth:10},Te.a.createElement(ke.QueryField,{placeholder:"Lucene Query",portalOrigin:"elasticsearch",onBlur:function(){},onChange:function(n){return i(bn(t,o(o({},e),{query:n})))},query:e.query}))),Te.a.createElement(ke.InlineField,{label:"Label",labelWidth:10},Te.a.createElement(ke.Input,{placeholder:"Label",onBlur:function(n){return i(bn(t,o(o({},e),{label:n.target.value})))},defaultValue:e.label})),Te.a.createElement(Vt,{index:t,elements:(null===(n=r.settings)||void 0===n?void 0:n.filters)||[],onAdd:function(){return i({type:"@bucketAggregations/filter/add"})},onRemove:function(){return i(function(e){return{type:"@bucketAggregations/filter/remove",payload:{index:e}}}(t))}}))}))))},xn=function(e){return function(t){return t.value===e}},wn={labelWidth:16},En=function(e){var t,n,r,a,i,l,s,u,c,d,m,f,v,g,h,b,y,_,x,w,E,S,T,k,O=e.bucketAgg,F=mt(),P=Tt().metrics,j=function(e){var t,n,r,a,i,o,l,s,u,c,d,p,m,f=Tt().metrics;switch(e.type){case"terms":var v=(null===(t=e.settings)||void 0===t?void 0:t.order)||"desc",g=(null===(n=e.settings)||void 0===n?void 0:n.size)||"10",h=parseInt((null===(r=e.settings)||void 0===r?void 0:r.min_doc_count)||"0",10),b=(null===(a=e.settings)||void 0===a?void 0:a.orderBy)||"_term",y="";if("0"!==g)y=(null===(i=ve.find(xn(v)))||void 0===i?void 0:i.label)+" "+g+", ";h>0&&(y+="Min Doc Count: "+h+", "),y+="Order by: ";var _=he.find(xn(b));if(_)y+=_.label;else{var x=null==f?void 0:f.find((function(e){return e.id===b}));y+=x?te(x):"metric not found"}return"0"===g&&(y+=" ("+v+")"),y;case"histogram":return"Interval: "+(w=(null===(o=e.settings)||void 0===o?void 0:o.interval)||1e3)+((h=(null===(l=e.settings)||void 0===l?void 0:l.min_doc_count)||1)>0?", Min Doc Count: "+h:"");case"filters":return"Filter Queries ("+((null===(s=e.settings)||void 0===s?void 0:s.filters)||(null===(u=fe.filters.defaultSettings)||void 0===u?void 0:u.filters)).length+")";case"geohash_grid":return"Precision: "+Math.max(Math.min(parseInt((null===(c=e.settings)||void 0===c?void 0:c.precision)||"5",10),12),1);case"date_histogram":var w=(null===(d=e.settings)||void 0===d?void 0:d.interval)||"auto",E=(h=(null===(p=e.settings)||void 0===p?void 0:p.min_doc_count)||0,(null===(m=e.settings)||void 0===m?void 0:m.trimEdges)||0);y="Interval: "+w;return h>0&&(y+=", Min Doc Count: "+h),E>0&&(y+=", Trim edges: "+E),y;default:return"Settings"}}(O),I=p(he,(P||[]).map((function(e){return{label:te(e),value:e.id}})));return Te.a.createElement(an,{label:j},"terms"===O.type&&Te.a.createElement(Te.a.Fragment,null,Te.a.createElement(ke.InlineField,o({label:"Order"},wn),Te.a.createElement(ke.Select,{onChange:function(e){return F(hn(O,"order",e.value))},options:ve,value:(null===(t=O.settings)||void 0===t?void 0:t.order)||(null===(n=fe[O.type].defaultSettings)||void 0===n?void 0:n.order)})),Te.a.createElement(ke.InlineField,o({label:"Size"},wn),Te.a.createElement(ke.Select,{onChange:function(e){return F(hn(O,"size",e.value))},options:ge,value:(null===(r=O.settings)||void 0===r?void 0:r.size)||(null===(a=fe[O.type].defaultSettings)||void 0===a?void 0:a.size),allowCustomValue:!0})),Te.a.createElement(ke.InlineField,o({label:"Min Doc Count"},wn),Te.a.createElement(ke.Input,{onBlur:function(e){return F(hn(O,"min_doc_count",e.target.value))},defaultValue:(null===(i=O.settings)||void 0===i?void 0:i.min_doc_count)||(null===(l=fe[O.type].defaultSettings)||void 0===l?void 0:l.min_doc_count)})),Te.a.createElement(ke.InlineField,o({label:"Order By"},wn),Te.a.createElement(ke.Select,{onChange:function(e){return F(hn(O,"orderBy",e.value))},options:I,value:(null===(s=O.settings)||void 0===s?void 0:s.orderBy)||(null===(u=fe[O.type].defaultSettings)||void 0===u?void 0:u.orderBy)})),Te.a.createElement(ke.InlineField,o({label:"Missing"},wn),Te.a.createElement(ke.Input,{onBlur:function(e){return F(hn(O,"missing",e.target.value))},defaultValue:(null===(c=O.settings)||void 0===c?void 0:c.missing)||(null===(d=fe[O.type].defaultSettings)||void 0===d?void 0:d.missing)}))),"geohash_grid"===O.type&&Te.a.createElement(ke.InlineField,o({label:"Precision"},wn),Te.a.createElement(ke.Input,{onBlur:function(e){return F(hn(O,"precision",e.target.value))},defaultValue:(null===(m=O.settings)||void 0===m?void 0:m.precision)||(null===(f=fe[O.type].defaultSettings)||void 0===f?void 0:f.precision)})),"date_histogram"===O.type&&Te.a.createElement(Te.a.Fragment,null,Te.a.createElement(ke.InlineField,o({label:"Interval"},wn),Te.a.createElement(ke.Select,{onChange:function(e){return F(hn(O,"interval",e.value))},options:be,value:(null===(v=O.settings)||void 0===v?void 0:v.interval)||(null===(g=fe[O.type].defaultSettings)||void 0===g?void 0:g.interval),allowCustomValue:!0})),Te.a.createElement(ke.InlineField,o({label:"Min Doc Count"},wn),Te.a.createElement(ke.Input,{onBlur:function(e){return F(hn(O,"min_doc_count",e.target.value))},defaultValue:(null===(h=O.settings)||void 0===h?void 0:h.min_doc_count)||(null===(b=fe[O.type].defaultSettings)||void 0===b?void 0:b.min_doc_count)})),Te.a.createElement(ke.InlineField,o({label:"Trim Edges"},wn,{tooltip:"Trim the edges on the timeseries datapoints"}),Te.a.createElement(ke.Input,{onBlur:function(e){return F(hn(O,"trimEdges",e.target.value))},defaultValue:(null===(y=O.settings)||void 0===y?void 0:y.trimEdges)||(null===(_=fe[O.type].defaultSettings)||void 0===_?void 0:_.trimEdges)})),Te.a.createElement(ke.InlineField,o({label:"Offset"},wn,{tooltip:"Change the start value of each bucket by the specified positive (+) or negative offset (-) duration, such as 1h for an hour, or 1d for a day"}),Te.a.createElement(ke.Input,{onBlur:function(e){return F(hn(O,"offset",e.target.value))},defaultValue:(null===(x=O.settings)||void 0===x?void 0:x.offset)||(null===(w=fe[O.type].defaultSettings)||void 0===w?void 0:w.offset)}))),"histogram"===O.type&&Te.a.createElement(Te.a.Fragment,null,Te.a.createElement(ke.InlineField,o({label:"Interval"},wn),Te.a.createElement(ke.Input,{onBlur:function(e){return F(hn(O,"interval",e.target.value))},defaultValue:(null===(E=O.settings)||void 0===E?void 0:E.interval)||(null===(S=fe[O.type].defaultSettings)||void 0===S?void 0:S.interval)})),Te.a.createElement(ke.InlineField,o({label:"Min Doc Count"},wn),Te.a.createElement(ke.Input,{onBlur:function(e){return F(hn(O,"min_doc_count",e.target.value))},defaultValue:(null===(T=O.settings)||void 0===T?void 0:T.min_doc_count)||(null===(k=fe[O.type].defaultSettings)||void 0===k?void 0:k.min_doc_count)}))),"filters"===O.type&&Te.a.createElement(_n,{value:O}))},Sn=Object.entries(fe).map((function(e){var t=d(e,2),n=t[0];return{label:t[1].label,value:n}})),Tn=function(e){var t=e.value,n=e.text;return{label:n,value:""+(t||n)}},kn=function(e){var t,n=e.value,r=kt(),a=mt();return Te.a.createElement(Te.a.Fragment,null,Te.a.createElement(ke.Segment,{className:Ft,options:Sn,onChange:function(e){return a((t=n.id,r=e.value,{type:"@bucketAggs/change_type",payload:{id:t,newType:r}}));var t,r},value:(t=n,{label:fe[t.type].label,value:t.type})}),ye(n)&&Te.a.createElement(ke.SegmentAsync,{className:Ft,loadOptions:function(){return s(void 0,void 0,void 0,(function(){return u(this,(function(e){switch(e.label){case 0:return[4,function(){switch(n.type){case"date_histogram":return r.getFields("date");case"geohash_grid":return r.getFields("geo_point");default:return r.getFields()}}()];case 1:return[2,e.sent().map(Tn)]}}))}))},onChange:function(e){return a((t=n.id,r=e.value,{type:"@bucketAggs/change_field",payload:{id:t,newField:r}}));var t,r},placeholder:"Select Field",value:n.field}),Te.a.createElement(En,{bucketAgg:n}))},On=function(e){var t=e.nextId,n=mt(),r=Tt().bucketAggs,a=(null==r?void 0:r.length)||0;return Te.a.createElement(Te.a.Fragment,null,r.map((function(e,r){return Te.a.createElement(fn,{key:e.id,label:0===r?"Group By":"Then By",onRemoveClick:function(){return n({type:"@bucketAggs/remove",payload:{id:e.id}})},disableRemove:!(a>1)},Te.a.createElement(kn,{value:e}),0===r&&Te.a.createElement(qt,{iconName:"plus",onClick:function(){return n({type:"@bucketAggs/add",payload:{id:t}})},label:"add"}))})))},Fn=function(e){return e.id},Pn=function(e){return parseInt(e,10)},jn=function(e){var t=e.query,n=mt(),r=function(){var e=Tt(),t=e.metrics,n=e.bucketAggs;return Object(Se.useMemo)((function(){return(Math.max.apply(Math,p(p((null==t?void 0:t.map(Fn))||["0"],(null==n?void 0:n.map(Fn))||["0"]).map(Pn)))+1).toString()}),[t,n])}();return Te.a.createElement(Te.a.Fragment,null,Te.a.createElement(ke.InlineFieldRow,null,Te.a.createElement(ke.InlineField,{label:"Query",labelWidth:17,grow:!0},Te.a.createElement(Te.a.Fragment,null,Te.a.createElement(Pt,{value:K.Lucene}),Te.a.createElement(ke.QueryField,{query:t,onBlur:function(){},onChange:function(e){return n(vt(e))},placeholder:"Lucene Query",portalOrigin:"elasticsearch"}))),Te.a.createElement(ke.InlineField,{label:"Alias",labelWidth:15},Te.a.createElement(ke.Input,{placeholder:"Alias Pattern",onBlur:function(e){return n({type:"change_alias_pattern",payload:{aliasPattern:e.currentTarget.value}})}}))),Te.a.createElement(gn,{nextId:r}),Te.a.createElement(On,{nextId:r}))},In={table:{label:"Table"},logs:{label:"Logs"},time_series:{label:"Time series"}},Dn=Object.entries(In).map((function(e){var t=d(e,2),n=t[0];return{label:t[1].label,value:n}})),Cn=function(e){var t,n=e.value,r=mt();return Te.a.createElement(ke.Segment,{className:Ft,options:Dn,onChange:function(e){return r({type:"change_format",payload:{format:e.value}})},value:(t=n,{label:In[t].label,value:t})})},qn=Object(ke.stylesFactory)((function(e){return{icon:Object(Be.css)(en||(en=m(["\n margin-right: ",";\n "],["\n margin-right: ",";\n "])),e.spacing.xs),button:Object(Be.css)(tn||(tn=m(["\n justify-content: start;\n "],["\n justify-content: start;\n "])))}})),Vn=function(e){var t=e.label,n=e.open,r=e.onClick,a=qn(Object(ke.useTheme)());return Te.a.createElement("button",{className:Object(Be.cx)("gf-form-label",a.button,Ft),onClick:r,"aria-expanded":n},Te.a.createElement(ke.Icon,{name:n?"angle-down":"angle-right","aria-hidden":"true",className:a.icon}),t)},An=function(){return Te.a.createElement("div",{className:"gf-form grafana-info-box"},Te.a.createElement("div",null,Te.a.createElement("h5",null,"Table"),Te.a.createElement("ul",null,Te.a.createElement("li",null,"return any set of columns")),Te.a.createElement("br",null),Te.a.createElement("h5",null,"Logs"),Te.a.createElement("ul",null,Te.a.createElement("li",null,"return any set of columns")),Te.a.createElement("br",null),Te.a.createElement("h5",null,"Time series"),Te.a.createElement("ul",null,Te.a.createElement("li",null,"return column as date, datetime, or timestamp"),Te.a.createElement("li",null,"return column with numeric datatype as values")),Te.a.createElement("br",null),"Example PPL query for time series:",Te.a.createElement("br",null),Te.a.createElement("code",null,"source= | eval dateValue=timestamp(timestamp) | stats count(response) by dateValue")))},Mn=function(){var e=Tt().format,t=d(Object(Se.useState)(!1),2),n=t[0],r=t[1];return Te.a.createElement(Te.a.Fragment,null,Te.a.createElement(fn,{label:"Format"},Te.a.createElement(Cn,{value:null!=e?e:"table"}),Te.a.createElement(Vn,{label:"Show help",open:n,onClick:function(){return r(!n)}})),n&&Te.a.createElement(An,null))},Ln=function(e){var t=e.query,n=mt();return Te.a.createElement(Te.a.Fragment,null,Te.a.createElement(ke.InlineFieldRow,null,Te.a.createElement(ke.InlineField,{label:"Query",labelWidth:17,grow:!0},Te.a.createElement(Te.a.Fragment,null,Te.a.createElement(Pt,{value:K.PPL}),Te.a.createElement(ke.QueryField,{query:t,onBlur:function(){},onChange:function(e){return n(vt(e))},placeholder:"PPL Query",portalOrigin:"elasticsearch"})))),Te.a.createElement(Mn,null))},Nn=function(e){var t=e.value;switch(t.queryType){case K.PPL:return Te.a.createElement(Ln,{query:t.query});default:return Te.a.createElement(jn,{query:t.query})}};n.d(t,"plugin",(function(){return Rn}));var Bn=function(){function e(){}return e.templateUrl="partials/annotations.editor.html",e}(),Rn=new r.DataSourcePlugin(we).setQueryEditor((function(e){var t=e.query,n=e.onChange,r=e.datasource;return Te.a.createElement(St,{datasource:r,onChange:n,query:t},Te.a.createElement(Nn,{value:t}))})).setConfigEditor((function(e){var t=e.options,n=e.onOptionsChange;return Object(Se.useEffect)((function(){var e,r=t.jsonData.esVersion||5;n(o(o({},t),{jsonData:o(o({},t.jsonData),{timeField:t.jsonData.timeField||"@timestamp",esVersion:r,maxConcurrentShardRequests:t.jsonData.maxConcurrentShardRequests||Me(r),logMessageField:t.jsonData.logMessageField||"",logLevelField:t.jsonData.logLevelField||"",pplEnabled:null===(e=t.jsonData.pplEnabled)||void 0===e||e})}))}),[]),Te.a.createElement(Te.a.Fragment,null,Te.a.createElement(ke.DataSourceHttpSettings,{defaultUrl:"http://localhost:9200",dataSourceConfig:t,showAccessOptions:!0,onChange:n,sigV4AuthToggleEnabled:me.config.sigV4AuthEnabled}),Te.a.createElement(Ce,{value:t,onChange:n}),Te.a.createElement(Ne,{value:t.jsonData,onChange:function(e){return n(o(o({},t),{jsonData:e}))}}),Te.a.createElement(ct,{value:t.jsonData.dataLinks,onChange:function(e){n(o(o({},t),{jsonData:o(o({},t.jsonData),{dataLinks:e})}))}}))})).setAnnotationQueryCtrl(Bn)}])})); +//# sourceMappingURL=module.js.map \ No newline at end of file diff --git a/dist/module.js.LICENSE.txt b/dist/module.js.LICENSE.txt new file mode 100644 index 0000000..c18ab1d --- /dev/null +++ b/dist/module.js.LICENSE.txt @@ -0,0 +1,14 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ diff --git a/dist/module.js.map b/dist/module.js.map new file mode 100644 index 0000000..7bc4ca9 --- /dev/null +++ b/dist/module.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["webpack:///webpack/bootstrap","webpack:///external \"react\"","webpack:///external \"@grafana/ui\"","webpack:///external \"@grafana/data\"","webpack:///external \"emotion\"","webpack:///external \"lodash\"","webpack:///external \"@grafana/runtime\"","webpack:///external \"rxjs\"","webpack:///external \"prismjs\"","webpack:///../node_modules/@grafana/e2e-selectors/index.js","webpack:///../node_modules/@grafana/e2e-selectors/index.production.js","webpack:///../node_modules/tslib/tslib.es6.js","webpack:///../node_modules/rxjs/node_modules/tslib/tslib.es6.js","webpack:///../node_modules/rxjs/_esm5/internal/util/isFunction.js","webpack:///../node_modules/rxjs/_esm5/internal/config.js","webpack:///../node_modules/rxjs/_esm5/internal/util/hostReportError.js","webpack:///../node_modules/rxjs/_esm5/internal/Observer.js","webpack:///../node_modules/rxjs/_esm5/internal/util/isArray.js","webpack:///../node_modules/rxjs/_esm5/internal/util/UnsubscriptionError.js","webpack:///../node_modules/rxjs/_esm5/internal/Subscription.js","webpack:///../node_modules/rxjs/_esm5/internal/util/isObject.js","webpack:///../node_modules/rxjs/_esm5/internal/symbol/rxSubscriber.js","webpack:///../node_modules/rxjs/_esm5/internal/Subscriber.js","webpack:///../node_modules/rxjs/_esm5/internal/operators/map.js","webpack:///./grammar.ts","webpack:///./language_provider.ts","webpack:///./dependencies/flatten.ts","webpack:///./components/QueryEditor/MetricAggregationsEditor/aggregations.ts","webpack:///./components/QueryEditor/MetricAggregationsEditor/utils.ts","webpack:///./components/QueryEditor/MetricAggregationsEditor/SettingsEditor/BucketScriptSettingsEditor/utils.ts","webpack:///./query_def.ts","webpack:///./dependencies/table_model.ts","webpack:///./types.ts","webpack:///./utils.ts","webpack:///./elastic_response.ts","webpack:///./index_pattern.ts","webpack:///./query_builder.ts","webpack:///./components/QueryEditor/BucketAggregationsEditor/utils.ts","webpack:///./components/QueryEditor/BucketAggregationsEditor/SettingsEditor/FiltersSettingsEditor/utils.ts","webpack:///./components/QueryEditor/BucketAggregationsEditor/aggregations.ts","webpack:///./datasource.ts","webpack:///./configuration/ElasticDetails.tsx","webpack:///./configuration/LogsConfig.tsx","webpack:///../node_modules/react-use/esm/usePrevious.js","webpack:///./dependencies/PluginSignatureBadge.tsx","webpack:///./dependencies/DataSourcePicker.tsx","webpack:///./configuration/DataLink.tsx","webpack:///./configuration/DataLinks.tsx","webpack:///./hooks/useStatelessReducer.ts","webpack:///./components/QueryEditor/state.ts","webpack:///./components/QueryEditor/MetricAggregationsEditor/state/reducer.ts","webpack:///./components/QueryEditor/MetricAggregationsEditor/state/types.ts","webpack:///./components/QueryEditor/BucketAggregationsEditor/state/reducer.ts","webpack:///./components/QueryEditor/BucketAggregationsEditor/state/types.ts","webpack:///./components/QueryEditor/QueryTypeEditor/state.ts","webpack:///./components/QueryEditor/PPLFormatEditor/state.ts","webpack:///./components/QueryEditor/ElasticsearchQueryContext.tsx","webpack:///./components/QueryEditor/QueryTypeEditor/utils.ts","webpack:///./components/QueryEditor/styles.ts","webpack:///./components/QueryEditor/QueryTypeEditor/index.tsx","webpack:///./components/QueryEditor/MetricAggregationsEditor/styles.ts","webpack:///./components/QueryEditor/MetricAggregationsEditor/state/actions.ts","webpack:///./components/IconButton.tsx","webpack:///./components/AddRemove.tsx","webpack:///./components/MetricPicker.tsx","webpack:///./components/QueryEditor/MetricAggregationsEditor/SettingsEditor/BucketScriptSettingsEditor/state/reducer.ts","webpack:///./components/QueryEditor/MetricAggregationsEditor/SettingsEditor/BucketScriptSettingsEditor/state/types.ts","webpack:///./components/QueryEditor/MetricAggregationsEditor/SettingsEditor/SettingField.tsx","webpack:///./components/QueryEditor/MetricAggregationsEditor/SettingsEditor/BucketScriptSettingsEditor/index.tsx","webpack:///./components/QueryEditor/MetricAggregationsEditor/SettingsEditor/BucketScriptSettingsEditor/state/actions.ts","webpack:///./components/QueryEditor/SettingsEditorContainer.tsx","webpack:///./components/QueryEditor/MetricAggregationsEditor/SettingsEditor/MovingAverageSettingsEditor.tsx","webpack:///./components/QueryEditor/MetricAggregationsEditor/SettingsEditor/index.tsx","webpack:///./components/QueryEditor/MetricAggregationsEditor/SettingsEditor/useDescription.ts","webpack:///./components/QueryEditor/MetricAggregationsEditor/MetricEditor.tsx","webpack:///./components/QueryEditor/QueryEditorRow.tsx","webpack:///./components/QueryEditor/MetricAggregationsEditor/index.tsx","webpack:///./components/QueryEditor/BucketAggregationsEditor/state/actions.ts","webpack:///./components/QueryEditor/BucketAggregationsEditor/SettingsEditor/FiltersSettingsEditor/state/actions.ts","webpack:///./components/QueryEditor/BucketAggregationsEditor/SettingsEditor/FiltersSettingsEditor/state/types.ts","webpack:///./components/QueryEditor/BucketAggregationsEditor/SettingsEditor/FiltersSettingsEditor/state/reducer.ts","webpack:///./components/QueryEditor/BucketAggregationsEditor/SettingsEditor/FiltersSettingsEditor/index.tsx","webpack:///./components/QueryEditor/BucketAggregationsEditor/SettingsEditor/useDescription.ts","webpack:///./components/QueryEditor/BucketAggregationsEditor/SettingsEditor/index.tsx","webpack:///./components/QueryEditor/BucketAggregationsEditor/BucketAggregationEditor.tsx","webpack:///./components/QueryEditor/BucketAggregationsEditor/index.tsx","webpack:///./hooks/useNextId.ts","webpack:///./components/QueryEditor/LuceneEditor.tsx","webpack:///./components/QueryEditor/PPLFormatEditor/utils.ts","webpack:///./components/QueryEditor/PPLFormatEditor/SettingsEditor.tsx","webpack:///./components/QueryEditor/PPLFormatEditor/OpenCloseButton.tsx","webpack:///./components/QueryEditor/PPLFormatEditor/HelpMessage.tsx","webpack:///./components/QueryEditor/PPLFormatEditor/index.tsx","webpack:///./components/QueryEditor/PPLEditor.tsx","webpack:///./components/QueryEditor/index.tsx","webpack:///./module.ts","webpack:///./configuration/ConfigEditor.tsx"],"names":["installedModules","__webpack_require__","moduleId","exports","module","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","prototype","hasOwnProperty","p","s","__WEBPACK_EXTERNAL_MODULE__0__","__WEBPACK_EXTERNAL_MODULE__1__","__WEBPACK_EXTERNAL_MODULE__2__","__WEBPACK_EXTERNAL_MODULE__3__","__WEBPACK_EXTERNAL_MODULE__4__","__WEBPACK_EXTERNAL_MODULE__5__","__WEBPACK_EXTERNAL_MODULE__6__","__WEBPACK_EXTERNAL_MODULE__7__","e","DataSource","TestData","QueryTab","scenarioSelectContainer","scenarioSelect","max","min","noise","seriesCount","spread","startValue","Panels","Panel","title","headerItems","containerByTitle","headerCornerInfo","Visualization","Graph","VisualizationTab","legendSection","Legend","legendItemAlias","showLegendSwitch","xAxis","labels","BarGauge","Text","container","Drawer","General","expand","contract","close","rcContentWrapper","PanelEditor","content","OptionsPane","open","select","tab","DataPane","FieldOptions","propertyEditor","PanelInspector","Data","Stats","Json","Query","refreshButton","jsonObjectKeys","Tab","active","RefreshPicker","runButton","queryInspectorButton","addQuery","QueryEditorRows","rows","QueryEditorRow","actionButton","AlertTab","Alert","alert","TransformTab","newTransform","transformationEditor","transformationEditorDebugger","Transforms","card","Reduce","modeLabel","calculationsLabel","searchInput","PageToolbar","item","QueryEditorToolbarItem","button","BackButton","backArrow","OptionsGroup","toggle","PluginVisualization","current","Select","option","input","singleValue","FieldConfigEditor","OverridesConfigEditor","FolderPicker","DataSourcePicker","TimeZonePicker","TraceViewer","spanBar","QueryField","ValuePicker","Search","section","items","DashboardLinks","dropDown","link","CallToActionCard","DataLinksContextMenu","singleLink","pages","Login","url","username","password","submit","skip","Home","delete","saveAndTest","DataSources","dataSources","AddDataSource","dataSourcePlugins","ConfirmModal","AddDashboard","addNewPanel","Dashboard","SubMenu","submenuItem","submenuItemLabels","submenuItemValueDropDownValueLinkTexts","submenuItemValueDropDownDropDown","submenuItemValueDropDownOptionTexts","Settings","deleteDashBoard","sectionItems","saveDashBoard","saveAsDashBoard","timezone","Annotations","List","addAnnotationCTA","Variables","addVariableCTA","newButton","table","tableRowNameFields","tableRowDefinitionFields","tableRowArrowUpButtons","tableRowArrowDownButtons","tableRowDuplicateButtons","tableRowRemoveButtons","Edit","headerLink","modeLabelNew","modeLabelEdit","generalNameInput","generalTypeSelect","generalLabelInput","generalHideSelect","selectionOptionsMultiSwitch","selectionOptionsIncludeAllSwitch","selectionOptionsCustomAllInput","previewOfValuesOption","submitButton","QueryVariable","queryOptionsDataSourceSelect","queryOptionsRefreshSelect","queryOptionsRegExInput","queryOptionsSortSelect","queryOptionsQueryInput","valueGroupsTagsEnabledSwitch","valueGroupsTagsTagsQueryInput","valueGroupsTagsTagsValuesQueryInput","ConstantVariable","constantOptionsQueryInput","TextBoxVariable","textBoxOptionsQueryInput","Dashboards","dashboards","SaveDashboardAsModal","newName","save","SaveDashboardModal","saveVariables","saveTimerange","SharePanelModal","linkToRenderedImage","Explore","graph","scrollBar","Toolbar","navBar","SoloPanel","PluginsList","page","list","listItem","signatureErrorNotice","PluginPage","signatureInfo","components","selectors","extendStatics","b","setPrototypeOf","__proto__","Array","__extends","TypeError","String","__","this","constructor","__assign","assign","arguments","length","apply","__rest","indexOf","getOwnPropertySymbols","propertyIsEnumerable","__awaiter","thisArg","_arguments","P","generator","Promise","resolve","reject","fulfilled","step","next","rejected","result","done","then","__generator","body","f","y","g","_","label","sent","trys","ops","verb","iterator","v","op","pop","push","__values","__read","ar","error","__spread","concat","__makeTemplateObject","cooked","raw","isFunction","x","_enable_super_gross_mode_that_will_cause_bad_things","undefined","hostReportError","err","setTimeout","empty","closed","useDeprecatedSynchronousErrorHandling","complete","isArray","UnsubscriptionError","UnsubscriptionErrorImpl","errors","Error","message","map","toString","join","Subscription","unsubscribe","_parentOrParents","_subscriptions","_ctorUnsubscribe","_unsubscribe","remove","index","flattenUnsubscriptionErrors","len","sub","add","teardown","subscription","EMPTY","tmp","subscriptions","subscriptionIndex","splice","reduce","errs","rxSubscriber","Math","random","_super","Subscriber","destinationOrNext","_this","syncErrorValue","syncErrorThrown","syncErrorThrowable","isStopped","destination","subscriber","_next","_error","_complete","_unsubscribeAndRecycle","SafeSubscriber","_parentSubscriber","observerOrNext","context","_context","__tryOrSetError","__tryOrUnsub","wrappedComplete","fn","parent","project","source","lift","MapOperator","subscribe","MapSubscriber","count","FUNCTIONS","insertText","documentation","detail","comment","pattern","lookbehind","inside","alias","punctuation","greedy","function","RegExp","number","operator","datasource","initialValues","importQueries","queries","datasourceType","query","isLogsQuery","prometheusLabels","elasticsearchLuceneLabels","keyOperatorValue","substring","getElasticsearchQuery","promQuery","tokens","tokenize","grammar","nameLabelValue","prop","getNameLabelValue","token","type","labelKey","labelValue","labelOperator","contentTokens","currentToken","currentStr","extractPrometheusLabels","expr","refId","flatten","target","opts","delimiter","maxDepth","currentDepth","output","prev","keys","forEach","isarray","safe","isobject","newKey","metric","metricAggregationConfig","supportsMultipleBucketPaths","requiresField","isPipelineAgg","supportsMissing","hasSettings","hasMeta","supportsInlineScript","defaults","avg","sum","extended_stats","meta","std_deviation_bounds_lower","std_deviation_bounds_upper","percentiles","settings","percents","cardinality","moving_avg","minVersion","model","window","moving_fn","derivative","cumulative_sum","bucket_script","pipelineVariables","pipelineAgg","raw_document","isSingleMetric","size","raw_data","logs","pipelineOptions","default","extendedStats","movingAvgModelOptions","defaultMetricAgg","id","defaultBucketAgg","interval","findMetricById","metrics","find","ElasticsearchQueryType","columns","columnMap","col","addColumn","row","addRow","sort","options","a","desc","reverse","text","field","removeEmpty","obj","entries","acc","cleanObj","targets","response","targetType","Lucene","processResponseToSeries","seriesList","responses","getErrorFromElasticResponse","hits","processHits","aggregations","tmpSeriesList","processBuckets","trimDatapoints","nameSeries","data","processPPLResponseToSeries","datarows","datapoints","targetVal","getInvalidPPLQuery","newSeries","props","schema","processMetrics","esAgg","hide","buckets","bucket","doc_count","values","percentileName","statName","stats","std_deviation_bounds","upper","lower","metricId","normalized_value","processAggregationDocs","aggDef","propKey","filterable","addMetricValue","metricName","propValues","getMetricName","filter","script","aggs","depth","aggId","bucketAggs","nameIndex","clone","key_as_string","metricDef","extendedStat","getSeriesName","series","metricTypeCount","replace","match","g1","g2","group","metricType","agg","pv","appliedAgg","propName","trim","uniq","hit","doc","hitsTotal","total","_id","_type","_index","_source","fields","histogram","trimEdges","points","slice","JSON","stringify","root_cause","reason","$$config","config","getTimeSeries","PPL","some","processResponseToDataFrames","getLogs","logMessageField","logLevelField","processPPLResponseToDataFrames","getTable","isLogsRequest","dataFrame","propNames","docs","timeField","addPreferredVisualisationType","arr","zipObject","flattenSchema","flattened","invalidTS","timeFieldIndex","findIndex","valueIndex","datarow","newDatarow","timestamp","unix","addField","time","string","parse","fieldNames","includes","preferredVisualisationType","intervalMap","Hourly","startOf","amount","Daily","Weekly","Monthly","Yearly","dateLocale","getIndexForToday","locale","format","getIndexList","from","to","intervalInfo","start","utc","endEpoch","valueOf","indexList","getPPLIndexPattern","indexPattern","startsWith","endsWith","getDefaultTimeRange","now","subtract","esVersion","getRangeFilter","gte","lte","buildTermsAgg","queryNode","metricRef","terms","parseInt","orderBy","order","isNaN","min_doc_count","missing","getDateHistogramAgg","extended_bounds","offset","getHistogramAgg","getFiltersAgg","filterObj","filters","query_string","analyze_wildcard","documentQuery","unmapped_type","script_fields","addAdhocFilters","adhocFilters","condition","queryCondition","bool","must","match_phrase","must_not","lt","range","gt","regexp","build","queryString","j","nestedAggs","queryType","precision","aggField","metricAgg","buckets_path","test","getTermsQuery","queryDef","keyname","getLogsQuery","querystring","addPPLAdhocFilters","adhocquery","isValid","buildPPLQuery","timeRangeFilter","separatorIndex","trimEnd","bucketAggregationConfig","defaultSettings","geohash_grid","date_histogram","orderOptions","sizeOptions","orderByOptions","intervalOptions","bucketAgg","ELASTIC_META_FIELDS","instanceSettings","basicAuth","withCredentials","settingsData","jsonData","database","timeInterval","maxConcurrentShardRequests","queryBuilder","dataLinks","languageProvider","pplEnabled","request","method","headers","Authorization","datasourceRequest","details","originMeta","requestAllIndices","results","maxTraversals","listLen","status","post","annotationQuery","annotation","timeEndField","tagsField","textField","dateRanges","rangeStart","rangeEnd","should","minimum_should_match","header","search_type","ignore_unavailable","payload","res","getFieldFromSource","fieldName","split","fieldValue","isString","isNumber","event","tags","timeEnd","titleField","interpolateLuceneQuery","scopedVars","interpolatePPLQuery","interpolateVariablesInQueries","expandedQueries","interpolatedQuery","expandedQuery","testDatasource","getFields","dateFields","getQueryHeader","searchType","timeFrom","timeTo","queryHeader","getQueryDisplayText","metricAggs","cloneDeep","luceneTargets","pplTargets","subQueries","luceneResponses","executeLuceneQueries","pplResponses","executePPLQueries","state","Done","createLuceneQuery","getMultiSearchUrl","pipe","er","enhanceDataFrame","createPPLQuery","rangeFrom","rangeTo","getPPLUrl","queryObj","getAdhocFilters","hasMetricOfType","esQuery","isMetadataField","configuredEsVersion","typeMap","float","double","integer","long","date","date_nanos","scaled_float","nested","shouldAddField","fieldNameParts","getFieldsRecursively","subObj","isObject","properties","indexName","mappings","typeName","getTerms","metricFindQuery","parsedQuery","getTagKeys","getTagValues","targetContainsTemplate","variableExists","objectContainsTemplate","isPrimitive","getSupportedQueryTypes","dataSourceSrv","dataLinkConfig","dataLink","datasourceUid","dsSettings","getInstanceSettings","internal","datasourceName","links","Input","FormField","Switch","indexPatternTypes","example","esVersions","className","labelWidth","inputWidth","onChange","placeholder","required","inputEl","version","defaultMaxConcurrentShardRequests","getMaxConcurrenShardRequestOrDefault","validationEvents","onBlur","tooltip","labelClass","checked","currentTarget","newInterval","newDatabase","changeHandler","ref","otherProps","display","signature","invalid","icon","color","valid","modified","getSignatureDisplayModel","displayName","setState","componentDidMount","getCurrentValue","hideTextValue","noDefault","ds","substr","imgUrl","info","logos","small","hideText","getDataSourceOptions","tracing","mixed","dashboard","variables","annotations","pluginId","getList","isDefault","render","autoFocus","openMenuOnFocus","isMulti","isClearable","backspaceRemovesValue","maxMenuHeight","menuPlacement","noOptionsMessage","getOptionLabel","align","justify","defaultProps","getStyles","firstRow","nameField","regexField","onDelete","suggestions","styles","showInternalLink","setShowInternalLink","previousUid","useInternalLink","variant","onClick","preventDefault","newValue","uid","theme","infoText","spacing","md","colors","textWeak","sm","newField","newDataLinks","valueRaw","origin","Value","reducer","action","DispatchContext","dispatch","INIT","changeQuery","queryReducer","prevQuery","aliasPatternReducer","prevAliasPattern","aliasPattern","metricToRemove","getChildren","children","flatMap","child","resultingMetrics","toRemove","newSettings","settingName","attribute","newAgg","lastAgg","newType","prevQueryType","prevFormat","DatasourceContext","QueryContext","reducers","newState","Provider","queryTypeConfig","segmentStyles","supportedTypes","hidden","textFaint","SROnly","iconName","buttonProps","onAdd","onRemove","elements","noWrap","pipelineVariable","newMetric","SettingField","defaultValue","previousMetrics","upperStateDispatch","width","pipelineVar","wrapper","settingsWrapper","xs","setOpen","predict","isEWMAMovingAverage","alpha","minimize","isHoltMovingAverage","beta","isHoltWintersMovingAverage","gamma","period","pad","inlineFieldProps","description","precision_threshold","selectedStats","hasValue","Boolean","stat","toSelectableValue","includePipelineAggregations","maxVersion","loadOptions","onRemoveClick","onHideClick","disableRemove","as","iconWrapper","surface","disabled","xxs","nextId","totalMetrics","portalOrigin","settingsDescription","minDocCount","orderByOption","allowCustomValue","bucketAggOptions","totalBucketAggs","toId","toInt","idString","grow","formatConfig","time_series","queryTypeOptions","displayHelp","setDisplayHelp","templateUrl","setQueryEditor","setConfigEditor","onOptionsChange","defaultUrl","dataSourceConfig","showAccessOptions","sigV4AuthToggleEnabled","sigV4AuthEnabled","setAnnotationQueryCtrl","ElasticAnnotationsQueryCtrl"],"mappings":";oJACE,IAAIA,EAAmB,GAGvB,SAASC,EAAoBC,GAG5B,GAAGF,EAAiBE,GACnB,OAAOF,EAAiBE,GAAUC,QAGnC,IAAIC,EAASJ,EAAiBE,GAAY,CACzCG,EAAGH,EACHI,GAAG,EACHH,QAAS,IAUV,OANAI,EAAQL,GAAUM,KAAKJ,EAAOD,QAASC,EAAQA,EAAOD,QAASF,GAG/DG,EAAOE,GAAI,EAGJF,EAAOD,QA0Df,OArDAF,EAAoBQ,EAAIF,EAGxBN,EAAoBS,EAAIV,EAGxBC,EAAoBU,EAAI,SAASR,EAASS,EAAMC,GAC3CZ,EAAoBa,EAAEX,EAASS,IAClCG,OAAOC,eAAeb,EAASS,EAAM,CAAEK,YAAY,EAAMC,IAAKL,KAKhEZ,EAAoBkB,EAAI,SAAShB,GACX,oBAAXiB,QAA0BA,OAAOC,aAC1CN,OAAOC,eAAeb,EAASiB,OAAOC,YAAa,CAAEC,MAAO,WAE7DP,OAAOC,eAAeb,EAAS,aAAc,CAAEm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SACfsI,SAAU,SAAA2E,GACR,OAAAuH,EAAgB,EAAD,KACVvjB,GAAO,CACV+O,SAAUiN,QAKhB,mBAAC,GAAS,CACRx5B,MAAOwd,EAAQ+O,SAASK,UACxBiI,SAAU,SAAA2E,GACRuH,EAAgB,EAAD,KACVvjB,GAAO,CACV+O,SAAU,EAAF,KACH/O,EAAQ+O,UAAQ,CACnBK,UAAW4M,cDhDtB6H,uBAAuBC","file":"module.js","sourcesContent":[" \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"/\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 10);\n","module.exports = __WEBPACK_EXTERNAL_MODULE__0__;","module.exports = __WEBPACK_EXTERNAL_MODULE__1__;","module.exports = __WEBPACK_EXTERNAL_MODULE__2__;","module.exports = __WEBPACK_EXTERNAL_MODULE__3__;","module.exports = __WEBPACK_EXTERNAL_MODULE__4__;","module.exports = __WEBPACK_EXTERNAL_MODULE__5__;","module.exports = __WEBPACK_EXTERNAL_MODULE__6__;","module.exports = __WEBPACK_EXTERNAL_MODULE__7__;","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./index.production.js');\n} else {\n module.exports = require('./index.development.js');\n}\n","\"use strict\";Object.defineProperty(exports,\"__esModule\",{value:!0});var e={DataSource:{TestData:{QueryTab:{scenarioSelectContainer:\"Test Data Query scenario select container\",scenarioSelect:\"Test Data Query scenario select\",max:\"TestData max\",min:\"TestData min\",noise:\"TestData noise\",seriesCount:\"TestData series count\",spread:\"TestData spread\",startValue:\"TestData start value\"}}},Panels:{Panel:{title:function(e){return\"Panel header title item \"+e},headerItems:function(e){return\"Panel header item \"+e},containerByTitle:function(e){return\"Panel container title \"+e},headerCornerInfo:function(e){return\"Panel header \"+e}},Visualization:{Graph:{VisualizationTab:{legendSection:\"Legend section\"},Legend:{legendItemAlias:function(e){return\"gpl alias \"+e},showLegendSwitch:\"gpl show legend\"},xAxis:{labels:function(){return\"div.flot-x-axis > div.flot-tick-label\"}}},BarGauge:{value:\"Bar gauge value\"},Text:{container:function(){return\".markdown-html\"}}}},Drawer:{General:{title:function(e){return\"Drawer title \"+e},expand:\"Drawer expand\",contract:\"Drawer contract\",close:\"Drawer close\",rcContentWrapper:function(){return\".drawer-content-wrapper\"}}},PanelEditor:{General:{content:\"Panel editor content\"},OptionsPane:{content:\"Panel editor option pane content\",close:\"Page toolbar button Close options pane\",open:\"Page toolbar button Open options pane\",select:\"Panel editor option pane select\",tab:function(e){return\"Panel editor option pane tab \"+e}},DataPane:{content:\"Panel editor data pane content\"},FieldOptions:{propertyEditor:function(e){return e+\" field property editor\"}}},PanelInspector:{Data:{content:\"Panel inspector Data content\"},Stats:{content:\"Panel inspector Stats content\"},Json:{content:\"Panel inspector Json content\"},Query:{content:\"Panel inspector Query content\",refreshButton:\"Panel inspector Query refresh button\",jsonObjectKeys:function(){return\".json-formatter-key\"}}},Tab:{title:function(e){return\"Tab \"+e},active:function(){return'[class*=\"-activeTabStyle\"]'}},RefreshPicker:{runButton:\"RefreshPicker run button\"},QueryTab:{content:\"Query editor tab content\",queryInspectorButton:\"Query inspector button\",addQuery:\"Query editor add query button\"},QueryEditorRows:{rows:\"Query editor row\"},QueryEditorRow:{actionButton:function(e){return e+\" query operation action\"},title:function(e){return\"Query editor row title \"+e}},AlertTab:{content:\"Alert editor tab content\"},Alert:{alert:function(e){return\"Alert \"+e}},TransformTab:{content:\"Transform editor tab content\",newTransform:function(e){return\"New transform \"+e},transformationEditor:function(e){return\"Transformation editor \"+e},transformationEditorDebugger:function(e){return\"Transformation editor debugger \"+e}},Transforms:{card:function(e){return\"New transform \"+e},Reduce:{modeLabel:\"Transform mode label\",calculationsLabel:\"Transform calculations label\"},searchInput:\"search transformations\"},PageToolbar:{container:function(){return\".page-toolbar\"},item:function(e){return\"Page toolbar button \"+e}},QueryEditorToolbarItem:{button:function(e){return\"QueryEditor toolbar item button \"+e}},BackButton:{backArrow:\"Go Back button\"},OptionsGroup:{toggle:function(e){return e?\"Options group \"+e:\"Options group\"}},PluginVisualization:{item:function(e){return\"Plugin visualization item \"+e},current:function(){return'[class*=\"-currentVisualizationItem\"]'}},Select:{option:\"Select option\",input:function(){return'input[id*=\"react-select-\"]'},singleValue:function(){return'div[class*=\"-singleValue\"]'}},FieldConfigEditor:{content:\"Field config editor content\"},OverridesConfigEditor:{content:\"Field overrides editor content\"},FolderPicker:{container:\"Folder picker select container\"},DataSourcePicker:{container:\"Data source picker select container\"},TimeZonePicker:{container:\"Time zone picker select container\"},TraceViewer:{spanBar:function(){return'[data-test-id=\"SpanBar--wrapper\"]'}},QueryField:{container:\"Query field\"},ValuePicker:{button:\"Value picker add button\",select:function(e){return\"Value picker select \"+e}},Search:{section:\"Search section\",items:\"Search items\"},DashboardLinks:{container:\"Dashboard link container\",dropDown:\"Dashboard link dropdown\",link:\"Dashboard link\"},CallToActionCard:{button:function(e){return\"Call to action button \"+e}},DataLinksContextMenu:{singleLink:\"Data link\"}},t={pages:{Login:{url:\"/login\",username:\"Username input field\",password:\"Password input field\",submit:\"Login button\",skip:\"Skip change password button\"},Home:{url:\"/\"},DataSource:{name:\"Data source settings page name input field\",delete:\"Data source settings page Delete button\",saveAndTest:\"Data source settings page Save and Test button\",alert:\"Data source settings page Alert\"},DataSources:{url:\"/datasources\",dataSources:function(e){return\"Data source list item \"+e}},AddDataSource:{url:\"/datasources/new\",dataSourcePlugins:function(e){return\"Data source plugin item \"+e}},ConfirmModal:{delete:\"Confirm Modal Danger Button\"},AddDashboard:{url:\"/dashboard/new\",addNewPanel:\"Add new panel\"},Dashboard:{url:function(e){return\"/d/\"+e},SubMenu:{submenuItem:\"Dashboard template variables submenu item\",submenuItemLabels:function(e){return\"Dashboard template variables submenu Label \"+e},submenuItemValueDropDownValueLinkTexts:function(e){return\"Dashboard template variables Variable Value DropDown value link text \"+e},submenuItemValueDropDownDropDown:\"Dashboard template variables Variable Value DropDown DropDown\",submenuItemValueDropDownOptionTexts:function(e){return\"Dashboard template variables Variable Value DropDown option text \"+e}},Settings:{General:{deleteDashBoard:\"Dashboard settings page delete dashboard button\",sectionItems:function(e){return\"Dashboard settings section item \"+e},saveDashBoard:\"Dashboard settings aside actions Save button\",saveAsDashBoard:\"Dashboard settings aside actions Save As button\",timezone:\"Time zone picker select container\",title:\"Dashboard settings page title\"},Annotations:{List:{addAnnotationCTA:e.CallToActionCard.button(\"Add Annotation Query\")}},Variables:{List:{addVariableCTA:e.CallToActionCard.button(\"Add variable\"),newButton:\"Variable editor New variable button\",table:\"Variable editor Table\",tableRowNameFields:function(e){return\"Variable editor Table Name field \"+e},tableRowDefinitionFields:function(e){return\"Variable editor Table Definition field \"+e},tableRowArrowUpButtons:function(e){return\"Variable editor Table ArrowUp button \"+e},tableRowArrowDownButtons:function(e){return\"Variable editor Table ArrowDown button \"+e},tableRowDuplicateButtons:function(e){return\"Variable editor Table Duplicate button \"+e},tableRowRemoveButtons:function(e){return\"Variable editor Table Remove button \"+e}},Edit:{General:{headerLink:\"Variable editor Header link\",modeLabelNew:\"Variable editor Header mode New\",modeLabelEdit:\"Variable editor Header mode Edit\",generalNameInput:\"Variable editor Form Name field\",generalTypeSelect:\"Variable editor Form Type select\",generalLabelInput:\"Variable editor Form Label field\",generalHideSelect:\"Variable editor Form Hide select\",selectionOptionsMultiSwitch:\"Variable editor Form Multi switch\",selectionOptionsIncludeAllSwitch:\"Variable editor Form IncludeAll switch\",selectionOptionsCustomAllInput:\"Variable editor Form IncludeAll field\",previewOfValuesOption:\"Variable editor Preview of Values option\",submitButton:\"Variable editor Submit button\"},QueryVariable:{queryOptionsDataSourceSelect:e.DataSourcePicker.container,queryOptionsRefreshSelect:\"Variable editor Form Query Refresh select\",queryOptionsRegExInput:\"Variable editor Form Query RegEx field\",queryOptionsSortSelect:\"Variable editor Form Query Sort select\",queryOptionsQueryInput:\"Variable editor Form Default Variable Query Editor textarea\",valueGroupsTagsEnabledSwitch:\"Variable editor Form Query UseTags switch\",valueGroupsTagsTagsQueryInput:\"Variable editor Form Query TagsQuery field\",valueGroupsTagsTagsValuesQueryInput:\"Variable editor Form Query TagsValuesQuery field\"},ConstantVariable:{constantOptionsQueryInput:\"Variable editor Form Constant Query field\"},TextBoxVariable:{textBoxOptionsQueryInput:\"Variable editor Form TextBox Query field\"}}}}},Dashboards:{url:\"/dashboards\",dashboards:function(e){return\"Dashboard search item \"+e}},SaveDashboardAsModal:{newName:\"Save dashboard title field\",save:\"Save dashboard button\"},SaveDashboardModal:{save:\"Dashboard settings Save Dashboard Modal Save button\",saveVariables:\"Dashboard settings Save Dashboard Modal Save variables checkbox\",saveTimerange:\"Dashboard settings Save Dashboard Modal Save timerange checkbox\"},SharePanelModal:{linkToRenderedImage:\"Link to rendered image\"},Explore:{url:\"/explore\",General:{container:\"Explore\",graph:\"Explore Graph\",table:\"Explore Table\",scrollBar:function(){return\".scrollbar-view\"}},Toolbar:{navBar:function(){return\".explore-toolbar\"}}},SoloPanel:{url:function(e){return\"/d-solo/\"+e}},PluginsList:{page:\"Plugins list page\",list:\"Plugins list\",listItem:\"Plugins list item\",signatureErrorNotice:\"Unsigned plugins notice\"},PluginPage:{page:\"Plugin page\",signatureInfo:\"Plugin signature info\"}},components:e};exports.selectors=t;\n//# sourceMappingURL=index.production.js.map\n","/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from) {\r\n for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)\r\n to[j] = from[i];\r\n return to;\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, privateMap) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to get private field on non-instance\");\r\n }\r\n return privateMap.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, privateMap, value) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to set private field on non-instance\");\r\n }\r\n privateMap.set(receiver, value);\r\n return value;\r\n}\r\n","/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport function __createBinding(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n}\r\n\r\nexport function __exportStar(m, exports) {\r\n for (var p in m) if (p !== \"default\" && !exports.hasOwnProperty(p)) exports[p] = m[p];\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n};\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\r\n result.default = mod;\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, privateMap) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to get private field on non-instance\");\r\n }\r\n return privateMap.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, privateMap, value) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to set private field on non-instance\");\r\n }\r\n privateMap.set(receiver, value);\r\n return value;\r\n}\r\n","/** PURE_IMPORTS_START PURE_IMPORTS_END */\nexport function isFunction(x) {\n return typeof x === 'function';\n}\n//# sourceMappingURL=isFunction.js.map\n","/** PURE_IMPORTS_START PURE_IMPORTS_END */\nvar _enable_super_gross_mode_that_will_cause_bad_things = false;\nexport var config = {\n Promise: undefined,\n set useDeprecatedSynchronousErrorHandling(value) {\n if (value) {\n var error = /*@__PURE__*/ new Error();\n /*@__PURE__*/ console.warn('DEPRECATED! RxJS was set to use deprecated synchronous error handling behavior by code at: \\n' + error.stack);\n }\n else if (_enable_super_gross_mode_that_will_cause_bad_things) {\n /*@__PURE__*/ console.log('RxJS: Back to a better error behavior. Thank you. <3');\n }\n _enable_super_gross_mode_that_will_cause_bad_things = value;\n },\n get useDeprecatedSynchronousErrorHandling() {\n return _enable_super_gross_mode_that_will_cause_bad_things;\n },\n};\n//# sourceMappingURL=config.js.map\n","/** PURE_IMPORTS_START PURE_IMPORTS_END */\nexport function hostReportError(err) {\n setTimeout(function () { throw err; }, 0);\n}\n//# sourceMappingURL=hostReportError.js.map\n","/** PURE_IMPORTS_START _config,_util_hostReportError PURE_IMPORTS_END */\nimport { config } from './config';\nimport { hostReportError } from './util/hostReportError';\nexport var empty = {\n closed: true,\n next: function (value) { },\n error: function (err) {\n if (config.useDeprecatedSynchronousErrorHandling) {\n throw err;\n }\n else {\n hostReportError(err);\n }\n },\n complete: function () { }\n};\n//# sourceMappingURL=Observer.js.map\n","/** PURE_IMPORTS_START PURE_IMPORTS_END */\nexport var isArray = /*@__PURE__*/ (function () { return Array.isArray || (function (x) { return x && typeof x.length === 'number'; }); })();\n//# sourceMappingURL=isArray.js.map\n","/** PURE_IMPORTS_START PURE_IMPORTS_END */\nvar UnsubscriptionErrorImpl = /*@__PURE__*/ (function () {\n function UnsubscriptionErrorImpl(errors) {\n Error.call(this);\n this.message = errors ?\n errors.length + \" errors occurred during unsubscription:\\n\" + errors.map(function (err, i) { return i + 1 + \") \" + err.toString(); }).join('\\n ') : '';\n this.name = 'UnsubscriptionError';\n this.errors = errors;\n return this;\n }\n UnsubscriptionErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype);\n return UnsubscriptionErrorImpl;\n})();\nexport var UnsubscriptionError = UnsubscriptionErrorImpl;\n//# sourceMappingURL=UnsubscriptionError.js.map\n","/** PURE_IMPORTS_START _util_isArray,_util_isObject,_util_isFunction,_util_UnsubscriptionError PURE_IMPORTS_END */\nimport { isArray } from './util/isArray';\nimport { isObject } from './util/isObject';\nimport { isFunction } from './util/isFunction';\nimport { UnsubscriptionError } from './util/UnsubscriptionError';\nvar Subscription = /*@__PURE__*/ (function () {\n function Subscription(unsubscribe) {\n this.closed = false;\n this._parentOrParents = null;\n this._subscriptions = null;\n if (unsubscribe) {\n this._ctorUnsubscribe = true;\n this._unsubscribe = unsubscribe;\n }\n }\n Subscription.prototype.unsubscribe = function () {\n var errors;\n if (this.closed) {\n return;\n }\n var _a = this, _parentOrParents = _a._parentOrParents, _ctorUnsubscribe = _a._ctorUnsubscribe, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions;\n this.closed = true;\n this._parentOrParents = null;\n this._subscriptions = null;\n if (_parentOrParents instanceof Subscription) {\n _parentOrParents.remove(this);\n }\n else if (_parentOrParents !== null) {\n for (var index = 0; index < _parentOrParents.length; ++index) {\n var parent_1 = _parentOrParents[index];\n parent_1.remove(this);\n }\n }\n if (isFunction(_unsubscribe)) {\n if (_ctorUnsubscribe) {\n this._unsubscribe = undefined;\n }\n try {\n _unsubscribe.call(this);\n }\n catch (e) {\n errors = e instanceof UnsubscriptionError ? flattenUnsubscriptionErrors(e.errors) : [e];\n }\n }\n if (isArray(_subscriptions)) {\n var index = -1;\n var len = _subscriptions.length;\n while (++index < len) {\n var sub = _subscriptions[index];\n if (isObject(sub)) {\n try {\n sub.unsubscribe();\n }\n catch (e) {\n errors = errors || [];\n if (e instanceof UnsubscriptionError) {\n errors = errors.concat(flattenUnsubscriptionErrors(e.errors));\n }\n else {\n errors.push(e);\n }\n }\n }\n }\n }\n if (errors) {\n throw new UnsubscriptionError(errors);\n }\n };\n Subscription.prototype.add = function (teardown) {\n var subscription = teardown;\n if (!teardown) {\n return Subscription.EMPTY;\n }\n switch (typeof teardown) {\n case 'function':\n subscription = new Subscription(teardown);\n case 'object':\n if (subscription === this || subscription.closed || typeof subscription.unsubscribe !== 'function') {\n return subscription;\n }\n else if (this.closed) {\n subscription.unsubscribe();\n return subscription;\n }\n else if (!(subscription instanceof Subscription)) {\n var tmp = subscription;\n subscription = new Subscription();\n subscription._subscriptions = [tmp];\n }\n break;\n default: {\n throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.');\n }\n }\n var _parentOrParents = subscription._parentOrParents;\n if (_parentOrParents === null) {\n subscription._parentOrParents = this;\n }\n else if (_parentOrParents instanceof Subscription) {\n if (_parentOrParents === this) {\n return subscription;\n }\n subscription._parentOrParents = [_parentOrParents, this];\n }\n else if (_parentOrParents.indexOf(this) === -1) {\n _parentOrParents.push(this);\n }\n else {\n return subscription;\n }\n var subscriptions = this._subscriptions;\n if (subscriptions === null) {\n this._subscriptions = [subscription];\n }\n else {\n subscriptions.push(subscription);\n }\n return subscription;\n };\n Subscription.prototype.remove = function (subscription) {\n var subscriptions = this._subscriptions;\n if (subscriptions) {\n var subscriptionIndex = subscriptions.indexOf(subscription);\n if (subscriptionIndex !== -1) {\n subscriptions.splice(subscriptionIndex, 1);\n }\n }\n };\n Subscription.EMPTY = (function (empty) {\n empty.closed = true;\n return empty;\n }(new Subscription()));\n return Subscription;\n}());\nexport { Subscription };\nfunction flattenUnsubscriptionErrors(errors) {\n return errors.reduce(function (errs, err) { return errs.concat((err instanceof UnsubscriptionError) ? err.errors : err); }, []);\n}\n//# sourceMappingURL=Subscription.js.map\n","/** PURE_IMPORTS_START PURE_IMPORTS_END */\nexport function isObject(x) {\n return x !== null && typeof x === 'object';\n}\n//# sourceMappingURL=isObject.js.map\n","/** PURE_IMPORTS_START PURE_IMPORTS_END */\nexport var rxSubscriber = /*@__PURE__*/ (function () {\n return typeof Symbol === 'function'\n ? /*@__PURE__*/ Symbol('rxSubscriber')\n : '@@rxSubscriber_' + /*@__PURE__*/ Math.random();\n})();\nexport var $$rxSubscriber = rxSubscriber;\n//# sourceMappingURL=rxSubscriber.js.map\n","/** PURE_IMPORTS_START tslib,_util_isFunction,_Observer,_Subscription,_internal_symbol_rxSubscriber,_config,_util_hostReportError PURE_IMPORTS_END */\nimport * as tslib_1 from \"tslib\";\nimport { isFunction } from './util/isFunction';\nimport { empty as emptyObserver } from './Observer';\nimport { Subscription } from './Subscription';\nimport { rxSubscriber as rxSubscriberSymbol } from '../internal/symbol/rxSubscriber';\nimport { config } from './config';\nimport { hostReportError } from './util/hostReportError';\nvar Subscriber = /*@__PURE__*/ (function (_super) {\n tslib_1.__extends(Subscriber, _super);\n function Subscriber(destinationOrNext, error, complete) {\n var _this = _super.call(this) || this;\n _this.syncErrorValue = null;\n _this.syncErrorThrown = false;\n _this.syncErrorThrowable = false;\n _this.isStopped = false;\n switch (arguments.length) {\n case 0:\n _this.destination = emptyObserver;\n break;\n case 1:\n if (!destinationOrNext) {\n _this.destination = emptyObserver;\n break;\n }\n if (typeof destinationOrNext === 'object') {\n if (destinationOrNext instanceof Subscriber) {\n _this.syncErrorThrowable = destinationOrNext.syncErrorThrowable;\n _this.destination = destinationOrNext;\n destinationOrNext.add(_this);\n }\n else {\n _this.syncErrorThrowable = true;\n _this.destination = new SafeSubscriber(_this, destinationOrNext);\n }\n break;\n }\n default:\n _this.syncErrorThrowable = true;\n _this.destination = new SafeSubscriber(_this, destinationOrNext, error, complete);\n break;\n }\n return _this;\n }\n Subscriber.prototype[rxSubscriberSymbol] = function () { return this; };\n Subscriber.create = function (next, error, complete) {\n var subscriber = new Subscriber(next, error, complete);\n subscriber.syncErrorThrowable = false;\n return subscriber;\n };\n Subscriber.prototype.next = function (value) {\n if (!this.isStopped) {\n this._next(value);\n }\n };\n Subscriber.prototype.error = function (err) {\n if (!this.isStopped) {\n this.isStopped = true;\n this._error(err);\n }\n };\n Subscriber.prototype.complete = function () {\n if (!this.isStopped) {\n this.isStopped = true;\n this._complete();\n }\n };\n Subscriber.prototype.unsubscribe = function () {\n if (this.closed) {\n return;\n }\n this.isStopped = true;\n _super.prototype.unsubscribe.call(this);\n };\n Subscriber.prototype._next = function (value) {\n this.destination.next(value);\n };\n Subscriber.prototype._error = function (err) {\n this.destination.error(err);\n this.unsubscribe();\n };\n Subscriber.prototype._complete = function () {\n this.destination.complete();\n this.unsubscribe();\n };\n Subscriber.prototype._unsubscribeAndRecycle = function () {\n var _parentOrParents = this._parentOrParents;\n this._parentOrParents = null;\n this.unsubscribe();\n this.closed = false;\n this.isStopped = false;\n this._parentOrParents = _parentOrParents;\n return this;\n };\n return Subscriber;\n}(Subscription));\nexport { Subscriber };\nvar SafeSubscriber = /*@__PURE__*/ (function (_super) {\n tslib_1.__extends(SafeSubscriber, _super);\n function SafeSubscriber(_parentSubscriber, observerOrNext, error, complete) {\n var _this = _super.call(this) || this;\n _this._parentSubscriber = _parentSubscriber;\n var next;\n var context = _this;\n if (isFunction(observerOrNext)) {\n next = observerOrNext;\n }\n else if (observerOrNext) {\n next = observerOrNext.next;\n error = observerOrNext.error;\n complete = observerOrNext.complete;\n if (observerOrNext !== emptyObserver) {\n context = Object.create(observerOrNext);\n if (isFunction(context.unsubscribe)) {\n _this.add(context.unsubscribe.bind(context));\n }\n context.unsubscribe = _this.unsubscribe.bind(_this);\n }\n }\n _this._context = context;\n _this._next = next;\n _this._error = error;\n _this._complete = complete;\n return _this;\n }\n SafeSubscriber.prototype.next = function (value) {\n if (!this.isStopped && this._next) {\n var _parentSubscriber = this._parentSubscriber;\n if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {\n this.__tryOrUnsub(this._next, value);\n }\n else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) {\n this.unsubscribe();\n }\n }\n };\n SafeSubscriber.prototype.error = function (err) {\n if (!this.isStopped) {\n var _parentSubscriber = this._parentSubscriber;\n var useDeprecatedSynchronousErrorHandling = config.useDeprecatedSynchronousErrorHandling;\n if (this._error) {\n if (!useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {\n this.__tryOrUnsub(this._error, err);\n this.unsubscribe();\n }\n else {\n this.__tryOrSetError(_parentSubscriber, this._error, err);\n this.unsubscribe();\n }\n }\n else if (!_parentSubscriber.syncErrorThrowable) {\n this.unsubscribe();\n if (useDeprecatedSynchronousErrorHandling) {\n throw err;\n }\n hostReportError(err);\n }\n else {\n if (useDeprecatedSynchronousErrorHandling) {\n _parentSubscriber.syncErrorValue = err;\n _parentSubscriber.syncErrorThrown = true;\n }\n else {\n hostReportError(err);\n }\n this.unsubscribe();\n }\n }\n };\n SafeSubscriber.prototype.complete = function () {\n var _this = this;\n if (!this.isStopped) {\n var _parentSubscriber = this._parentSubscriber;\n if (this._complete) {\n var wrappedComplete = function () { return _this._complete.call(_this._context); };\n if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {\n this.__tryOrUnsub(wrappedComplete);\n this.unsubscribe();\n }\n else {\n this.__tryOrSetError(_parentSubscriber, wrappedComplete);\n this.unsubscribe();\n }\n }\n else {\n this.unsubscribe();\n }\n }\n };\n SafeSubscriber.prototype.__tryOrUnsub = function (fn, value) {\n try {\n fn.call(this._context, value);\n }\n catch (err) {\n this.unsubscribe();\n if (config.useDeprecatedSynchronousErrorHandling) {\n throw err;\n }\n else {\n hostReportError(err);\n }\n }\n };\n SafeSubscriber.prototype.__tryOrSetError = function (parent, fn, value) {\n if (!config.useDeprecatedSynchronousErrorHandling) {\n throw new Error('bad call');\n }\n try {\n fn.call(this._context, value);\n }\n catch (err) {\n if (config.useDeprecatedSynchronousErrorHandling) {\n parent.syncErrorValue = err;\n parent.syncErrorThrown = true;\n return true;\n }\n else {\n hostReportError(err);\n return true;\n }\n }\n return false;\n };\n SafeSubscriber.prototype._unsubscribe = function () {\n var _parentSubscriber = this._parentSubscriber;\n this._context = null;\n this._parentSubscriber = null;\n _parentSubscriber.unsubscribe();\n };\n return SafeSubscriber;\n}(Subscriber));\nexport { SafeSubscriber };\n//# sourceMappingURL=Subscriber.js.map\n","/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */\nimport * as tslib_1 from \"tslib\";\nimport { Subscriber } from '../Subscriber';\nexport function map(project, thisArg) {\n return function mapOperation(source) {\n if (typeof project !== 'function') {\n throw new TypeError('argument is not a function. Are you looking for `mapTo()`?');\n }\n return source.lift(new MapOperator(project, thisArg));\n };\n}\nvar MapOperator = /*@__PURE__*/ (function () {\n function MapOperator(project, thisArg) {\n this.project = project;\n this.thisArg = thisArg;\n }\n MapOperator.prototype.call = function (subscriber, source) {\n return source.subscribe(new MapSubscriber(subscriber, this.project, this.thisArg));\n };\n return MapOperator;\n}());\nexport { MapOperator };\nvar MapSubscriber = /*@__PURE__*/ (function (_super) {\n tslib_1.__extends(MapSubscriber, _super);\n function MapSubscriber(destination, project, thisArg) {\n var _this = _super.call(this, destination) || this;\n _this.project = project;\n _this.count = 0;\n _this.thisArg = thisArg || _this;\n return _this;\n }\n MapSubscriber.prototype._next = function (value) {\n var result;\n try {\n result = this.project.call(this.thisArg, value, this.count++);\n }\n catch (err) {\n this.destination.error(err);\n return;\n }\n this.destination.next(result);\n };\n return MapSubscriber;\n}(Subscriber));\n//# sourceMappingURL=map.js.map\n","import { Grammar } from 'prismjs';\nimport { CompletionItem } from '@grafana/ui';\n\nexport const RATE_RANGES: CompletionItem[] = [\n { label: '$__interval', sortText: '$__interval' },\n { label: '$__rate_interval', sortText: '$__rate_interval' },\n { label: '1m', sortText: '00:01:00' },\n { label: '5m', sortText: '00:05:00' },\n { label: '10m', sortText: '00:10:00' },\n { label: '30m', sortText: '00:30:00' },\n { label: '1h', sortText: '01:00:00' },\n { label: '1d', sortText: '24:00:00' },\n];\n\nexport const OPERATORS = ['by', 'group_left', 'group_right', 'ignoring', 'on', 'offset', 'without'];\n\nconst AGGREGATION_OPERATORS: CompletionItem[] = [\n {\n label: 'sum',\n insertText: 'sum',\n documentation: 'Calculate sum over dimensions',\n },\n {\n label: 'min',\n insertText: 'min',\n documentation: 'Select minimum over dimensions',\n },\n {\n label: 'max',\n insertText: 'max',\n documentation: 'Select maximum over dimensions',\n },\n {\n label: 'avg',\n insertText: 'avg',\n documentation: 'Calculate the average over dimensions',\n },\n {\n label: 'stddev',\n insertText: 'stddev',\n documentation: 'Calculate population standard deviation over dimensions',\n },\n {\n label: 'stdvar',\n insertText: 'stdvar',\n documentation: 'Calculate population standard variance over dimensions',\n },\n {\n label: 'count',\n insertText: 'count',\n documentation: 'Count number of elements in the vector',\n },\n {\n label: 'count_values',\n insertText: 'count_values',\n documentation: 'Count number of elements with the same value',\n },\n {\n label: 'bottomk',\n insertText: 'bottomk',\n documentation: 'Smallest k elements by sample value',\n },\n {\n label: 'topk',\n insertText: 'topk',\n documentation: 'Largest k elements by sample value',\n },\n {\n label: 'quantile',\n insertText: 'quantile',\n documentation: 'Calculate φ-quantile (0 ≤ φ ≤ 1) over dimensions',\n },\n];\n\nexport const FUNCTIONS = [\n ...AGGREGATION_OPERATORS,\n {\n insertText: 'abs',\n label: 'abs',\n detail: 'abs(v instant-vector)',\n documentation: 'Returns the input vector with all sample values converted to their absolute value.',\n },\n {\n insertText: 'absent',\n label: 'absent',\n detail: 'absent(v instant-vector)',\n documentation:\n '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.',\n },\n {\n insertText: 'ceil',\n label: 'ceil',\n detail: 'ceil(v instant-vector)',\n documentation: 'Rounds the sample values of all elements in `v` up to the nearest integer.',\n },\n {\n insertText: 'changes',\n label: 'changes',\n detail: 'changes(v range-vector)',\n documentation:\n '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.',\n },\n {\n insertText: 'clamp_max',\n label: 'clamp_max',\n detail: 'clamp_max(v instant-vector, max scalar)',\n documentation: 'Clamps the sample values of all elements in `v` to have an upper limit of `max`.',\n },\n {\n insertText: 'clamp_min',\n label: 'clamp_min',\n detail: 'clamp_min(v instant-vector, min scalar)',\n documentation: 'Clamps the sample values of all elements in `v` to have a lower limit of `min`.',\n },\n {\n insertText: 'count_scalar',\n label: 'count_scalar',\n detail: 'count_scalar(v instant-vector)',\n documentation:\n '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.',\n },\n {\n insertText: 'day_of_month',\n label: 'day_of_month',\n detail: 'day_of_month(v=vector(time()) instant-vector)',\n documentation: 'Returns the day of the month for each of the given times in UTC. Returned values are from 1 to 31.',\n },\n {\n insertText: 'day_of_week',\n label: 'day_of_week',\n detail: 'day_of_week(v=vector(time()) instant-vector)',\n documentation:\n '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.',\n },\n {\n insertText: 'days_in_month',\n label: 'days_in_month',\n detail: 'days_in_month(v=vector(time()) instant-vector)',\n documentation:\n 'Returns number of days in the month for each of the given times in UTC. Returned values are from 28 to 31.',\n },\n {\n insertText: 'delta',\n label: 'delta',\n detail: 'delta(v range-vector)',\n documentation:\n '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.',\n },\n {\n insertText: 'deriv',\n label: 'deriv',\n detail: 'deriv(v range-vector)',\n documentation:\n 'Calculates the per-second derivative of the time series in a range vector `v`, using simple linear regression.',\n },\n {\n insertText: 'drop_common_labels',\n label: 'drop_common_labels',\n detail: 'drop_common_labels(instant-vector)',\n documentation: 'Drops all labels that have the same name and value across all series in the input vector.',\n },\n {\n insertText: 'exp',\n label: 'exp',\n detail: 'exp(v instant-vector)',\n documentation:\n 'Calculates the exponential function for all elements in `v`.\\nSpecial cases are:\\n* `Exp(+Inf) = +Inf` \\n* `Exp(NaN) = NaN`',\n },\n {\n insertText: 'floor',\n label: 'floor',\n detail: 'floor(v instant-vector)',\n documentation: 'Rounds the sample values of all elements in `v` down to the nearest integer.',\n },\n {\n insertText: 'histogram_quantile',\n label: 'histogram_quantile',\n detail: 'histogram_quantile(φ float, b instant-vector)',\n documentation:\n '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.',\n },\n {\n insertText: 'holt_winters',\n label: 'holt_winters',\n detail: 'holt_winters(v range-vector, sf scalar, tf scalar)',\n documentation:\n '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.',\n },\n {\n insertText: 'hour',\n label: 'hour',\n detail: 'hour(v=vector(time()) instant-vector)',\n documentation: 'Returns the hour of the day for each of the given times in UTC. Returned values are from 0 to 23.',\n },\n {\n insertText: 'idelta',\n label: 'idelta',\n detail: 'idelta(v range-vector)',\n documentation:\n 'Calculates the difference between the last two samples in the range vector `v`, returning an instant vector with the given deltas and equivalent labels.',\n },\n {\n insertText: 'increase',\n label: 'increase',\n detail: 'increase(v range-vector)',\n documentation:\n '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.',\n },\n {\n insertText: 'irate',\n label: 'irate',\n detail: 'irate(v range-vector)',\n documentation:\n '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.',\n },\n {\n insertText: 'label_replace',\n label: 'label_replace',\n detail: 'label_replace(v instant-vector, dst_label string, replacement string, src_label string, regex string)',\n documentation:\n \"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.\",\n },\n {\n insertText: 'ln',\n label: 'ln',\n detail: 'ln(v instant-vector)',\n documentation:\n '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`',\n },\n {\n insertText: 'log2',\n label: 'log2',\n detail: 'log2(v instant-vector)',\n documentation:\n 'Calculates the binary logarithm for all elements in `v`. The special cases are equivalent to those in `ln`.',\n },\n {\n insertText: 'log10',\n label: 'log10',\n detail: 'log10(v instant-vector)',\n documentation:\n 'Calculates the decimal logarithm for all elements in `v`. The special cases are equivalent to those in `ln`.',\n },\n {\n insertText: 'minute',\n label: 'minute',\n detail: 'minute(v=vector(time()) instant-vector)',\n documentation:\n 'Returns the minute of the hour for each of the given times in UTC. Returned values are from 0 to 59.',\n },\n {\n insertText: 'month',\n label: 'month',\n detail: 'month(v=vector(time()) instant-vector)',\n documentation:\n '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.',\n },\n {\n insertText: 'predict_linear',\n label: 'predict_linear',\n detail: 'predict_linear(v range-vector, t scalar)',\n documentation:\n 'Predicts the value of time series `t` seconds from now, based on the range vector `v`, using simple linear regression.',\n },\n {\n insertText: 'rate',\n label: 'rate',\n detail: 'rate(v range-vector)',\n documentation:\n \"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.\",\n },\n {\n insertText: 'resets',\n label: 'resets',\n detail: 'resets(v range-vector)',\n documentation:\n '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.',\n },\n {\n insertText: 'round',\n label: 'round',\n detail: 'round(v instant-vector, to_nearest=1 scalar)',\n documentation:\n '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.',\n },\n {\n insertText: 'scalar',\n label: 'scalar',\n detail: 'scalar(v instant-vector)',\n documentation:\n '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`.',\n },\n {\n insertText: 'sort',\n label: 'sort',\n detail: 'sort(v instant-vector)',\n documentation: 'Returns vector elements sorted by their sample values, in ascending order.',\n },\n {\n insertText: 'sort_desc',\n label: 'sort_desc',\n detail: 'sort_desc(v instant-vector)',\n documentation: 'Returns vector elements sorted by their sample values, in descending order.',\n },\n {\n insertText: 'sqrt',\n label: 'sqrt',\n detail: 'sqrt(v instant-vector)',\n documentation: 'Calculates the square root of all elements in `v`.',\n },\n {\n insertText: 'time',\n label: 'time',\n detail: 'time()',\n documentation:\n '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.',\n },\n {\n insertText: 'vector',\n label: 'vector',\n detail: 'vector(s scalar)',\n documentation: 'Returns the scalar `s` as a vector with no labels.',\n },\n {\n insertText: 'year',\n label: 'year',\n detail: 'year(v=vector(time()) instant-vector)',\n documentation: 'Returns the year for each of the given times in UTC.',\n },\n {\n insertText: 'avg_over_time',\n label: 'avg_over_time',\n detail: 'avg_over_time(range-vector)',\n documentation: 'The average value of all points in the specified interval.',\n },\n {\n insertText: 'min_over_time',\n label: 'min_over_time',\n detail: 'min_over_time(range-vector)',\n documentation: 'The minimum value of all points in the specified interval.',\n },\n {\n insertText: 'max_over_time',\n label: 'max_over_time',\n detail: 'max_over_time(range-vector)',\n documentation: 'The maximum value of all points in the specified interval.',\n },\n {\n insertText: 'sum_over_time',\n label: 'sum_over_time',\n detail: 'sum_over_time(range-vector)',\n documentation: 'The sum of all values in the specified interval.',\n },\n {\n insertText: 'count_over_time',\n label: 'count_over_time',\n detail: 'count_over_time(range-vector)',\n documentation: 'The count of all values in the specified interval.',\n },\n {\n insertText: 'quantile_over_time',\n label: 'quantile_over_time',\n detail: 'quantile_over_time(scalar, range-vector)',\n documentation: 'The φ-quantile (0 ≤ φ ≤ 1) of the values in the specified interval.',\n },\n {\n insertText: 'stddev_over_time',\n label: 'stddev_over_time',\n detail: 'stddev_over_time(range-vector)',\n documentation: 'The population standard deviation of the values in the specified interval.',\n },\n {\n insertText: 'stdvar_over_time',\n label: 'stdvar_over_time',\n detail: 'stdvar_over_time(range-vector)',\n documentation: 'The population standard variance of the values in the specified interval.',\n },\n];\n\nconst tokenizer: Grammar = {\n comment: {\n pattern: /#.*/,\n },\n 'context-aggregation': {\n pattern: /((by|without)\\s*)\\([^)]*\\)/, // by ()\n lookbehind: true,\n inside: {\n 'label-key': {\n pattern: /[^(),\\s][^,)]*[^),\\s]*/,\n alias: 'attr-name',\n },\n punctuation: /[()]/,\n },\n },\n 'context-labels': {\n pattern: /\\{[^}]*(?=})/,\n greedy: true,\n inside: {\n comment: {\n pattern: /#.*/,\n },\n 'label-key': {\n pattern: /[a-z_]\\w*(?=\\s*(=|!=|=~|!~))/,\n alias: 'attr-name',\n greedy: true,\n },\n 'label-value': {\n pattern: /\"(?:\\\\.|[^\\\\\"])*\"/,\n greedy: true,\n alias: 'attr-value',\n },\n punctuation: /[{]/,\n },\n },\n function: new RegExp(`\\\\b(?:${FUNCTIONS.map(f => f.label).join('|')})(?=\\\\s*\\\\()`, 'i'),\n 'context-range': [\n {\n pattern: /\\[[^\\]]*(?=])/, // [1m]\n inside: {\n 'range-duration': {\n pattern: /\\b\\d+[smhdwy]\\b/i,\n alias: 'number',\n },\n },\n },\n {\n pattern: /(offset\\s+)\\w+/, // offset 1m\n lookbehind: true,\n inside: {\n 'range-duration': {\n pattern: /\\b\\d+[smhdwy]\\b/i,\n alias: 'number',\n },\n },\n },\n ],\n number: /\\b-?\\d+((\\.\\d*)?([eE][+-]?\\d+)?)?\\b/,\n operator: new RegExp(`/[-+*/=%^~]|&&?|\\\\|?\\\\||!=?|<(?:=>?|<|>)?|>[>=]?|\\\\b(?:${OPERATORS.join('|')})\\\\b`, 'i'),\n punctuation: /[{};()`,.]/,\n};\n\nexport default tokenizer;\n","import { ElasticsearchQuery, PromQuery } from './types';\nimport { DataQuery, LanguageProvider } from '@grafana/data';\nimport { ElasticDatasource } from './datasource';\n\nimport Prism, { Token } from 'prismjs';\nimport grammar from './grammar';\n\nfunction getNameLabelValue(promQuery: string, tokens: any): string {\n let nameLabelValue = '';\n for (let prop in tokens) {\n if (typeof tokens[prop] === 'string') {\n nameLabelValue = tokens[prop] as string;\n break;\n }\n }\n return nameLabelValue;\n}\n\nfunction extractPrometheusLabels(promQuery: string): string[][] {\n const labels: string[][] = [];\n if (!promQuery || promQuery.length === 0) {\n return labels;\n }\n const tokens = Prism.tokenize(promQuery, grammar);\n const nameLabelValue = getNameLabelValue(promQuery, tokens);\n if (nameLabelValue && nameLabelValue.length > 0) {\n labels.push(['__name__', '=', '\"' + nameLabelValue + '\"']);\n }\n\n for (let prop in tokens) {\n if (tokens[prop] instanceof Token) {\n let token: Token = tokens[prop] as Token;\n if (token.type === 'context-labels') {\n let labelKey = '';\n let labelValue = '';\n let labelOperator = '';\n let contentTokens: any[] = token.content as any[];\n for (let currentToken in contentTokens) {\n if (typeof contentTokens[currentToken] === 'string') {\n let currentStr: string;\n currentStr = contentTokens[currentToken] as string;\n if (currentStr === '=' || currentStr === '!=' || currentStr === '=~' || currentStr === '!~') {\n labelOperator = currentStr;\n }\n } else if (contentTokens[currentToken] instanceof Token) {\n switch (contentTokens[currentToken].type) {\n case 'label-key':\n labelKey = contentTokens[currentToken].content as string;\n break;\n case 'label-value':\n labelValue = contentTokens[currentToken].content as string;\n labels.push([labelKey, labelOperator, labelValue]);\n break;\n }\n }\n }\n }\n }\n }\n return labels;\n}\n\nfunction getElasticsearchQuery(prometheusLabels: string[][]): string {\n let elasticsearchLuceneLabels = [];\n for (let keyOperatorValue of prometheusLabels) {\n switch (keyOperatorValue[1]) {\n case '=': {\n elasticsearchLuceneLabels.push(keyOperatorValue[0] + ':' + keyOperatorValue[2]);\n break;\n }\n case '!=': {\n elasticsearchLuceneLabels.push('NOT ' + keyOperatorValue[0] + ':' + keyOperatorValue[2]);\n break;\n }\n case '=~': {\n elasticsearchLuceneLabels.push(\n keyOperatorValue[0] + ':/' + keyOperatorValue[2].substring(1, keyOperatorValue[2].length - 1) + '/'\n );\n break;\n }\n case '!~': {\n elasticsearchLuceneLabels.push(\n 'NOT ' + keyOperatorValue[0] + ':/' + keyOperatorValue[2].substring(1, keyOperatorValue[2].length - 1) + '/'\n );\n break;\n }\n }\n }\n return elasticsearchLuceneLabels.join(' AND ');\n}\n\nexport default class ElasticsearchLanguageProvider extends LanguageProvider {\n request: (url: string, params?: any) => Promise;\n start: () => Promise;\n datasource: ElasticDatasource;\n\n constructor(datasource: ElasticDatasource, initialValues?: any) {\n super();\n this.datasource = datasource;\n\n Object.assign(this, initialValues);\n }\n\n importQueries(queries: DataQuery[], datasourceType: string): ElasticsearchQuery[] {\n if (datasourceType === 'prometheus' || datasourceType === 'loki') {\n return queries.map(query => {\n let prometheusQuery: PromQuery = query as PromQuery;\n const expr = getElasticsearchQuery(extractPrometheusLabels(prometheusQuery.expr));\n return {\n isLogsQuery: true,\n query: expr,\n refId: query.refId,\n };\n });\n }\n return queries.map(query => {\n return {\n isLogsQuery: true,\n query: '',\n refId: query.refId,\n };\n });\n }\n}\n","// Copyright (c) 2014, Hugh Kennedy\n// Based on code from https://github.com/hughsk/flat/blob/master/index.js\n//\nexport default function flatten(target: object, opts?: { delimiter?: any; maxDepth?: any; safe?: any }): any {\n opts = opts || {};\n\n const delimiter = opts.delimiter || '.';\n let maxDepth = opts.maxDepth || 3;\n let currentDepth = 1;\n const output: any = {};\n\n function step(object: any, prev: string | null) {\n Object.keys(object).forEach(key => {\n const value = object[key];\n const isarray = opts?.safe && Array.isArray(value);\n const type = Object.prototype.toString.call(value);\n const isobject = type === '[object Object]';\n\n const newKey = prev ? prev + delimiter + key : key;\n\n if (!opts?.maxDepth) {\n maxDepth = currentDepth + 1;\n }\n\n if (!isarray && isobject && Object.keys(value).length && currentDepth < maxDepth) {\n ++currentDepth;\n return step(value, newKey);\n }\n\n output[newKey] = value;\n });\n }\n\n step(target, null);\n\n return output;\n}\n","import { metricAggregationConfig } from './utils';\n\nexport type PipelineMetricAggregationType =\n | 'moving_avg'\n | 'moving_fn'\n | 'derivative'\n | 'cumulative_sum'\n | 'bucket_script';\n\nexport type MetricAggregationType =\n | 'count'\n | 'avg'\n | 'sum'\n | 'min'\n | 'max'\n | 'extended_stats'\n | 'percentiles'\n | 'cardinality'\n | 'raw_document'\n | 'raw_data'\n | 'logs'\n | PipelineMetricAggregationType;\n\ninterface BaseMetricAggregation {\n id: string;\n type: MetricAggregationType;\n hide?: boolean;\n}\n\nexport interface PipelineVariable {\n name: string;\n pipelineAgg: string;\n}\n\nexport interface MetricAggregationWithField extends BaseMetricAggregation {\n field?: string;\n}\n\nexport interface MetricAggregationWithMissingSupport extends BaseMetricAggregation {\n settings?: {\n missing?: string;\n };\n}\n\nexport interface MetricAggregationWithInlineScript extends BaseMetricAggregation {\n settings?: {\n script?: string;\n };\n}\n\ninterface Count extends BaseMetricAggregation {\n type: 'count';\n}\n\ninterface Average\n extends MetricAggregationWithField,\n MetricAggregationWithMissingSupport,\n MetricAggregationWithInlineScript {\n type: 'avg';\n settings?: {\n script?: string;\n missing?: string;\n };\n}\n\ninterface Sum extends MetricAggregationWithField, MetricAggregationWithInlineScript {\n type: 'sum';\n settings?: {\n script?: string;\n missing?: string;\n };\n}\n\ninterface Max extends MetricAggregationWithField, MetricAggregationWithInlineScript {\n type: 'max';\n settings?: {\n script?: string;\n missing?: string;\n };\n}\n\ninterface Min extends MetricAggregationWithField, MetricAggregationWithInlineScript {\n type: 'min';\n settings?: {\n script?: string;\n missing?: string;\n };\n}\n\nexport type ExtendedStatMetaType =\n | 'avg'\n | 'min'\n | 'max'\n | 'sum'\n | 'count'\n | 'std_deviation'\n | 'std_deviation_bounds_upper'\n | 'std_deviation_bounds_lower';\nexport interface ExtendedStat {\n label: string;\n value: ExtendedStatMetaType;\n}\n\nexport interface ExtendedStats extends MetricAggregationWithField, MetricAggregationWithInlineScript {\n type: 'extended_stats';\n settings?: {\n script?: string;\n missing?: string;\n sigma?: string;\n };\n meta?: {\n [P in ExtendedStatMetaType]?: boolean;\n };\n}\n\ninterface Percentiles extends MetricAggregationWithField, MetricAggregationWithInlineScript {\n type: 'percentiles';\n settings?: {\n percents?: string[];\n script?: string;\n missing?: string;\n };\n}\n\nexport interface UniqueCount extends MetricAggregationWithField {\n type: 'cardinality';\n settings?: {\n precision_threshold?: string;\n missing?: string;\n };\n}\n\ninterface RawDocument extends BaseMetricAggregation {\n type: 'raw_document';\n settings?: {\n size?: string;\n };\n}\n\ninterface RawData extends BaseMetricAggregation {\n type: 'raw_data';\n settings?: {\n size?: string;\n };\n}\n\ninterface Logs extends BaseMetricAggregation {\n type: 'logs';\n}\n\nexport interface BasePipelineMetricAggregation extends MetricAggregationWithField {\n type: PipelineMetricAggregationType;\n}\n\ninterface PipelineMetricAggregationWithMultipleBucketPaths extends BaseMetricAggregation {\n type: PipelineMetricAggregationType;\n pipelineVariables?: PipelineVariable[];\n}\n\nexport type MovingAverageModel = 'simple' | 'linear' | 'ewma' | 'holt' | 'holt_winters';\n\nexport interface MovingAverageModelOption {\n label: string;\n value: MovingAverageModel;\n}\n\ninterface BaseMovingAverageModelSettings {\n model: MovingAverageModel;\n window: number;\n predict: number;\n}\n\ninterface MovingAverageSimpleModelSettings extends BaseMovingAverageModelSettings {\n model: 'simple';\n}\n\ninterface MovingAverageLinearModelSettings extends BaseMovingAverageModelSettings {\n model: 'linear';\n}\n\ninterface MovingAverageEWMAModelSettings extends BaseMovingAverageModelSettings {\n model: 'ewma';\n alpha: number;\n minimize: boolean;\n}\ninterface MovingAverageHoltModelSettings extends BaseMovingAverageModelSettings {\n model: 'holt';\n settings: {\n alpha?: number;\n beta?: number;\n };\n minimize: boolean;\n}\ninterface MovingAverageHoltWintersModelSettings extends BaseMovingAverageModelSettings {\n model: 'holt_winters';\n settings: {\n alpha?: number;\n beta?: number;\n gamma?: number;\n period?: number;\n pad?: boolean;\n };\n minimize: boolean;\n}\n\nexport type MovingAverageModelSettings = Partial<\n Extract<\n | MovingAverageSimpleModelSettings\n | MovingAverageLinearModelSettings\n | MovingAverageEWMAModelSettings\n | MovingAverageHoltModelSettings\n | MovingAverageHoltWintersModelSettings,\n { model: T }\n >\n>;\n\nexport interface MovingAverage\n extends BasePipelineMetricAggregation {\n type: 'moving_avg';\n settings?: MovingAverageModelSettings;\n}\n\nexport const isEWMAMovingAverage = (metric: MovingAverage | MovingAverage<'ewma'>): metric is MovingAverage<'ewma'> =>\n metric.settings?.model === 'ewma';\n\nexport const isHoltMovingAverage = (metric: MovingAverage | MovingAverage<'holt'>): metric is MovingAverage<'holt'> =>\n metric.settings?.model === 'holt';\n\nexport const isHoltWintersMovingAverage = (\n metric: MovingAverage | MovingAverage<'holt_winters'>\n): metric is MovingAverage<'holt_winters'> => metric.settings?.model === 'holt_winters';\n\ninterface MovingFunction extends BasePipelineMetricAggregation {\n type: 'moving_fn';\n settings?: {\n window?: string;\n script?: string;\n shift?: string;\n };\n}\n\nexport interface Derivative extends BasePipelineMetricAggregation {\n type: 'derivative';\n settings?: {\n unit?: string;\n };\n}\n\ninterface CumulativeSum extends BasePipelineMetricAggregation {\n type: 'cumulative_sum';\n settings?: {\n format?: string;\n };\n}\n\nexport interface BucketScript extends PipelineMetricAggregationWithMultipleBucketPaths {\n type: 'bucket_script';\n settings?: {\n script?: string;\n };\n}\n\ntype PipelineMetricAggregation = MovingAverage | Derivative | CumulativeSum | BucketScript;\n\nexport type MetricAggregationWithSettings =\n | BucketScript\n | CumulativeSum\n | Derivative\n | RawData\n | RawDocument\n | UniqueCount\n | Percentiles\n | ExtendedStats\n | Min\n | Max\n | Sum\n | Average\n | MovingAverage\n | MovingFunction;\n\nexport type MetricAggregationWithMeta = ExtendedStats;\n\nexport type MetricAggregation = Count | Logs | PipelineMetricAggregation | MetricAggregationWithSettings;\n\n// Guards\n// Given the structure of the aggregations (ie. `settings` field being always optional) we cannot\n// determine types based solely on objects' properties, therefore we use `metricAggregationConfig` as the\n// source of truth.\n\n/**\n * Checks if `metric` requires a field (either referring to a document or another aggregation)\n * @param metric\n */\nexport const isMetricAggregationWithField = (\n metric: BaseMetricAggregation | MetricAggregationWithField\n): metric is MetricAggregationWithField => metricAggregationConfig[metric.type].requiresField;\n\nexport const isPipelineAggregation = (\n metric: BaseMetricAggregation | PipelineMetricAggregation\n): metric is PipelineMetricAggregation => metricAggregationConfig[metric.type].isPipelineAgg;\n\nexport const isPipelineAggregationWithMultipleBucketPaths = (\n metric: BaseMetricAggregation | PipelineMetricAggregationWithMultipleBucketPaths\n): metric is PipelineMetricAggregationWithMultipleBucketPaths =>\n metricAggregationConfig[metric.type].supportsMultipleBucketPaths;\n\nexport const isMetricAggregationWithMissingSupport = (\n metric: BaseMetricAggregation | MetricAggregationWithMissingSupport\n): metric is MetricAggregationWithMissingSupport => metricAggregationConfig[metric.type].supportsMissing;\n\nexport const isMetricAggregationWithSettings = (\n metric: BaseMetricAggregation | MetricAggregationWithSettings\n): metric is MetricAggregationWithSettings => metricAggregationConfig[metric.type].hasSettings;\n\nexport const isMetricAggregationWithMeta = (\n metric: BaseMetricAggregation | MetricAggregationWithMeta\n): metric is MetricAggregationWithMeta => metricAggregationConfig[metric.type].hasMeta;\n\nexport const isMetricAggregationWithInlineScript = (\n metric: BaseMetricAggregation | MetricAggregationWithInlineScript\n): metric is MetricAggregationWithInlineScript => metricAggregationConfig[metric.type].supportsInlineScript;\n\nexport const METRIC_AGGREGATION_TYPES = [\n 'count',\n 'avg',\n 'sum',\n 'min',\n 'max',\n 'extended_stats',\n 'percentiles',\n 'cardinality',\n 'raw_document',\n 'raw_data',\n 'logs',\n 'moving_avg',\n 'moving_fn',\n 'derivative',\n 'cumulative_sum',\n 'bucket_script',\n];\n\nexport const isMetricAggregationType = (s: MetricAggregationType | string): s is MetricAggregationType =>\n METRIC_AGGREGATION_TYPES.includes(s);\n","import { MetricsConfiguration } from '../../../types';\nimport {\n isMetricAggregationWithField,\n isPipelineAggregationWithMultipleBucketPaths,\n MetricAggregation,\n PipelineMetricAggregationType,\n} from './aggregations';\nimport { defaultPipelineVariable } from './SettingsEditor/BucketScriptSettingsEditor/utils';\n\nexport const metricAggregationConfig: MetricsConfiguration = {\n count: {\n label: 'Count',\n requiresField: false,\n isPipelineAgg: false,\n supportsMissing: false,\n supportsMultipleBucketPaths: false,\n hasSettings: false,\n hasMeta: false,\n supportsInlineScript: false,\n defaults: {},\n },\n avg: {\n label: 'Average',\n requiresField: true,\n supportsInlineScript: true,\n supportsMissing: true,\n isPipelineAgg: false,\n supportsMultipleBucketPaths: false,\n hasSettings: true,\n hasMeta: false,\n defaults: {},\n },\n sum: {\n label: 'Sum',\n requiresField: true,\n supportsInlineScript: true,\n supportsMissing: true,\n isPipelineAgg: false,\n supportsMultipleBucketPaths: false,\n hasSettings: true,\n hasMeta: false,\n defaults: {},\n },\n max: {\n label: 'Max',\n requiresField: true,\n supportsInlineScript: true,\n supportsMissing: true,\n isPipelineAgg: false,\n supportsMultipleBucketPaths: false,\n hasSettings: true,\n hasMeta: false,\n defaults: {},\n },\n min: {\n label: 'Min',\n requiresField: true,\n supportsInlineScript: true,\n supportsMissing: true,\n isPipelineAgg: false,\n supportsMultipleBucketPaths: false,\n hasSettings: true,\n hasMeta: false,\n defaults: {},\n },\n extended_stats: {\n label: 'Extended Stats',\n requiresField: true,\n supportsMissing: true,\n supportsInlineScript: true,\n isPipelineAgg: false,\n supportsMultipleBucketPaths: false,\n hasSettings: true,\n hasMeta: true,\n defaults: {\n meta: {\n std_deviation_bounds_lower: true,\n std_deviation_bounds_upper: true,\n },\n },\n },\n percentiles: {\n label: 'Percentiles',\n requiresField: true,\n supportsMissing: true,\n supportsInlineScript: true,\n isPipelineAgg: false,\n supportsMultipleBucketPaths: false,\n hasSettings: true,\n hasMeta: false,\n defaults: {\n settings: {\n percents: ['25', '50', '75', '95', '99'],\n },\n },\n },\n cardinality: {\n label: 'Unique Count',\n requiresField: true,\n supportsMissing: true,\n isPipelineAgg: false,\n supportsMultipleBucketPaths: false,\n hasSettings: true,\n supportsInlineScript: false,\n hasMeta: false,\n defaults: {},\n },\n moving_avg: {\n label: 'Moving Average',\n requiresField: true,\n isPipelineAgg: true,\n minVersion: 2,\n supportsMissing: false,\n supportsMultipleBucketPaths: false,\n hasSettings: true,\n supportsInlineScript: false,\n hasMeta: false,\n defaults: {\n settings: {\n model: 'simple',\n window: 5,\n },\n },\n },\n moving_fn: {\n // TODO: Check this\n label: 'Moving Function',\n requiresField: true,\n isPipelineAgg: true,\n supportsMultipleBucketPaths: false,\n supportsInlineScript: false,\n supportsMissing: false,\n hasMeta: false,\n hasSettings: true,\n minVersion: 70,\n defaults: {},\n },\n derivative: {\n label: 'Derivative',\n requiresField: true,\n isPipelineAgg: true,\n minVersion: 2,\n supportsMissing: false,\n supportsMultipleBucketPaths: false,\n hasSettings: true,\n supportsInlineScript: false,\n hasMeta: false,\n defaults: {},\n },\n cumulative_sum: {\n label: 'Cumulative Sum',\n requiresField: true,\n isPipelineAgg: true,\n minVersion: 2,\n supportsMissing: false,\n supportsMultipleBucketPaths: false,\n hasSettings: true,\n supportsInlineScript: false,\n hasMeta: false,\n defaults: {},\n },\n bucket_script: {\n label: 'Bucket Script',\n requiresField: false,\n isPipelineAgg: true,\n supportsMissing: false,\n supportsMultipleBucketPaths: true,\n minVersion: 2,\n hasSettings: true,\n supportsInlineScript: false,\n hasMeta: false,\n defaults: {\n pipelineVariables: [defaultPipelineVariable()],\n },\n },\n raw_document: {\n label: 'Raw Document (legacy)',\n requiresField: false,\n isSingleMetric: true,\n isPipelineAgg: false,\n supportsMissing: false,\n supportsMultipleBucketPaths: false,\n hasSettings: true,\n supportsInlineScript: false,\n hasMeta: false,\n defaults: {\n settings: {\n size: '500',\n },\n },\n },\n raw_data: {\n label: 'Raw Data',\n requiresField: false,\n isSingleMetric: true,\n isPipelineAgg: false,\n supportsMissing: false,\n supportsMultipleBucketPaths: false,\n hasSettings: false,\n supportsInlineScript: false,\n hasMeta: false,\n defaults: {\n settings: {\n size: '500',\n },\n },\n },\n logs: {\n label: 'Logs',\n requiresField: false,\n isPipelineAgg: false,\n supportsMissing: false,\n supportsMultipleBucketPaths: false,\n hasSettings: false,\n supportsInlineScript: false,\n hasMeta: false,\n defaults: {},\n },\n};\n\ninterface PipelineOption {\n label: string;\n default?: string | number | boolean;\n}\n\ntype PipelineOptions = {\n [K in PipelineMetricAggregationType]: PipelineOption[];\n};\n\nexport const pipelineOptions: PipelineOptions = {\n moving_avg: [\n { label: 'window', default: 5 },\n { label: 'model', default: 'simple' },\n { label: 'predict' },\n { label: 'minimize', default: false },\n ],\n moving_fn: [{ label: 'window', default: 5 }, { label: 'script' }],\n derivative: [{ label: 'unit' }],\n cumulative_sum: [{ label: 'format' }],\n bucket_script: [],\n};\n\n/**\n * Given a metric `MetricA` and an array of metrics, returns all children of `MetricA`.\n * `MetricB` is considered a child of `MetricA` if `MetricA` is referenced by `MetricB` in it's `field` attribute\n * (`MetricA.id === MetricB.field`) or in it's pipeline aggregation variables (for bucket_scripts).\n * @param metric\n * @param metrics\n */\nexport const getChildren = (metric: MetricAggregation, metrics: MetricAggregation[]): MetricAggregation[] => {\n const children = metrics.filter(m => {\n // TODO: Check this.\n if (isPipelineAggregationWithMultipleBucketPaths(m)) {\n return m.pipelineVariables?.some(pv => pv.pipelineAgg === metric.id);\n }\n\n return isMetricAggregationWithField(m) && metric.id === m.field;\n });\n\n return [...children, ...children.flatMap(child => getChildren(child, metrics))];\n};\n","import { PipelineVariable } from '../../aggregations';\n\nexport const defaultPipelineVariable = (): PipelineVariable => ({ name: 'var1', pipelineAgg: '' });\n","import { BucketAggregation } from './components/QueryEditor/BucketAggregationsEditor/aggregations';\nimport {\n ExtendedStat,\n MetricAggregation,\n MovingAverageModelOption,\n MetricAggregationType,\n} from './components/QueryEditor/MetricAggregationsEditor/aggregations';\nimport { metricAggregationConfig, pipelineOptions } from './components/QueryEditor/MetricAggregationsEditor/utils';\nimport { PPLFormatType } from './components/QueryEditor/PPLFormatEditor/formats';\n\nexport const extendedStats: ExtendedStat[] = [\n { label: 'Avg', value: 'avg' },\n { label: 'Min', value: 'min' },\n { label: 'Max', value: 'max' },\n { label: 'Sum', value: 'sum' },\n { label: 'Count', value: 'count' },\n { label: 'Std Dev', value: 'std_deviation' },\n { label: 'Std Dev Upper', value: 'std_deviation_bounds_upper' },\n { label: 'Std Dev Lower', value: 'std_deviation_bounds_lower' },\n];\n\nexport const movingAvgModelOptions: MovingAverageModelOption[] = [\n { label: 'Simple', value: 'simple' },\n { label: 'Linear', value: 'linear' },\n { label: 'Exponentially Weighted', value: 'ewma' },\n { label: 'Holt Linear', value: 'holt' },\n { label: 'Holt Winters', value: 'holt_winters' },\n];\n\nexport function defaultMetricAgg(id = '1'): MetricAggregation {\n return { type: 'count', id };\n}\n\nexport function defaultBucketAgg(id = '1'): BucketAggregation {\n return { type: 'date_histogram', id, settings: { interval: 'auto' } };\n}\n\nexport function defaultPPLFormat(): PPLFormatType {\n return 'table';\n}\n\nexport const findMetricById = (metrics: MetricAggregation[], id: MetricAggregation['id']) =>\n metrics.find(metric => metric.id === id);\n\nexport function hasMetricOfType(target: any, type: string): boolean {\n return target && target.metrics && target.metrics.some((m: any) => m.type === type);\n}\n\n// Even if we have type guards when building a query, we currently have no way of getting this information from the response.\n// We should try to find a better (type safe) way of doing the following 2.\nexport function isPipelineAgg(metricType: MetricAggregationType) {\n return metricType in pipelineOptions;\n}\n\nexport function isPipelineAggWithMultipleBucketPaths(metricType: MetricAggregationType) {\n return !!metricAggregationConfig[metricType].supportsMultipleBucketPaths;\n}\n","import _ from 'lodash';\nimport { Column, TableData, QueryResultMeta } from '@grafana/data';\n\n/**\n * Extends the standard Column class with variables that get\n * mutated in the angular table panel.\n */\nexport interface MutableColumn extends Column {\n title?: string;\n sort?: boolean;\n desc?: boolean;\n type?: string;\n}\n\nexport default class TableModel implements TableData {\n columns: MutableColumn[];\n rows: any[];\n type: string;\n columnMap: any;\n refId?: string;\n meta?: QueryResultMeta;\n\n constructor(table?: any) {\n this.columns = [];\n this.columnMap = {};\n this.rows = [];\n this.type = 'table';\n\n if (table) {\n if (table.columns) {\n for (const col of table.columns) {\n this.addColumn(col);\n }\n }\n if (table.rows) {\n for (const row of table.rows) {\n this.addRow(row);\n }\n }\n }\n }\n\n sort(options: { col: number; desc: boolean }) {\n if (options.col === null || this.columns.length <= options.col) {\n return;\n }\n\n this.rows.sort((a, b) => {\n a = a[options.col];\n b = b[options.col];\n // Sort null or undefined separately from comparable values\n return +(a == null) - +(b == null) || +(a > b) || -(a < b);\n });\n\n if (options.desc) {\n this.rows.reverse();\n }\n\n this.columns[options.col].sort = true;\n this.columns[options.col].desc = options.desc;\n }\n\n addColumn(col: Column) {\n if (!this.columnMap[col.text]) {\n this.columns.push(col);\n this.columnMap[col.text] = col;\n }\n }\n\n addRow(row: any[]) {\n this.rows.push(row);\n }\n}\n\n// Returns true if both rows have matching non-empty fields as well as matching\n// indexes where one field is empty and the other is not\nfunction areRowsMatching(columns: Column[], row: any[], otherRow: any[]) {\n let foundFieldToMatch = false;\n for (let columnIndex = 0; columnIndex < columns.length; columnIndex++) {\n if (row[columnIndex] !== undefined && otherRow[columnIndex] !== undefined) {\n if (row[columnIndex] !== otherRow[columnIndex]) {\n return false;\n }\n } else if (row[columnIndex] === undefined || otherRow[columnIndex] === undefined) {\n foundFieldToMatch = true;\n }\n }\n return foundFieldToMatch;\n}\n\nexport function mergeTablesIntoModel(dst?: TableModel, ...tables: TableModel[]): TableModel {\n const model = dst || new TableModel();\n\n if (arguments.length === 1) {\n return model;\n }\n // Single query returns data columns and rows as is\n if (arguments.length === 2) {\n model.columns = tables[0].hasOwnProperty('columns') ? [...tables[0].columns] : [];\n model.rows = tables[0].hasOwnProperty('rows') ? [...tables[0].rows] : [];\n return model;\n }\n\n // Filter out any tables that are not of TableData format\n const tableDataTables = tables.filter(table => !!table.columns);\n\n // Track column indexes of union: name -> index\n const columnNames: { [key: string]: any } = {};\n\n // Union of all non-value columns\n const columnsUnion = tableDataTables.slice().reduce((acc, series) => {\n series.columns.forEach(col => {\n const { text } = col;\n if (columnNames[text] === undefined) {\n columnNames[text] = acc.length;\n acc.push(col);\n }\n });\n return acc;\n }, [] as MutableColumn[]);\n\n // Map old column index to union index per series, e.g.,\n // given columnNames {A: 0, B: 1} and\n // data [{columns: [{ text: 'A' }]}, {columns: [{ text: 'B' }]}] => [[0], [1]]\n const columnIndexMapper = tableDataTables.map(series => series.columns.map(col => columnNames[col.text]));\n\n // Flatten rows of all series and adjust new column indexes\n const flattenedRows = tableDataTables.reduce((acc, series, seriesIndex) => {\n const mapper = columnIndexMapper[seriesIndex];\n series.rows.forEach(row => {\n const alteredRow: MutableColumn[] = [];\n // Shifting entries according to index mapper\n mapper.forEach((to, from) => {\n alteredRow[to] = row[from];\n });\n acc.push(alteredRow);\n });\n return acc;\n }, [] as MutableColumn[][]);\n\n // Merge rows that have same values for columns\n const mergedRows: { [key: string]: any } = {};\n\n const compactedRows = flattenedRows.reduce((acc, row, rowIndex) => {\n if (!mergedRows[rowIndex]) {\n // Look from current row onwards\n let offset = rowIndex + 1;\n // More than one row can be merged into current row\n while (offset < flattenedRows.length) {\n // Find next row that could be merged\n const match = _.findIndex(flattenedRows, otherRow => areRowsMatching(columnsUnion, row, otherRow), offset);\n if (match > -1) {\n const matchedRow = flattenedRows[match];\n // Merge values from match into current row if there is a gap in the current row\n for (let columnIndex = 0; columnIndex < columnsUnion.length; columnIndex++) {\n if (row[columnIndex] === undefined && matchedRow[columnIndex] !== undefined) {\n row[columnIndex] = matchedRow[columnIndex];\n }\n }\n // Don't visit this row again\n mergedRows[match] = matchedRow;\n // Keep looking for more rows to merge\n offset = match + 1;\n } else {\n // No match found, stop looking\n break;\n }\n }\n acc.push(row);\n }\n return acc;\n }, [] as MutableColumn[][]);\n\n model.columns = columnsUnion;\n model.rows = compactedRows;\n return model;\n}\n","import { DataQuery, DataSourceJsonData } from '@grafana/data';\nimport {\n BucketAggregation,\n BucketAggregationType,\n} from './components/QueryEditor/BucketAggregationsEditor/aggregations';\nimport {\n MetricAggregation,\n MetricAggregationType,\n} from './components/QueryEditor/MetricAggregationsEditor/aggregations';\nimport { PPLFormatType } from './components/QueryEditor/PPLFormatEditor/formats';\n\nexport interface ElasticsearchOptions extends DataSourceJsonData {\n database: string;\n timeField: string;\n esVersion: number;\n interval?: string;\n timeInterval: string;\n maxConcurrentShardRequests?: number;\n logMessageField?: string;\n logLevelField?: string;\n dataLinks?: DataLinkConfig[];\n pplEnabled?: boolean;\n}\n\ninterface MetricConfiguration {\n label: string;\n requiresField: boolean;\n supportsInlineScript: boolean;\n supportsMissing: boolean;\n isPipelineAgg: boolean;\n minVersion?: number;\n maxVersion?: number;\n supportsMultipleBucketPaths: boolean;\n isSingleMetric?: boolean;\n hasSettings: boolean;\n hasMeta: boolean;\n defaults: Omit, 'id' | 'type'>;\n}\n\ntype BucketConfiguration = {\n label: string;\n requiresField: boolean;\n defaultSettings: Extract['settings'];\n};\n\nexport type MetricsConfiguration = {\n [P in MetricAggregationType]: MetricConfiguration

;\n};\n\nexport type BucketsConfiguration = {\n [P in BucketAggregationType]: BucketConfiguration

;\n};\n\nexport type QueryTypeConfiguration = {\n [P in ElasticsearchQueryType]: { label: string };\n};\n\nexport type FormatConfiguration = {\n [P in PPLFormatType]: { label: string };\n};\n\nexport interface ElasticsearchAggregation {\n id: string;\n type: MetricAggregationType | BucketAggregationType;\n settings?: unknown;\n field?: string;\n hide: boolean;\n}\n\nexport interface ElasticsearchQuery extends DataQuery {\n isLogsQuery?: boolean;\n alias?: string;\n query?: string;\n bucketAggs?: BucketAggregation[];\n metrics?: MetricAggregation[];\n timeField?: string;\n queryType?: ElasticsearchQueryType;\n format?: PPLFormatType;\n}\n\nexport type DataLinkConfig = {\n field: string;\n url: string;\n datasourceUid?: string;\n};\n\nexport enum ElasticsearchQueryType {\n Lucene = 'lucene',\n PPL = 'PPL',\n}\n\nexport interface PromQuery extends DataQuery {\n expr: string;\n format?: string;\n instant?: boolean;\n range?: boolean;\n hinting?: boolean;\n interval?: string;\n intervalFactor?: number;\n legendFormat?: string;\n valueWithRefId?: boolean;\n requestId?: string;\n showingGraph?: boolean;\n showingTable?: boolean;\n}\n","import {\n isMetricAggregationWithField,\n MetricAggregation,\n} from './components/QueryEditor/MetricAggregationsEditor/aggregations';\nimport { metricAggregationConfig } from './components/QueryEditor/MetricAggregationsEditor/utils';\n\nexport const describeMetric = (metric: MetricAggregation) => {\n if (!isMetricAggregationWithField(metric)) {\n return metricAggregationConfig[metric.type].label;\n }\n\n // TODO: field might be undefined\n return `${metricAggregationConfig[metric.type].label} ${metric.field}`;\n};\n\n/**\n * Utility function to clean up aggregations settings objects.\n * It removes nullish values and empty strings, array and objects\n * recursing over nested objects (not arrays).\n * @param obj\n */\nexport const removeEmpty = (obj: T): Partial =>\n Object.entries(obj).reduce((acc, [key, value]) => {\n // Removing nullish values (null & undefined)\n if (value == null) {\n return { ...acc };\n }\n\n // Removing empty arrays (This won't recurse the array)\n if (Array.isArray(value) && value.length === 0) {\n return { ...acc };\n }\n\n // Removing empty strings\n if (value?.length === 0) {\n return { ...acc };\n }\n\n // Recursing over nested objects\n if (!Array.isArray(value) && typeof value === 'object') {\n const cleanObj = removeEmpty(value);\n\n if (Object.keys(cleanObj).length === 0) {\n return { ...acc };\n }\n\n return { ...acc, [key]: cleanObj };\n }\n\n return {\n ...acc,\n [key]: value,\n };\n }, {});\n","import _ from 'lodash';\nimport flatten from './dependencies/flatten';\nimport * as queryDef from './query_def';\nimport TableModel from './dependencies/table_model';\nimport {\n dateTime,\n DataQueryResponse,\n DataFrame,\n toDataFrame,\n FieldType,\n MutableDataFrame,\n PreferredVisualisationType,\n} from '@grafana/data';\nimport { ElasticsearchAggregation, ElasticsearchQuery, ElasticsearchQueryType } from './types';\nimport {\n ExtendedStatMetaType,\n isMetricAggregationWithField,\n} from './components/QueryEditor/MetricAggregationsEditor/aggregations';\nimport { describeMetric } from './utils';\nimport { metricAggregationConfig } from './components/QueryEditor/MetricAggregationsEditor/utils';\n\nexport class ElasticResponse {\n constructor(\n private targets: ElasticsearchQuery[],\n private response: any,\n private targetType: ElasticsearchQueryType = ElasticsearchQueryType.Lucene\n ) {\n this.targets = targets;\n this.response = response;\n this.targetType = targetType;\n }\n\n processMetrics(esAgg: any, target: ElasticsearchQuery, seriesList: any, props: any) {\n let newSeries: any;\n\n for (let y = 0; y < target.metrics!.length; y++) {\n const metric = target.metrics![y];\n if (metric.hide) {\n continue;\n }\n\n switch (metric.type) {\n case 'count': {\n newSeries = { datapoints: [], metric: 'count', props, refId: target.refId };\n for (let i = 0; i < esAgg.buckets.length; i++) {\n const bucket = esAgg.buckets[i];\n const value = bucket.doc_count;\n newSeries.datapoints.push([value, bucket.key]);\n }\n seriesList.push(newSeries);\n break;\n }\n case 'percentiles': {\n if (esAgg.buckets.length === 0) {\n break;\n }\n\n const firstBucket = esAgg.buckets[0];\n const percentiles = firstBucket[metric.id].values;\n\n for (const percentileName in percentiles) {\n newSeries = {\n datapoints: [],\n metric: 'p' + percentileName,\n props: props,\n field: metric.field,\n refId: target.refId,\n };\n\n for (let i = 0; i < esAgg.buckets.length; i++) {\n const bucket = esAgg.buckets[i];\n const values = bucket[metric.id].values;\n newSeries.datapoints.push([values[percentileName], bucket.key]);\n }\n seriesList.push(newSeries);\n }\n\n break;\n }\n case 'extended_stats': {\n for (const statName in metric.meta) {\n if (!metric.meta[statName as ExtendedStatMetaType]) {\n continue;\n }\n\n newSeries = {\n datapoints: [],\n metric: statName,\n props: props,\n field: metric.field,\n refId: target.refId,\n };\n\n for (let i = 0; i < esAgg.buckets.length; i++) {\n const bucket = esAgg.buckets[i];\n const stats = bucket[metric.id];\n\n // add stats that are in nested obj to top level obj\n stats.std_deviation_bounds_upper = stats.std_deviation_bounds.upper;\n stats.std_deviation_bounds_lower = stats.std_deviation_bounds.lower;\n\n newSeries.datapoints.push([stats[statName], bucket.key]);\n }\n\n seriesList.push(newSeries);\n }\n\n break;\n }\n default: {\n newSeries = {\n datapoints: [],\n metric: metric.type,\n metricId: metric.id,\n props: props,\n refId: target.refId,\n };\n\n if (isMetricAggregationWithField(metric)) {\n newSeries.field = metric.field;\n }\n\n for (let i = 0; i < esAgg.buckets.length; i++) {\n const bucket = esAgg.buckets[i];\n const value = bucket[metric.id];\n\n if (value !== undefined) {\n if (value.normalized_value) {\n newSeries.datapoints.push([value.normalized_value, bucket.key]);\n } else {\n newSeries.datapoints.push([value.value, bucket.key]);\n }\n }\n }\n seriesList.push(newSeries);\n break;\n }\n }\n }\n }\n\n processAggregationDocs(\n esAgg: any,\n aggDef: ElasticsearchAggregation,\n target: ElasticsearchQuery,\n table: any,\n props: any\n ) {\n // add columns\n if (table.columns.length === 0) {\n for (const propKey of _.keys(props)) {\n table.addColumn({ text: propKey, filterable: true });\n }\n table.addColumn({ text: aggDef.field, filterable: true });\n }\n\n // helper func to add values to value array\n const addMetricValue = (values: any[], metricName: string, value: any) => {\n table.addColumn({ text: metricName });\n values.push(value);\n };\n const buckets = _.isArray(esAgg.buckets) ? esAgg.buckets : [esAgg.buckets];\n for (const bucket of buckets) {\n const values = [];\n\n for (const propValues of _.values(props)) {\n values.push(propValues);\n }\n\n // add bucket key (value)\n values.push(bucket.key);\n\n for (const metric of target.metrics || []) {\n switch (metric.type) {\n case 'count': {\n addMetricValue(values, this.getMetricName(metric.type), bucket.doc_count);\n break;\n }\n case 'extended_stats': {\n for (const statName in metric.meta) {\n if (!metric.meta[statName as ExtendedStatMetaType]) {\n continue;\n }\n\n const stats = bucket[metric.id];\n // add stats that are in nested obj to top level obj\n stats.std_deviation_bounds_upper = stats.std_deviation_bounds.upper;\n stats.std_deviation_bounds_lower = stats.std_deviation_bounds.lower;\n\n addMetricValue(values, this.getMetricName(statName as ExtendedStatMetaType), stats[statName]);\n }\n break;\n }\n case 'percentiles': {\n const percentiles = bucket[metric.id].values;\n\n for (const percentileName in percentiles) {\n addMetricValue(values, `p${percentileName} ${metric.field}`, percentiles[percentileName]);\n }\n break;\n }\n default: {\n let metricName = this.getMetricName(metric.type);\n const otherMetrics = _.filter(target.metrics, { type: metric.type });\n\n // if more of the same metric type include field field name in property\n if (otherMetrics.length > 1) {\n if (isMetricAggregationWithField(metric)) {\n metricName += ' ' + metric.field;\n }\n\n if (metric.type === 'bucket_script') {\n //Use the formula in the column name\n metricName = metric.settings?.script || '';\n }\n }\n\n addMetricValue(values, metricName, bucket[metric.id].value);\n break;\n }\n }\n }\n\n table.rows.push(values);\n }\n }\n\n // This is quite complex\n // need to recurse down the nested buckets to build series\n processBuckets(aggs: any, target: ElasticsearchQuery, seriesList: any, table: TableModel, props: any, depth: number) {\n let bucket, aggDef: any, esAgg, aggId;\n const maxDepth = target.bucketAggs!.length - 1;\n\n for (aggId in aggs) {\n aggDef = _.find(target.bucketAggs, { id: aggId });\n esAgg = aggs[aggId];\n\n if (!aggDef) {\n continue;\n }\n\n if (depth === maxDepth) {\n if (aggDef.type === 'date_histogram') {\n this.processMetrics(esAgg, target, seriesList, props);\n } else {\n this.processAggregationDocs(esAgg, aggDef, target, table, props);\n }\n } else {\n for (const nameIndex in esAgg.buckets) {\n bucket = esAgg.buckets[nameIndex];\n props = _.clone(props);\n if (bucket.key !== void 0) {\n props[aggDef.field] = bucket.key;\n } else {\n props['filter'] = nameIndex;\n }\n if (bucket.key_as_string) {\n props[aggDef.field] = bucket.key_as_string;\n }\n this.processBuckets(bucket, target, seriesList, table, props, depth + 1);\n }\n }\n }\n }\n\n private getMetricName(metric: string): string {\n const metricDef = Object.entries(metricAggregationConfig)\n .filter(([key]) => key === metric)\n .map(([_, value]) => value)[0];\n\n if (metricDef) {\n return metricDef.label;\n }\n\n const extendedStat = queryDef.extendedStats.find(e => e.value === metric);\n if (extendedStat) {\n return extendedStat.label;\n }\n\n return metric;\n }\n\n private getSeriesName(series: any, target: ElasticsearchQuery, metricTypeCount: any) {\n let metricName = this.getMetricName(series.metric);\n\n if (target.alias) {\n const regex = /\\{\\{([\\s\\S]+?)\\}\\}/g;\n\n return target.alias.replace(regex, (match: any, g1: any, g2: any) => {\n const group = g1 || g2;\n\n if (group.indexOf('term ') === 0) {\n return series.props[group.substring(5)];\n }\n if (series.props[group] !== void 0) {\n return series.props[group];\n }\n if (group === 'metric') {\n return metricName;\n }\n if (group === 'field') {\n return series.field || '';\n }\n\n return match;\n });\n }\n\n if (queryDef.isPipelineAgg(series.metric)) {\n if (series.metric && queryDef.isPipelineAggWithMultipleBucketPaths(series.metric)) {\n const agg: any = _.find(target.metrics, { id: series.metricId });\n if (agg && agg.settings.script) {\n metricName = agg.settings.script;\n\n for (const pv of agg.pipelineVariables) {\n const appliedAgg: any = _.find(target.metrics, { id: pv.pipelineAgg });\n if (appliedAgg) {\n metricName = metricName.replace('params.' + pv.name, describeMetric(appliedAgg));\n }\n }\n } else {\n metricName = 'Unset';\n }\n } else {\n const appliedAgg: any = _.find(target.metrics, { id: series.field });\n if (appliedAgg) {\n metricName += ' ' + describeMetric(appliedAgg);\n } else {\n metricName = 'Unset';\n }\n }\n } else if (series.field) {\n metricName += ' ' + series.field;\n }\n\n const propKeys = _.keys(series.props);\n if (propKeys.length === 0) {\n return metricName;\n }\n\n let name = '';\n for (const propName in series.props) {\n name += series.props[propName] + ' ';\n }\n\n if (metricTypeCount === 1) {\n return name.trim();\n }\n\n return name.trim() + ' ' + metricName;\n }\n\n nameSeries(seriesList: any, target: ElasticsearchQuery) {\n const metricTypeCount = _.uniq(_.map(seriesList, 'metric')).length;\n\n for (let i = 0; i < seriesList.length; i++) {\n const series = seriesList[i];\n series.target = this.getSeriesName(series, target, metricTypeCount);\n }\n }\n\n processHits(hits: { total: { value: any }; hits: any[] }, seriesList: any[], target: ElasticsearchQuery) {\n const hitsTotal = typeof hits.total === 'number' ? hits.total : hits.total.value; // <- Works with Elasticsearch 7.0+\n\n const series: any = {\n target: target.refId,\n type: 'docs',\n refId: target.refId,\n datapoints: [],\n total: hitsTotal,\n filterable: true,\n };\n let propName, hit, doc: any, i;\n\n for (i = 0; i < hits.hits.length; i++) {\n hit = hits.hits[i];\n doc = {\n _id: hit._id,\n _type: hit._type,\n _index: hit._index,\n };\n\n if (hit._source) {\n for (propName in hit._source) {\n doc[propName] = hit._source[propName];\n }\n }\n\n for (propName in hit.fields) {\n doc[propName] = hit.fields[propName];\n }\n series.datapoints.push(doc);\n }\n\n seriesList.push(series);\n }\n\n trimDatapoints(aggregations: any, target: ElasticsearchQuery) {\n const histogram: any = _.find(target.bucketAggs, { type: 'date_histogram' });\n\n const shouldDropFirstAndLast = histogram && histogram.settings && histogram.settings.trimEdges;\n if (shouldDropFirstAndLast) {\n const trim = histogram.settings.trimEdges;\n for (const prop in aggregations) {\n const points = aggregations[prop];\n if (points.datapoints.length > trim * 2) {\n points.datapoints = points.datapoints.slice(trim, points.datapoints.length - trim);\n }\n }\n }\n }\n\n getErrorFromElasticResponse(response: any, err: any) {\n const result: any = {};\n result.data = JSON.stringify(err, null, 4);\n if (err.root_cause && err.root_cause.length > 0 && err.root_cause[0].reason) {\n result.message = err.root_cause[0].reason;\n } else {\n result.message = err.reason || 'Unknown elastic error response';\n }\n\n if (response.$$config) {\n result.config = response.$$config;\n }\n\n return result;\n }\n\n getInvalidPPLQuery(response: any) {\n const result: any = {};\n result.message = 'Invalid time series query';\n\n if (response.$$config) {\n result.config = response.$$config;\n }\n\n return result;\n }\n\n getTimeSeries() {\n if (this.targetType === ElasticsearchQueryType.PPL) {\n return this.processPPLResponseToSeries();\n } else if (this.targets.some(target => target.metrics?.some(metric => metric.type === 'raw_data'))) {\n return this.processResponseToDataFrames(false);\n }\n return this.processResponseToSeries();\n }\n\n getLogs(logMessageField?: string, logLevelField?: string): DataQueryResponse {\n if (this.targetType === ElasticsearchQueryType.PPL) {\n return this.processPPLResponseToDataFrames(true, logMessageField, logLevelField);\n }\n return this.processResponseToDataFrames(true, logMessageField, logLevelField);\n }\n\n getTable() {\n return this.processPPLResponseToDataFrames(false);\n }\n\n processResponseToDataFrames(\n isLogsRequest: boolean,\n logMessageField?: string,\n logLevelField?: string\n ): DataQueryResponse {\n const dataFrame: DataFrame[] = [];\n\n for (let n = 0; n < this.response.responses.length; n++) {\n const response = this.response.responses[n];\n if (response.error) {\n throw this.getErrorFromElasticResponse(this.response, response.error);\n }\n\n if (response.hits && response.hits.hits.length > 0) {\n const { propNames, docs } = flattenHits(response.hits.hits);\n if (docs.length > 0) {\n let series = createEmptyDataFrame(\n propNames,\n this.targets[0].timeField!,\n isLogsRequest,\n this.targetType,\n logMessageField,\n logLevelField\n );\n\n // Add a row for each document\n for (const doc of docs) {\n if (logLevelField) {\n // Remap level field based on the datasource config. This field is then used in explore to figure out the\n // log level. We may rewrite some actual data in the level field if they are different.\n doc['level'] = doc[logLevelField];\n }\n\n series.add(doc);\n }\n if (isLogsRequest) {\n series = addPreferredVisualisationType(series, 'logs');\n }\n const target = this.targets[n];\n series.refId = target.refId;\n dataFrame.push(series);\n }\n }\n\n if (response.aggregations) {\n const aggregations = response.aggregations;\n const target = this.targets[n];\n const tmpSeriesList: any[] = [];\n const table = new TableModel();\n\n this.processBuckets(aggregations, target, tmpSeriesList, table, {}, 0);\n this.trimDatapoints(tmpSeriesList, target);\n this.nameSeries(tmpSeriesList, target);\n\n if (table.rows.length > 0) {\n const series = toDataFrame(table);\n series.refId = target.refId;\n dataFrame.push(series);\n }\n\n for (let y = 0; y < tmpSeriesList.length; y++) {\n let series = toDataFrame(tmpSeriesList[y]);\n\n // When log results, show aggregations only in graph. Log fields are then going to be shown in table.\n if (isLogsRequest) {\n series = addPreferredVisualisationType(series, 'graph');\n }\n\n series.refId = target.refId;\n dataFrame.push(series);\n }\n }\n }\n\n return { data: dataFrame, key: this.targets[0]?.refId };\n }\n\n processResponseToSeries = () => {\n const seriesList = [];\n\n for (let i = 0; i < this.response.responses.length; i++) {\n const response = this.response.responses[i];\n const target = this.targets[i];\n\n if (response.error) {\n throw this.getErrorFromElasticResponse(this.response, response.error);\n }\n\n if (response.hits && response.hits.hits.length > 0) {\n this.processHits(response.hits, seriesList, target);\n }\n\n if (response.aggregations) {\n const aggregations = response.aggregations;\n const target = this.targets[i];\n const tmpSeriesList: any[] = [];\n const table = new TableModel();\n table.refId = target.refId;\n\n this.processBuckets(aggregations, target, tmpSeriesList, table, {}, 0);\n this.trimDatapoints(tmpSeriesList, target);\n this.nameSeries(tmpSeriesList, target);\n\n for (let y = 0; y < tmpSeriesList.length; y++) {\n seriesList.push(tmpSeriesList[y]);\n }\n\n if (table.rows.length > 0) {\n seriesList.push(table);\n }\n }\n }\n\n return { data: seriesList, key: this.targets[0]?.refId };\n };\n\n processPPLResponseToSeries = () => {\n const target = this.targets[0];\n const response = this.response;\n const seriesList = [];\n\n if (response.datarows.length > 0) {\n // Handle error from Elasticsearch\n if (response.error) {\n throw this.getErrorFromElasticResponse(this.response, response.error);\n }\n // Get the data points and target that will be inputted to newSeries\n const { datapoints, targetVal, invalidTS } = getPPLDatapoints(response);\n\n // We throw an error if the inputted query is not valid\n if (invalidTS) {\n throw this.getInvalidPPLQuery(this.response);\n }\n\n const newSeries = {\n datapoints,\n props: response.schema,\n refId: target.refId,\n target: targetVal,\n };\n seriesList.push(newSeries);\n }\n return { data: seriesList, key: this.targets[0]?.refId };\n };\n\n processPPLResponseToDataFrames(\n isLogsRequest: boolean,\n logMessageField?: string,\n logLevelField?: string\n ): DataQueryResponse {\n if (this.response.error) {\n throw this.getErrorFromElasticResponse(this.response, this.response.error);\n }\n\n const dataFrame: DataFrame[] = [];\n\n //map the schema into an array of string containing its name\n const schema = this.response.schema.map((a: { name: any }) => a.name);\n //combine the schema key and response value\n const response = _.map(this.response.datarows, arr => _.zipObject(schema, arr));\n //flatten the response\n const { flattenSchema, docs } = flattenResponses(response);\n\n if (response.length > 0) {\n let series = createEmptyDataFrame(\n flattenSchema,\n this.targets[0].timeField!,\n isLogsRequest,\n this.targetType,\n logMessageField,\n logLevelField\n );\n // Add a row for each document\n for (const doc of docs) {\n if (logLevelField) {\n // Remap level field based on the datasource config. This field is then used in explore to figure out the\n // log level. We may rewrite some actual data in the level field if they are different.\n doc['level'] = doc[logLevelField];\n }\n series.add(doc);\n }\n if (isLogsRequest) {\n series = addPreferredVisualisationType(series, 'logs');\n }\n const target = this.targets[0];\n series.refId = target.refId;\n dataFrame.push(series);\n }\n return { data: dataFrame, key: this.targets[0]?.refId };\n }\n}\n\ntype Doc = {\n _id: string;\n _type: string;\n _index: string;\n _source?: any;\n};\n\n/**\n * Flatten the docs from response mainly the _source part which can be nested. This flattens it so that it is one level\n * deep and the keys are: `level1Name.level2Name...`. Also returns list of all properties from all the docs (not all\n * docs have to have the same keys).\n * @param hits\n */\nconst flattenHits = (hits: Doc[]): { docs: Array>; propNames: string[] } => {\n const docs: any[] = [];\n // We keep a list of all props so that we can create all the fields in the dataFrame, this can lead\n // to wide sparse dataframes in case the scheme is different per document.\n let propNames: string[] = [];\n\n for (const hit of hits) {\n const flattened = hit._source ? flatten(hit._source) : {};\n const doc = {\n _id: hit._id,\n _type: hit._type,\n _index: hit._index,\n _source: { ...flattened },\n ...flattened,\n };\n\n for (const propName of Object.keys(doc)) {\n if (propNames.indexOf(propName) === -1) {\n propNames.push(propName);\n }\n }\n\n docs.push(doc);\n }\n\n propNames.sort();\n return { docs, propNames };\n};\n\n/**\n * Flatten the response which can be nested. This flattens it so that it is one level deep and the keys are:\n * `level1Name.level2Name...`. Also returns list of all schemas from all the response\n * @param responses\n */\nconst flattenResponses = (responses: any): { docs: Array>; flattenSchema: string[] } => {\n const docs: any[] = [];\n // We keep a list of all schemas so that we can create all the fields in the dataFrame, this can lead\n // to wide sparse dataframes in case the scheme is different per document.\n let flattenSchema: string[] = [];\n\n for (const response of responses) {\n const doc = flatten(response);\n\n for (const schema of Object.keys(doc)) {\n if (flattenSchema.indexOf(schema) === -1) {\n flattenSchema.push(schema);\n }\n }\n docs.push(doc);\n }\n return { docs, flattenSchema };\n};\n\n/**\n * Returns the datapoints and target needed for parsing PPL time series response.\n * Also checks to ensure the query is a valid time series query\n * @param responses\n */\nconst getPPLDatapoints = (response: any): { datapoints: any; targetVal: any; invalidTS: boolean } => {\n let invalidTS = false;\n\n // We check if a valid date type is contained in the response\n const timeFieldIndex = _.findIndex(\n response.schema,\n (field: { type: string }) => field.type === 'timestamp' || field.type === 'datetime' || field.type === 'date'\n );\n\n const valueIndex = timeFieldIndex === 0 ? 1 : 0;\n\n //time series response should include a value field and timestamp\n if (\n timeFieldIndex === -1 ||\n response.datarows[0].length !== 2 ||\n typeof response.datarows[0][valueIndex] !== 'number'\n ) {\n invalidTS = true;\n }\n\n const datapoints = _.map(response.datarows, datarow => {\n const newDatarow = _.clone(datarow);\n const [timestamp] = newDatarow.splice(timeFieldIndex, 1);\n newDatarow.push(dateTime(timestamp).unix() * 1000);\n return newDatarow;\n });\n\n const targetVal = response.schema[valueIndex]?.name;\n\n return { datapoints, targetVal, invalidTS };\n};\n\n/**\n * Create empty dataframe but with created fields. Fields are based from propNames (should be from the response) and\n * also from configuration specified fields for message, time, and level.\n * @param propNames\n * @param timeField\n * @param logMessageField\n * @param logLevelField\n */\nconst createEmptyDataFrame = (\n propNames: string[],\n timeField: string,\n isLogsRequest: boolean,\n targetType: ElasticsearchQueryType,\n logMessageField?: string,\n logLevelField?: string\n): MutableDataFrame => {\n const series = new MutableDataFrame({ fields: [] });\n\n //PPL table response should add time field only when it is part of the query response\n if (targetType === ElasticsearchQueryType.Lucene || isLogsRequest) {\n series.addField({\n config: {\n filterable: true,\n },\n name: timeField,\n type: FieldType.time,\n });\n }\n\n if (logMessageField) {\n series.addField({\n name: logMessageField,\n type: FieldType.string,\n }).parse = (v: any) => {\n return v || '';\n };\n }\n\n if (logLevelField) {\n series.addField({\n name: 'level',\n type: FieldType.string,\n }).parse = (v: any) => {\n return v || '';\n };\n }\n\n const fieldNames = series.fields.map(field => field.name);\n\n for (const propName of propNames) {\n // Do not duplicate fields. This can mean that we will shadow some fields.\n if (fieldNames.includes(propName)) {\n continue;\n }\n // Do not add _source field (besides logs) as we are showing each _source field in table instead.\n if (!isLogsRequest && propName === '_source') {\n continue;\n }\n\n series.addField({\n config: {\n filterable: true,\n },\n name: propName,\n type: FieldType.string,\n }).parse = (v: any) => {\n return v || '';\n };\n }\n\n return series;\n};\n\nconst addPreferredVisualisationType = (series: any, type: PreferredVisualisationType) => {\n let s = series;\n s.meta\n ? (s.meta.preferredVisualisationType = type)\n : (s.meta = {\n preferredVisualisationType: type,\n });\n\n return s;\n};\n","import { toUtc, dateTime, DateTime, TimeRange } from '@grafana/data';\n\nconst intervalMap: any = {\n Hourly: { startOf: 'hour', amount: 'hours' },\n Daily: { startOf: 'day', amount: 'days' },\n Weekly: { startOf: 'isoWeek', amount: 'weeks' },\n Monthly: { startOf: 'month', amount: 'months' },\n Yearly: { startOf: 'year', amount: 'years' },\n};\n\nexport class IndexPattern {\n private dateLocale = 'en';\n\n constructor(private pattern: any, private interval?: string) {}\n\n getIndexForToday() {\n if (this.interval) {\n return toUtc()\n .locale(this.dateLocale)\n .format(this.pattern);\n } else {\n return this.pattern;\n }\n }\n\n getIndexList(from?: DateTime, to?: DateTime) {\n // When no `from` or `to` is provided, we request data from 7 subsequent/previous indices\n // for the provided index pattern.\n // This is useful when requesting log context where the only time data we have is the log\n // timestamp.\n const indexOffset = 7;\n if (!this.interval) {\n return this.pattern;\n }\n\n const intervalInfo = intervalMap[this.interval];\n const start = dateTime(from || dateTime(to).add(-indexOffset, intervalInfo.amount))\n .utc()\n .startOf(intervalInfo.startOf);\n const endEpoch = dateTime(to || dateTime(from).add(indexOffset, intervalInfo.amount))\n .utc()\n .startOf(intervalInfo.startOf)\n .valueOf();\n const indexList = [];\n\n while (start.valueOf() <= endEpoch) {\n indexList.push(start.locale(this.dateLocale).format(this.pattern));\n start.add(1, intervalInfo.amount);\n }\n\n return indexList;\n }\n\n getPPLIndexPattern() {\n // PPL currently does not support multi-indexing through lists, so a wildcard\n // pattern is used to match all patterns and relies on the time range filter\n // to filter out the incorrect indexes.\n if (!this.interval) {\n return this.pattern;\n }\n\n let indexPattern = this.pattern.match(/\\[(.*?)\\]/)[1];\n\n if (this.pattern.startsWith('[')) {\n indexPattern = indexPattern + '*';\n } else if (this.pattern.endsWith(']')) {\n indexPattern = '*' + indexPattern;\n }\n return indexPattern;\n }\n}\n\nexport function getDefaultTimeRange(): TimeRange {\n const now = dateTime();\n\n return {\n from: dateTime(now).subtract(6, 'hour'),\n to: now,\n raw: { from: 'now-6h', to: 'now' },\n };\n}\n","import { dateTime, dateMath } from '@grafana/data';\nimport {\n Filters,\n Histogram,\n DateHistogram,\n Terms,\n} from './components/QueryEditor/BucketAggregationsEditor/aggregations';\nimport {\n isMetricAggregationWithField,\n isMetricAggregationWithSettings,\n isPipelineAggregation,\n isPipelineAggregationWithMultipleBucketPaths,\n} from './components/QueryEditor/MetricAggregationsEditor/aggregations';\nimport { defaultBucketAgg, defaultMetricAgg, defaultPPLFormat, findMetricById } from './query_def';\nimport { ElasticsearchQuery, ElasticsearchQueryType } from './types';\n\nexport class ElasticQueryBuilder {\n timeField: string;\n esVersion: number;\n\n constructor(options: { timeField: string; esVersion: number }) {\n this.timeField = options.timeField;\n this.esVersion = options.esVersion;\n }\n\n getRangeFilter() {\n const filter: any = {};\n filter[this.timeField] = {\n gte: '$timeFrom',\n lte: '$timeTo',\n format: 'epoch_millis',\n };\n\n return filter;\n }\n\n buildTermsAgg(aggDef: Terms, queryNode: { terms?: any; aggs?: any }, target: ElasticsearchQuery) {\n let metricRef;\n queryNode.terms = { field: aggDef.field };\n\n if (!aggDef.settings) {\n return queryNode;\n }\n\n // TODO: This default should be somewhere else together with the one used in the UI\n const size = aggDef.settings?.size ? parseInt(aggDef.settings.size, 10) : 500;\n queryNode.terms.size = size === 0 ? 500 : size;\n\n if (aggDef.settings.orderBy !== void 0) {\n queryNode.terms.order = {};\n if (aggDef.settings.orderBy === '_term' && this.esVersion >= 60) {\n queryNode.terms.order['_key'] = aggDef.settings.order;\n } else {\n queryNode.terms.order[aggDef.settings.orderBy] = aggDef.settings.order;\n }\n\n // if metric ref, look it up and add it to this agg level\n metricRef = parseInt(aggDef.settings.orderBy, 10);\n if (!isNaN(metricRef)) {\n for (let metric of target.metrics || []) {\n if (metric.id === aggDef.settings.orderBy) {\n queryNode.aggs = {};\n queryNode.aggs[metric.id] = {};\n if (isMetricAggregationWithField(metric)) {\n queryNode.aggs[metric.id][metric.type] = { field: metric.field };\n }\n break;\n }\n }\n }\n }\n\n if (aggDef.settings.min_doc_count !== void 0) {\n queryNode.terms.min_doc_count = parseInt(aggDef.settings.min_doc_count, 10);\n\n if (isNaN(queryNode.terms.min_doc_count)) {\n queryNode.terms.min_doc_count = aggDef.settings.min_doc_count;\n }\n }\n\n if (aggDef.settings.missing) {\n queryNode.terms.missing = aggDef.settings.missing;\n }\n\n return queryNode;\n }\n\n getDateHistogramAgg(aggDef: DateHistogram) {\n const esAgg: any = {};\n const settings = aggDef.settings || {};\n esAgg.interval = settings.interval;\n esAgg.field = this.timeField;\n esAgg.min_doc_count = settings.min_doc_count || 0;\n esAgg.extended_bounds = { min: '$timeFrom', max: '$timeTo' };\n esAgg.format = 'epoch_millis';\n\n if (settings.offset !== '') {\n esAgg.offset = settings.offset;\n }\n\n if (esAgg.interval === 'auto') {\n esAgg.interval = '$__interval';\n }\n\n return esAgg;\n }\n\n getHistogramAgg(aggDef: Histogram) {\n const esAgg: any = {};\n const settings = aggDef.settings || {};\n esAgg.interval = settings.interval;\n esAgg.field = aggDef.field;\n esAgg.min_doc_count = settings.min_doc_count || 0;\n\n return esAgg;\n }\n\n getFiltersAgg(aggDef: Filters) {\n const filterObj: Record = {};\n\n for (let { query, label } of aggDef.settings?.filters || []) {\n filterObj[label || query] = {\n query_string: {\n query: query,\n analyze_wildcard: true,\n },\n };\n }\n\n return filterObj;\n }\n\n documentQuery(query: any, size: number) {\n query.size = size;\n query.sort = {};\n query.sort[this.timeField] = { order: 'desc', unmapped_type: 'boolean' };\n\n // fields field not supported on ES 5.x\n if (this.esVersion < 5) {\n query.fields = ['*', '_source'];\n }\n\n query.script_fields = {};\n return query;\n }\n\n addAdhocFilters(query: any, adhocFilters: any) {\n if (!adhocFilters) {\n return;\n }\n\n let i, filter, condition: any, queryCondition: any;\n\n for (i = 0; i < adhocFilters.length; i++) {\n filter = adhocFilters[i];\n condition = {};\n condition[filter.key] = filter.value;\n queryCondition = {};\n queryCondition[filter.key] = { query: filter.value };\n\n switch (filter.operator) {\n case '=':\n if (!query.query.bool.must) {\n query.query.bool.must = [];\n }\n query.query.bool.must.push({ match_phrase: queryCondition });\n break;\n case '!=':\n if (!query.query.bool.must_not) {\n query.query.bool.must_not = [];\n }\n query.query.bool.must_not.push({ match_phrase: queryCondition });\n break;\n case '<':\n condition[filter.key] = { lt: filter.value };\n query.query.bool.filter.push({ range: condition });\n break;\n case '>':\n condition[filter.key] = { gt: filter.value };\n query.query.bool.filter.push({ range: condition });\n break;\n case '=~':\n query.query.bool.filter.push({ regexp: condition });\n break;\n case '!~':\n query.query.bool.filter.push({\n bool: { must_not: { regexp: condition } },\n });\n break;\n }\n }\n }\n\n build(target: ElasticsearchQuery, adhocFilters?: any, queryString?: string) {\n // make sure query has defaults;\n target.metrics = target.metrics || [defaultMetricAgg()];\n target.bucketAggs = target.bucketAggs || [defaultBucketAgg()];\n target.timeField = this.timeField;\n target.queryType = ElasticsearchQueryType.Lucene;\n\n let i, j, pv, nestedAggs, metric;\n const query = {\n size: 0,\n query: {\n bool: {\n filter: [\n { range: this.getRangeFilter() },\n {\n query_string: {\n analyze_wildcard: true,\n query: queryString,\n },\n },\n ],\n },\n },\n };\n\n this.addAdhocFilters(query, adhocFilters);\n\n // If target doesn't have bucketAggs and type is not raw_document, it is invalid query.\n if (target.bucketAggs.length === 0) {\n metric = target.metrics[0];\n\n if (!metric || !(metric.type === 'raw_document' || metric.type === 'raw_data')) {\n throw { message: 'Invalid query' };\n }\n }\n\n /* Handle document query:\n * Check if metric type is raw_document. If metric doesn't have size (or size is 0), update size to 500.\n * Otherwise it will not be a valid query and error will be thrown.\n */\n if (target.metrics?.[0]?.type === 'raw_document' || target.metrics?.[0]?.type === 'raw_data') {\n metric = target.metrics[0];\n\n // TODO: This default should be somewhere else together with the one used in the UI\n const size = metric.settings?.size ? parseInt(metric.settings.size, 10) : 500;\n\n return this.documentQuery(query, size || 500);\n }\n\n nestedAggs = query;\n\n for (i = 0; i < target.bucketAggs.length; i++) {\n const aggDef = target.bucketAggs[i];\n const esAgg: any = {};\n\n switch (aggDef.type) {\n case 'date_histogram': {\n esAgg['date_histogram'] = this.getDateHistogramAgg(aggDef);\n break;\n }\n case 'histogram': {\n esAgg['histogram'] = this.getHistogramAgg(aggDef);\n break;\n }\n case 'filters': {\n esAgg['filters'] = { filters: this.getFiltersAgg(aggDef) };\n break;\n }\n case 'terms': {\n this.buildTermsAgg(aggDef, esAgg, target);\n break;\n }\n case 'geohash_grid': {\n esAgg['geohash_grid'] = {\n field: aggDef.field,\n precision: aggDef.settings?.precision,\n };\n break;\n }\n }\n\n nestedAggs.aggs = nestedAggs.aggs || {};\n nestedAggs.aggs[aggDef.id] = esAgg;\n nestedAggs = esAgg;\n }\n\n nestedAggs.aggs = {};\n\n for (i = 0; i < target.metrics.length; i++) {\n metric = target.metrics[i];\n if (metric.type === 'count') {\n continue;\n }\n\n const aggField: any = {};\n let metricAgg: any = null;\n\n if (isPipelineAggregation(metric)) {\n if (isPipelineAggregationWithMultipleBucketPaths(metric)) {\n if (metric.pipelineVariables) {\n metricAgg = {\n buckets_path: {},\n };\n\n for (j = 0; j < metric.pipelineVariables.length; j++) {\n pv = metric.pipelineVariables[j];\n\n if (pv.name && pv.pipelineAgg && /^\\d*$/.test(pv.pipelineAgg)) {\n const appliedAgg = findMetricById(target.metrics, pv.pipelineAgg);\n if (appliedAgg) {\n if (appliedAgg.type === 'count') {\n metricAgg.buckets_path[pv.name] = '_count';\n } else {\n metricAgg.buckets_path[pv.name] = pv.pipelineAgg;\n }\n }\n }\n }\n } else {\n continue;\n }\n } else {\n if (metric.field && /^\\d*$/.test(metric.field)) {\n const appliedAgg = findMetricById(target.metrics, metric.field);\n if (appliedAgg) {\n if (appliedAgg.type === 'count') {\n metricAgg = { buckets_path: '_count' };\n } else {\n metricAgg = { buckets_path: metric.field };\n }\n }\n } else {\n continue;\n }\n }\n } else if (isMetricAggregationWithField(metric)) {\n metricAgg = { field: metric.field };\n }\n\n metricAgg = {\n ...metricAgg,\n ...(isMetricAggregationWithSettings(metric) && metric.settings),\n };\n\n aggField[metric.type] = metricAgg;\n nestedAggs.aggs[metric.id] = aggField;\n }\n\n return query;\n }\n\n getTermsQuery(queryDef: any) {\n const query: any = {\n size: 0,\n query: {\n bool: {\n filter: [{ range: this.getRangeFilter() }],\n },\n },\n };\n\n if (queryDef.query) {\n query.query.bool.filter.push({\n query_string: {\n analyze_wildcard: true,\n query: queryDef.query,\n },\n });\n }\n\n let size = 500;\n if (queryDef.size) {\n size = queryDef.size;\n }\n\n query.aggs = {\n '1': {\n terms: {\n field: queryDef.field,\n size: size,\n order: {},\n },\n },\n };\n\n // Default behaviour is to order results by { _key: asc }\n // queryDef.order allows selection of asc/desc\n // queryDef.orderBy allows selection of doc_count ordering (defaults desc)\n\n const { orderBy = 'key', order = orderBy === 'doc_count' ? 'desc' : 'asc' } = queryDef;\n\n if (['asc', 'desc'].indexOf(order) < 0) {\n throw { message: `Invalid query sort order ${order}` };\n }\n\n switch (orderBy) {\n case 'key':\n case 'term':\n const keyname = this.esVersion >= 60 ? '_key' : '_term';\n query.aggs['1'].terms.order[keyname] = order;\n break;\n case 'doc_count':\n query.aggs['1'].terms.order['_count'] = order;\n break;\n default:\n throw { message: `Invalid query sort type ${orderBy}` };\n }\n\n return query;\n }\n\n getLogsQuery(target: ElasticsearchQuery, adhocFilters?: any, querystring?: string) {\n let query: any = {\n size: 0,\n query: {\n bool: {\n filter: [{ range: this.getRangeFilter() }],\n },\n },\n };\n\n this.addAdhocFilters(query, adhocFilters);\n\n if (target.query) {\n query.query.bool.filter.push({\n query_string: {\n analyze_wildcard: true,\n query: querystring,\n },\n });\n }\n\n query = this.documentQuery(query, 500);\n\n return {\n ...query,\n aggs: this.build(target, null, querystring).aggs,\n };\n }\n\n /* Adds Ad hoc filters for PPL:\n * Check for the value type and parse it accordingly so it can be added onto the query string through 'where' command\n */\n addPPLAdhocFilters(queryString: any, adhocFilters: any) {\n let i, value, adhocquery;\n\n for (i = 0; i < adhocFilters.length; i++) {\n if (dateMath.isValid(adhocFilters[i].value)) {\n const validTime = dateTime(adhocFilters[i].value).format('YYYY-MM-DD HH:mm:ss.SSSSSS');\n value = `timestamp('${validTime}')`;\n } else if (typeof adhocFilters[i].value === 'string') {\n value = `'${adhocFilters[i].value}'`;\n } else {\n value = adhocFilters[i].value;\n }\n adhocquery = `\\`${adhocFilters[i].key}\\` ${adhocFilters[i].operator} ${value}`;\n\n if (i > 0) {\n queryString += ' and ' + adhocquery;\n } else {\n queryString += ' | where ' + adhocquery;\n }\n }\n return queryString;\n }\n\n buildPPLQuery(target: any, adhocFilters?: any, queryString?: string) {\n // make sure query has defaults\n target.format = target.format || defaultPPLFormat();\n target.queryType = ElasticsearchQueryType.PPL;\n\n // set isLogsQuery depending on the format\n target.isLogsQuery = target.format === 'logs';\n\n if (adhocFilters) {\n queryString = this.addPPLAdhocFilters(queryString, adhocFilters);\n }\n\n const timeRangeFilter = \" where $timestamp >= timestamp('$timeFrom') and $timestamp <= timestamp('$timeTo')\";\n //time range filter must be placed before other query filters\n if (queryString) {\n const separatorIndex = queryString.indexOf('|');\n if (separatorIndex === -1) {\n queryString = [queryString.trimEnd(), timeRangeFilter].join(' |');\n } else {\n queryString = [\n queryString.slice(0, separatorIndex).trimEnd(),\n timeRangeFilter,\n queryString.slice(separatorIndex + 1),\n ].join(' |');\n }\n }\n\n return { query: queryString };\n }\n}\n","import { BucketsConfiguration } from '../../../types';\nimport { defaultFilter } from './SettingsEditor/FiltersSettingsEditor/utils';\n\nexport const bucketAggregationConfig: BucketsConfiguration = {\n terms: {\n label: 'Terms',\n requiresField: true,\n defaultSettings: {\n min_doc_count: '0',\n size: '10',\n order: 'desc',\n orderBy: '_term',\n },\n },\n filters: {\n label: 'Filters',\n requiresField: false,\n defaultSettings: {\n filters: [defaultFilter()],\n },\n },\n geohash_grid: {\n label: 'Geo Hash Grid',\n requiresField: true,\n defaultSettings: {\n precision: '3',\n },\n },\n date_histogram: {\n label: 'Date Histogram',\n requiresField: true,\n defaultSettings: {\n interval: 'auto',\n min_doc_count: '0',\n trimEdges: '0',\n },\n },\n histogram: {\n label: 'Histogram',\n requiresField: true,\n defaultSettings: {\n interval: '1000',\n min_doc_count: '0',\n },\n },\n};\n\n// TODO: Define better types for the following\nexport const orderOptions = [\n { label: 'Top', value: 'desc' },\n { label: 'Bottom', value: 'asc' },\n];\n\nexport const sizeOptions = [\n { label: 'No limit', value: '0' },\n { label: '1', value: '1' },\n { label: '2', value: '2' },\n { label: '3', value: '3' },\n { label: '5', value: '5' },\n { label: '10', value: '10' },\n { label: '15', value: '15' },\n { label: '20', value: '20' },\n];\n\nexport const orderByOptions = [\n { label: 'Term value', value: '_term' },\n { label: 'Doc Count', value: '_count' },\n];\n\nexport const intervalOptions = [\n { label: 'auto', value: 'auto' },\n { label: '10s', value: '10s' },\n { label: '1m', value: '1m' },\n { label: '5m', value: '5m' },\n { label: '10m', value: '10m' },\n { label: '20m', value: '20m' },\n { label: '1h', value: '1h' },\n { label: '1d', value: '1d' },\n];\n","import { Filter } from '../../aggregations';\n\nexport const defaultFilter = (): Filter => ({ label: '', query: '*' });\n","import { bucketAggregationConfig } from './utils';\n\nexport type BucketAggregationType = 'terms' | 'filters' | 'geohash_grid' | 'date_histogram' | 'histogram';\n\ninterface BaseBucketAggregation {\n id: string;\n type: BucketAggregationType;\n settings?: Record;\n}\n\nexport interface BucketAggregationWithField extends BaseBucketAggregation {\n field?: string;\n}\n\nexport interface DateHistogram extends BucketAggregationWithField {\n type: 'date_histogram';\n settings?: {\n interval?: string;\n min_doc_count?: string;\n trimEdges?: string;\n offset?: string;\n };\n}\n\nexport interface Histogram extends BucketAggregationWithField {\n type: 'histogram';\n settings?: {\n interval?: string;\n min_doc_count?: string;\n };\n}\n\ntype TermsOrder = 'desc' | 'asc';\n\nexport interface Terms extends BucketAggregationWithField {\n type: 'terms';\n settings?: {\n order?: TermsOrder;\n size?: string;\n min_doc_count?: string;\n orderBy?: string;\n missing?: string;\n };\n}\n\nexport type Filter = {\n query: string;\n label: string;\n};\nexport interface Filters extends BaseBucketAggregation {\n type: 'filters';\n settings?: {\n filters?: Filter[];\n };\n}\n\ninterface GeoHashGrid extends BucketAggregationWithField {\n type: 'geohash_grid';\n settings?: {\n precision?: string;\n };\n}\n\nexport type BucketAggregation = DateHistogram | Histogram | Terms | Filters | GeoHashGrid;\n\nexport const isBucketAggregationWithField = (\n bucketAgg: BucketAggregation | BucketAggregationWithField\n): bucketAgg is BucketAggregationWithField => bucketAggregationConfig[bucketAgg.type].requiresField;\n","import _ from 'lodash';\nimport { from, merge, of, Observable } from 'rxjs';\nimport { map } from 'rxjs/operators';\nimport {\n DataSourceApi,\n DataSourceInstanceSettings,\n DataQueryRequest,\n DataQueryResponse,\n DataFrame,\n ScopedVars,\n DataLink,\n PluginMeta,\n DataQuery,\n MetricFindValue,\n dateTime,\n TimeRange,\n LoadingState,\n toUtc,\n} from '@grafana/data';\nimport LanguageProvider from './language_provider';\nimport { ElasticResponse } from './elastic_response';\nimport { IndexPattern, getDefaultTimeRange } from './index_pattern';\nimport { ElasticQueryBuilder } from './query_builder';\nimport { defaultBucketAgg, hasMetricOfType } from './query_def';\nimport { getBackendSrv, getDataSourceSrv, getTemplateSrv } from '@grafana/runtime';\nimport { DataLinkConfig, ElasticsearchOptions, ElasticsearchQuery, ElasticsearchQueryType } from './types';\nimport { metricAggregationConfig } from './components/QueryEditor/MetricAggregationsEditor/utils';\nimport {\n isMetricAggregationWithField,\n isPipelineAggregationWithMultipleBucketPaths,\n} from './components/QueryEditor/MetricAggregationsEditor/aggregations';\nimport { bucketAggregationConfig } from './components/QueryEditor/BucketAggregationsEditor/utils';\nimport { isBucketAggregationWithField } from './components/QueryEditor/BucketAggregationsEditor/aggregations';\n\n// Those are metadata fields as defined in https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-fields.html#_identity_metadata_fields.\n// custom fields can start with underscores, therefore is not safe to exclude anything that starts with one.\nconst ELASTIC_META_FIELDS = [\n '_index',\n '_type',\n '_id',\n '_source',\n '_size',\n '_field_names',\n '_ignored',\n '_routing',\n '_meta',\n];\n\nexport class ElasticDatasource extends DataSourceApi {\n basicAuth?: string;\n withCredentials?: boolean;\n url: string;\n name: string;\n index: string;\n timeField: string;\n esVersion: number;\n interval: string;\n maxConcurrentShardRequests?: number;\n queryBuilder: ElasticQueryBuilder;\n indexPattern: IndexPattern;\n logMessageField?: string;\n logLevelField?: string;\n dataLinks: DataLinkConfig[];\n languageProvider: LanguageProvider;\n pplEnabled?: boolean;\n\n constructor(instanceSettings: DataSourceInstanceSettings) {\n super(instanceSettings);\n this.basicAuth = instanceSettings.basicAuth;\n this.withCredentials = instanceSettings.withCredentials;\n this.url = instanceSettings.url!;\n this.name = instanceSettings.name;\n const settingsData = instanceSettings.jsonData || ({} as ElasticsearchOptions);\n this.index = settingsData.database ?? '';\n\n this.timeField = settingsData.timeField;\n this.esVersion = settingsData.esVersion;\n this.indexPattern = new IndexPattern(this.index, settingsData.interval);\n this.interval = settingsData.timeInterval;\n this.maxConcurrentShardRequests = settingsData.maxConcurrentShardRequests;\n this.queryBuilder = new ElasticQueryBuilder({\n timeField: this.timeField,\n esVersion: this.esVersion,\n });\n this.logMessageField = settingsData.logMessageField || '';\n this.logLevelField = settingsData.logLevelField || '';\n this.dataLinks = settingsData.dataLinks || [];\n\n if (this.logMessageField === '') {\n this.logMessageField = undefined;\n }\n\n if (this.logLevelField === '') {\n this.logLevelField = undefined;\n }\n this.languageProvider = new LanguageProvider(this);\n this.pplEnabled = settingsData.pplEnabled ?? true;\n }\n\n private request(method: string, url: string, data?: undefined) {\n const options: any = {\n url: this.url + '/' + url,\n method: method,\n data: data,\n };\n\n if (this.basicAuth || this.withCredentials) {\n options.withCredentials = true;\n }\n if (this.basicAuth) {\n options.headers = {\n Authorization: this.basicAuth,\n };\n }\n\n return getBackendSrv()\n .datasourceRequest(options)\n .catch((err: any) => {\n if (err.data && err.data.error) {\n throw {\n message: `Elasticsearch error: ${err.data.error.reason}. ${err.data.error.details}`,\n error: err.data.error,\n };\n }\n throw err;\n });\n }\n\n async importQueries(queries: DataQuery[], originMeta: PluginMeta): Promise {\n return this.languageProvider.importQueries(queries, originMeta.id);\n }\n\n /**\n * Sends a GET request to the specified url on the newest matching and available index.\n *\n * When multiple indices span the provided time range, the request is sent starting from the newest index,\n * and then going backwards until an index is found.\n *\n * @param url the url to query the index on, for example `/_mapping`.\n */\n private get(url: string, range = getDefaultTimeRange()) {\n const indexList = this.indexPattern.getIndexList(range.from, range.to);\n if (_.isArray(indexList) && indexList.length) {\n return this.requestAllIndices(indexList, url).then((results: any) => {\n results.data.$$config = results.config;\n return results.data;\n });\n } else {\n return this.request('GET', this.indexPattern.getIndexForToday() + url).then((results: any) => {\n results.data.$$config = results.config;\n return results.data;\n });\n }\n }\n\n private async requestAllIndices(indexList: string[], url: string): Promise {\n const maxTraversals = 7; // do not go beyond one week (for a daily pattern)\n const listLen = indexList.length;\n for (let i = 0; i < Math.min(listLen, maxTraversals); i++) {\n try {\n return await this.request('GET', indexList[listLen - i - 1] + url);\n } catch (err) {\n if (err.status !== 404 || i === maxTraversals - 1) {\n throw err;\n }\n }\n }\n }\n\n private post(url: string, data: any) {\n return this.request('POST', url, data).then((results: any) => {\n results.data.$$config = results.config;\n return results.data;\n });\n }\n\n annotationQuery(options: any): Promise {\n const annotation = options.annotation;\n const timeField = annotation.timeField || '@timestamp';\n const timeEndField = annotation.timeEndField || null;\n const queryString = annotation.query || '*';\n const tagsField = annotation.tagsField || 'tags';\n const textField = annotation.textField || null;\n\n const dateRanges = [];\n const rangeStart: any = {};\n rangeStart[timeField] = {\n from: options.range.from.valueOf(),\n to: options.range.to.valueOf(),\n format: 'epoch_millis',\n };\n dateRanges.push({ range: rangeStart });\n\n if (timeEndField) {\n const rangeEnd: any = {};\n rangeEnd[timeEndField] = {\n from: options.range.from.valueOf(),\n to: options.range.to.valueOf(),\n format: 'epoch_millis',\n };\n dateRanges.push({ range: rangeEnd });\n }\n\n const queryInterpolated = getTemplateSrv().replace(queryString, {}, 'lucene');\n const query = {\n bool: {\n filter: [\n {\n bool: {\n should: dateRanges,\n minimum_should_match: 1,\n },\n },\n {\n query_string: {\n query: queryInterpolated,\n },\n },\n ],\n },\n };\n\n const data: any = {\n query,\n size: 10000,\n };\n\n // fields field not supported on ES 5.x\n if (this.esVersion < 5) {\n data['fields'] = [timeField, '_source'];\n }\n\n const header: any = {\n search_type: 'query_then_fetch',\n ignore_unavailable: true,\n };\n\n // old elastic annotations had index specified on them\n if (annotation.index) {\n header.index = annotation.index;\n } else {\n header.index = this.indexPattern.getIndexList(options.range.from, options.range.to);\n }\n\n const payload = JSON.stringify(header) + '\\n' + JSON.stringify(data) + '\\n';\n\n return this.post('_msearch', payload).then((res: any) => {\n const list = [];\n const hits = res.responses[0].hits.hits;\n\n const getFieldFromSource = (source: any, fieldName: any) => {\n if (!fieldName) {\n return;\n }\n\n const fieldNames = fieldName.split('.');\n let fieldValue = source;\n\n for (let i = 0; i < fieldNames.length; i++) {\n fieldValue = fieldValue[fieldNames[i]];\n if (!fieldValue) {\n console.log('could not find field in annotation: ', fieldName);\n return '';\n }\n }\n\n return fieldValue;\n };\n\n for (let i = 0; i < hits.length; i++) {\n const source = hits[i]._source;\n let time = getFieldFromSource(source, timeField);\n if (typeof hits[i].fields !== 'undefined') {\n const fields = hits[i].fields;\n if (_.isString(fields[timeField]) || _.isNumber(fields[timeField])) {\n time = fields[timeField];\n }\n }\n\n const event: {\n annotation: any;\n time: number;\n timeEnd?: number;\n text: string;\n tags: string | string[];\n } = {\n annotation: annotation,\n time: toUtc(time).valueOf(),\n text: getFieldFromSource(source, textField),\n tags: getFieldFromSource(source, tagsField),\n };\n\n if (timeEndField) {\n const timeEnd = getFieldFromSource(source, timeEndField);\n if (timeEnd) {\n event.timeEnd = toUtc(timeEnd).valueOf();\n }\n }\n\n // legacy support for title tield\n if (annotation.titleField) {\n const title = getFieldFromSource(source, annotation.titleField);\n if (title) {\n event.text = title + '\\n' + event.text;\n }\n }\n\n if (typeof event.tags === 'string') {\n event.tags = event.tags.split(',');\n }\n\n list.push(event);\n }\n return list;\n });\n }\n\n private interpolateLuceneQuery(queryString: string, scopedVars: ScopedVars) {\n // Elasticsearch Lucene queryString should always be '*' if empty string\n return getTemplateSrv().replace(queryString, scopedVars, 'lucene') || '*';\n }\n\n private interpolatePPLQuery(queryString: string, scopedVars: ScopedVars) {\n return getTemplateSrv().replace(queryString, scopedVars, 'pipe');\n }\n\n interpolateVariablesInQueries(queries: ElasticsearchQuery[], scopedVars: ScopedVars): ElasticsearchQuery[] {\n let expandedQueries = queries;\n if (queries && queries.length > 0) {\n expandedQueries = queries.map(query => {\n let interpolatedQuery;\n if (query.queryType === ElasticsearchQueryType.PPL) {\n interpolatedQuery = this.interpolatePPLQuery(query.query || '', scopedVars);\n } else {\n interpolatedQuery = this.interpolateLuceneQuery(query.query || '', scopedVars);\n }\n const expandedQuery = {\n ...query,\n datasource: this.name,\n query: interpolatedQuery,\n };\n\n for (let bucketAgg of query.bucketAggs || []) {\n if (bucketAgg.type === 'filters') {\n for (let filter of bucketAgg.settings?.filters || []) {\n filter.query = this.interpolateLuceneQuery(filter.query, scopedVars);\n }\n }\n }\n return expandedQuery;\n });\n }\n return expandedQueries;\n }\n\n testDatasource() {\n // validate that the index exist and has date field\n return this.getFields('date').then(\n (dateFields: any) => {\n const timeField: any = _.find(dateFields, { text: this.timeField });\n if (!timeField) {\n return {\n status: 'error',\n message: 'No date field named ' + this.timeField + ' found',\n };\n }\n return { status: 'success', message: 'Index OK. Time field name OK.' };\n },\n (err: any) => {\n console.error(err);\n if (err.message) {\n return { status: 'error', message: err.message };\n } else {\n return { status: 'error', message: err.status };\n }\n }\n );\n }\n\n getQueryHeader(searchType: any, timeFrom: any, timeTo: any) {\n const queryHeader: any = {\n search_type: searchType,\n ignore_unavailable: true,\n index: this.indexPattern.getIndexList(timeFrom, timeTo),\n };\n\n if (this.esVersion >= 56 && this.esVersion < 70) {\n queryHeader['max_concurrent_shard_requests'] = this.maxConcurrentShardRequests;\n }\n\n return JSON.stringify(queryHeader);\n }\n\n getQueryDisplayText(query: ElasticsearchQuery) {\n // TODO: This might be refactored a bit.\n const metricAggs = query.metrics;\n const bucketAggs = query.bucketAggs;\n let text = '';\n\n if (query.query) {\n text += 'Query: ' + query.query + ', ';\n }\n\n text += 'Metrics: ';\n\n text += metricAggs?.reduce((acc, metric) => {\n const metricConfig = metricAggregationConfig[metric.type];\n\n let text = metricConfig.label + '(';\n\n if (isMetricAggregationWithField(metric)) {\n text += metric.field;\n }\n if (isPipelineAggregationWithMultipleBucketPaths(metric)) {\n text += metric.settings?.script?.replace(new RegExp('params.', 'g'), '');\n }\n text += '), ';\n\n return `${acc} ${text}`;\n }, '');\n\n text += bucketAggs?.reduce((acc, bucketAgg, index) => {\n const bucketConfig = bucketAggregationConfig[bucketAgg.type];\n\n let text = '';\n if (index === 0) {\n text += ' Group by: ';\n }\n\n text += bucketConfig.label + '(';\n if (isBucketAggregationWithField(bucketAgg)) {\n text += bucketAgg.field;\n }\n\n return `${acc} ${text}), `;\n }, '');\n\n if (query.alias) {\n text += 'Alias: ' + query.alias;\n }\n\n return text;\n }\n\n query(options: DataQueryRequest): Observable {\n const targets = this.interpolateVariablesInQueries(_.cloneDeep(options.targets), options.scopedVars);\n\n const luceneTargets: ElasticsearchQuery[] = [];\n const pplTargets: ElasticsearchQuery[] = [];\n\n for (const target of targets) {\n if (target.hide) {\n continue;\n }\n\n switch (target.queryType) {\n case ElasticsearchQueryType.PPL:\n pplTargets.push(target);\n break;\n case ElasticsearchQueryType.Lucene:\n default:\n luceneTargets.push(target);\n }\n }\n\n const subQueries: Array> = [];\n\n if (luceneTargets.length) {\n const luceneResponses = this.executeLuceneQueries(luceneTargets, options);\n subQueries.push(luceneResponses);\n }\n if (pplTargets.length) {\n const pplResponses = this.executePPLQueries(pplTargets, options);\n subQueries.push(pplResponses);\n }\n if (subQueries.length === 0) {\n return of({\n data: [],\n state: LoadingState.Done,\n });\n }\n return merge(...subQueries);\n }\n\n /**\n * Execute all Lucene queries. Returns an Observable to be merged.\n */\n private executeLuceneQueries(\n targets: ElasticsearchQuery[],\n options: DataQueryRequest\n ): Observable {\n let payload = '';\n\n for (const target of targets) {\n payload += this.createLuceneQuery(target, options);\n }\n\n // We replace the range here for actual values. We need to replace it together with enclosing \"\" so that we replace\n // it as an integer not as string with digits. This is because elastic will convert the string only if the time\n // field is specified as type date (which probably should) but can also be specified as integer (millisecond epoch)\n // and then sending string will error out.\n payload = payload.replace(/\"\\$timeFrom\"/g, options.range.from.valueOf().toString());\n payload = payload.replace(/\"\\$timeTo\"/g, options.range.to.valueOf().toString());\n payload = getTemplateSrv().replace(payload, options.scopedVars);\n\n return from(this.post(this.getMultiSearchUrl(), payload)).pipe(\n map((res: any) => {\n const er = new ElasticResponse(targets, res);\n\n if (targets.some(target => target.isLogsQuery)) {\n const response = er.getLogs(this.logMessageField, this.logLevelField);\n for (const dataFrame of response.data) {\n enhanceDataFrame(dataFrame, this.dataLinks);\n }\n return response;\n }\n\n return er.getTimeSeries();\n })\n );\n }\n\n /**\n * Execute all PPL queries. Returns an Observable to be merged.\n */\n private executePPLQueries(\n targets: ElasticsearchQuery[],\n options: DataQueryRequest\n ): Observable {\n const subQueries: Array> = [];\n\n for (const target of targets) {\n let payload = this.createPPLQuery(target, options);\n\n const rangeFrom = dateTime(options.range.from.valueOf()).format('YYYY-MM-DD HH:mm:ss');\n const rangeTo = dateTime(options.range.to.valueOf()).format('YYYY-MM-DD HH:mm:ss');\n // Replace the range here for actual values.\n payload = payload.replace(/\\$timeTo/g, rangeTo);\n payload = payload.replace(/\\$timeFrom/g, rangeFrom);\n payload = payload.replace(/\\$timestamp/g, `\\`${this.timeField}\\``);\n subQueries.push(\n from(this.post(this.getPPLUrl(), payload)).pipe(\n map((res: any) => {\n const er = new ElasticResponse([target], res, ElasticsearchQueryType.PPL);\n\n if (targets.some(target => target.isLogsQuery)) {\n const response = er.getLogs(this.logMessageField, this.logLevelField);\n for (const dataFrame of response.data) {\n enhanceDataFrame(dataFrame, this.dataLinks);\n }\n return response;\n } else if (targets.some(target => target.format === 'table')) {\n return er.getTable();\n }\n return er.getTimeSeries();\n })\n )\n );\n }\n return merge(...subQueries);\n }\n\n /**\n * Creates the payload string for a Lucene query\n */\n private createLuceneQuery(target: ElasticsearchQuery, options: DataQueryRequest): string {\n let queryString = getTemplateSrv().replace(target.query, options.scopedVars, 'lucene');\n // @ts-ignore\n // add global adhoc filters to timeFilter\n const adhocFilters = getTemplateSrv().getAdhocFilters(this.name);\n // Elasticsearch queryString should always be '*' if empty string\n if (!queryString || queryString === '') {\n queryString = '*';\n }\n\n let queryObj;\n if (target.isLogsQuery || hasMetricOfType(target, 'logs')) {\n target.bucketAggs = [defaultBucketAgg()];\n target.metrics = [];\n // Setting this for metrics queries that are typed as logs\n target.isLogsQuery = true;\n queryObj = this.queryBuilder.getLogsQuery(target, adhocFilters, queryString);\n } else {\n if (target.alias) {\n target.alias = getTemplateSrv().replace(target.alias, options.scopedVars, 'lucene');\n }\n queryObj = this.queryBuilder.build(target, adhocFilters, queryString);\n }\n\n const esQuery = JSON.stringify(queryObj);\n const searchType = queryObj.size === 0 && this.esVersion < 5 ? 'count' : 'query_then_fetch';\n const header = this.getQueryHeader(searchType, options.range.from, options.range.to);\n return header + '\\n' + esQuery + '\\n';\n }\n\n /**\n * Creates the payload string for a PPL query\n */\n private createPPLQuery(target: ElasticsearchQuery, options: DataQueryRequest): string {\n let queryString = getTemplateSrv().replace(target.query, options.scopedVars, 'pipe');\n let queryObj;\n\n // @ts-ignore\n // add global adhoc filters to timeFilter\n const adhocFilters = getTemplateSrv().getAdhocFilters(this.name);\n\n // Elasticsearch PPL queryString should always be 'source=indexName' if empty string\n if (!queryString) {\n queryString = `source=\\`${this.indexPattern.getPPLIndexPattern()}\\``;\n }\n\n queryObj = this.queryBuilder.buildPPLQuery(target, adhocFilters, queryString);\n return JSON.stringify(queryObj);\n }\n\n isMetadataField(fieldName: string) {\n return ELASTIC_META_FIELDS.includes(fieldName);\n }\n\n // TODO: instead of being a string, this could be a custom type representing all the elastic types\n async getFields(type?: string, range?: TimeRange): Promise {\n const configuredEsVersion = this.esVersion;\n return this.get('/_mapping', range).then((result: any) => {\n const typeMap: any = {\n float: 'number',\n double: 'number',\n integer: 'number',\n long: 'number',\n date: 'date',\n date_nanos: 'date',\n string: 'string',\n text: 'string',\n scaled_float: 'number',\n nested: 'nested',\n };\n\n const shouldAddField = (obj: any, key: string) => {\n if (this.isMetadataField(key)) {\n return false;\n }\n\n if (!type) {\n return true;\n }\n\n // equal query type filter, or via typemap translation\n return type === obj.type || type === typeMap[obj.type];\n };\n\n // Store subfield names: [system, process, cpu, total] -> system.process.cpu.total\n const fieldNameParts: any = [];\n const fields: any = {};\n\n function getFieldsRecursively(obj: any) {\n for (const key in obj) {\n const subObj = obj[key];\n\n // Check mapping field for nested fields\n if (_.isObject(subObj.properties)) {\n fieldNameParts.push(key);\n getFieldsRecursively(subObj.properties);\n }\n\n if (_.isObject(subObj.fields)) {\n fieldNameParts.push(key);\n getFieldsRecursively(subObj.fields);\n }\n\n if (_.isString(subObj.type)) {\n const fieldName = fieldNameParts.concat(key).join('.');\n\n // Hide meta-fields and check field type\n if (shouldAddField(subObj, key)) {\n fields[fieldName] = {\n text: fieldName,\n type: subObj.type,\n };\n }\n }\n }\n fieldNameParts.pop();\n }\n\n for (const indexName in result) {\n const index = result[indexName];\n if (index && index.mappings) {\n const mappings = index.mappings;\n\n if (configuredEsVersion < 70) {\n for (const typeName in mappings) {\n const properties = mappings[typeName].properties;\n getFieldsRecursively(properties);\n }\n } else {\n const properties = mappings.properties;\n getFieldsRecursively(properties);\n }\n }\n }\n\n // transform to array\n return _.map(fields, value => {\n return value;\n });\n });\n }\n\n getTerms(queryDef: any, range = getDefaultTimeRange()) {\n const searchType = this.esVersion >= 5 ? 'query_then_fetch' : 'count';\n const header = this.getQueryHeader(searchType, range.from, range.to);\n let esQuery = JSON.stringify(this.queryBuilder.getTermsQuery(queryDef));\n\n esQuery = esQuery.replace(/\\$timeFrom/g, range.from.valueOf().toString());\n esQuery = esQuery.replace(/\\$timeTo/g, range.to.valueOf().toString());\n esQuery = header + '\\n' + esQuery + '\\n';\n\n const url = this.getMultiSearchUrl();\n\n return this.post(url, esQuery).then((res: any) => {\n if (!res.responses[0].aggregations) {\n return [];\n }\n\n const buckets = res.responses[0].aggregations['1'].buckets;\n return _.map(buckets, bucket => {\n return {\n text: bucket.key_as_string || bucket.key,\n value: bucket.key,\n };\n });\n });\n }\n\n getMultiSearchUrl() {\n if (this.esVersion >= 70 && this.maxConcurrentShardRequests) {\n return `_msearch?max_concurrent_shard_requests=${this.maxConcurrentShardRequests}`;\n }\n\n return '_msearch';\n }\n\n getPPLUrl() {\n return '_opendistro/_ppl';\n }\n\n metricFindQuery(query: string, options?: any): Promise {\n const range = options?.range;\n const parsedQuery = JSON.parse(query);\n if (query) {\n if (parsedQuery.find === 'fields') {\n parsedQuery.field = getTemplateSrv().replace(parsedQuery.field, {}, 'lucene');\n return this.getFields(query, range);\n }\n\n if (parsedQuery.find === 'terms') {\n parsedQuery.field = getTemplateSrv().replace(parsedQuery.field, {}, 'lucene');\n parsedQuery.query = getTemplateSrv().replace(parsedQuery.query || '*', {}, 'lucene');\n return this.getTerms(query, range);\n }\n }\n\n return Promise.resolve([]);\n }\n\n getTagKeys() {\n return this.getFields();\n }\n\n getTagValues(options: any) {\n return this.getTerms({ field: options.key, query: '*' });\n }\n\n targetContainsTemplate(target: any) {\n // @ts-ignore\n if (getTemplateSrv().variableExists(target.query) || getTemplateSrv().variableExists(target.alias)) {\n return true;\n }\n\n for (const bucketAgg of target.bucketAggs) {\n // @ts-ignore\n if (getTemplateSrv().variableExists(bucketAgg.field) || this.objectContainsTemplate(bucketAgg.settings)) {\n return true;\n }\n }\n\n for (const metric of target.metrics) {\n if (\n // @ts-ignore\n getTemplateSrv().variableExists(metric.field) ||\n this.objectContainsTemplate(metric.settings) ||\n this.objectContainsTemplate(metric.meta)\n ) {\n return true;\n }\n }\n\n return false;\n }\n\n private isPrimitive(obj: any) {\n if (obj === null || obj === undefined) {\n return true;\n }\n if (['string', 'number', 'boolean'].some(type => type === typeof true)) {\n return true;\n }\n\n return false;\n }\n\n private objectContainsTemplate(obj: any) {\n if (!obj) {\n return false;\n }\n\n for (const key of Object.keys(obj)) {\n if (this.isPrimitive(obj[key])) {\n // @ts-ignore\n if (getTemplateSrv().variableExists(obj[key])) {\n return true;\n }\n } else if (Array.isArray(obj[key])) {\n for (const item of obj[key]) {\n if (this.objectContainsTemplate(item)) {\n return true;\n }\n }\n } else {\n if (this.objectContainsTemplate(obj[key])) {\n return true;\n }\n }\n }\n\n return false;\n }\n\n getSupportedQueryTypes(): ElasticsearchQueryType[] {\n return [ElasticsearchQueryType.Lucene, ...(this.pplEnabled ? [ElasticsearchQueryType.PPL] : [])];\n }\n}\n\n/**\n * Modifies dataframe and adds dataLinks from the config.\n * Exported for tests.\n */\nexport function enhanceDataFrame(dataFrame: DataFrame, dataLinks: DataLinkConfig[]) {\n const dataSourceSrv = getDataSourceSrv();\n\n if (!dataLinks.length) {\n return;\n }\n\n for (const field of dataFrame.fields) {\n const dataLinkConfig = dataLinks.find(dataLink => field.name && field.name.match(dataLink.field));\n\n if (!dataLinkConfig) {\n continue;\n }\n\n let link: DataLink;\n\n if (dataLinkConfig.datasourceUid) {\n // @ts-ignore\n const dsSettings = dataSourceSrv.getInstanceSettings(dataLinkConfig.datasourceUid);\n\n link = {\n title: '',\n url: '',\n internal: {\n query: { query: dataLinkConfig.url },\n datasourceUid: dataLinkConfig.datasourceUid,\n // @ts-ignore\n datasourceName: dsSettings?.name ?? 'Data source not found',\n },\n };\n } else {\n link = {\n title: '',\n url: dataLinkConfig.url,\n };\n }\n\n field.config = field.config || {};\n field.config.links = [...(field.config.links || []), link];\n }\n}\n","import React from 'react';\nimport { EventsWithValidation, regexValidation, LegacyForms } from '@grafana/ui';\nconst { Select, Input, FormField, Switch } = LegacyForms;\nimport { ElasticsearchOptions } from '../types';\nimport { DataSourceSettings, SelectableValue } from '@grafana/data';\n\nconst indexPatternTypes = [\n { label: 'No pattern', value: 'none' },\n { label: 'Hourly', value: 'Hourly', example: '[logstash-]YYYY.MM.DD.HH' },\n { label: 'Daily', value: 'Daily', example: '[logstash-]YYYY.MM.DD' },\n { label: 'Weekly', value: 'Weekly', example: '[logstash-]GGGG.WW' },\n { label: 'Monthly', value: 'Monthly', example: '[logstash-]YYYY.MM' },\n { label: 'Yearly', value: 'Yearly', example: '[logstash-]YYYY' },\n];\n\nconst esVersions = [\n { label: '2.x', value: 2 },\n { label: '5.x', value: 5 },\n { label: '5.6+', value: 56 },\n { label: '6.0+', value: 60 },\n { label: '7.0+', value: 70 },\n];\n\ntype Props = {\n value: DataSourceSettings;\n onChange: (value: DataSourceSettings) => void;\n};\nexport const ElasticDetails = (props: Props) => {\n const { value, onChange } = props;\n\n return (\n <>\n

Elasticsearch details

\n\n
\n
\n
\n \n
\n\n
\n \n pattern.value === (value.jsonData.interval === undefined ? 'none' : value.jsonData.interval)\n )}\n />\n }\n />\n
\n
\n\n
\n \n
\n\n
\n {\n const maxConcurrentShardRequests = getMaxConcurrenShardRequestOrDefault(\n value.jsonData.maxConcurrentShardRequests,\n option.value!\n );\n onChange({\n ...value,\n jsonData: {\n ...value.jsonData,\n esVersion: option.value!,\n maxConcurrentShardRequests,\n },\n });\n }}\n value={esVersions.find(version => version.value === value.jsonData.esVersion)}\n />\n }\n />\n
\n {value.jsonData.esVersion >= 56 && (\n
\n \n
\n )}\n
\n
\n \n }\n tooltip={\n <>\n A lower limit for the auto group by time interval. Recommended to be set to write frequency, for\n example 1m if your data is written every minute.\n \n }\n />\n
\n
\n
\n \n
\n
\n \n );\n};\n\nconst jsonDataChangeHandler = (key: keyof ElasticsearchOptions, value: Props['value'], onChange: Props['onChange']) => (\n event: React.SyntheticEvent\n) => {\n onChange({\n ...value,\n jsonData: {\n ...value.jsonData,\n [key]: event.currentTarget.value,\n },\n });\n};\n\nconst jsonDataSwitchChangeHandler = (\n key: keyof ElasticsearchOptions,\n value: Props['value'],\n onChange: Props['onChange']\n) => (event: React.SyntheticEvent) => {\n onChange({\n ...value,\n jsonData: {\n ...value.jsonData,\n [key]: event.currentTarget.checked,\n },\n });\n};\n\nconst intervalHandler = (value: Props['value'], onChange: Props['onChange']) => (option: SelectableValue) => {\n const { database } = value;\n // If option value is undefined it will send its label instead so we have to convert made up value to undefined here.\n const newInterval = option.value === 'none' ? undefined : option.value;\n\n if (!database || database.length === 0 || database.startsWith('[logstash-]')) {\n let newDatabase = '';\n\n if (newInterval !== undefined) {\n const pattern = indexPatternTypes.find(pattern => pattern.value === newInterval);\n\n if (pattern) {\n newDatabase = pattern.example ?? '';\n }\n }\n\n onChange({\n ...value,\n database: newDatabase,\n jsonData: {\n ...value.jsonData,\n interval: newInterval,\n },\n });\n } else {\n onChange({\n ...value,\n jsonData: {\n ...value.jsonData,\n interval: newInterval,\n },\n });\n }\n};\n\nfunction getMaxConcurrenShardRequestOrDefault(maxConcurrentShardRequests: number | undefined, version: number): number {\n if (maxConcurrentShardRequests === 5 && version < 70) {\n return 256;\n }\n\n if (maxConcurrentShardRequests === 256 && version >= 70) {\n return 5;\n }\n\n return maxConcurrentShardRequests || defaultMaxConcurrentShardRequests(version);\n}\n\nexport function defaultMaxConcurrentShardRequests(version: number) {\n return version >= 70 ? 5 : 256;\n}\n","import React from 'react';\nimport { LegacyForms } from '@grafana/ui';\nconst { FormField } = LegacyForms;\nimport { ElasticsearchOptions } from '../types';\n\ntype Props = {\n value: ElasticsearchOptions;\n onChange: (value: ElasticsearchOptions) => void;\n};\nexport const LogsConfig = (props: Props) => {\n const { value, onChange } = props;\n const changeHandler = (key: keyof ElasticsearchOptions) => (\n event: React.SyntheticEvent\n ) => {\n onChange({\n ...value,\n [key]: event.currentTarget.value,\n });\n };\n\n return (\n <>\n

Logs

\n\n
\n
\n \n
\n
\n \n
\n
\n \n );\n};\n","import { useEffect, useRef } from 'react';\nvar usePrevious = function (state) {\n var ref = useRef();\n useEffect(function () {\n ref.current = state;\n });\n return ref.current;\n};\nexport default usePrevious;\n","import React, { HTMLAttributes } from 'react';\nimport { Badge, BadgeProps } from '@grafana/ui';\nimport { PluginErrorCode, PluginSignatureStatus } from '@grafana/data';\n\ninterface Props extends HTMLAttributes {\n status?: PluginSignatureStatus;\n}\n\nexport const PluginSignatureBadge: React.FC = ({ status, ...otherProps }) => {\n const display = getSignatureDisplayModel(status);\n return (\n \n );\n};\n\nexport function isUnsignedPluginSignature(signature?: PluginSignatureStatus) {\n return signature && signature !== PluginSignatureStatus.valid && signature !== PluginSignatureStatus.internal;\n}\n\nexport function mapPluginErrorCodeToSignatureStatus(code: PluginErrorCode) {\n switch (code) {\n case PluginErrorCode.invalidSignature:\n return PluginSignatureStatus.invalid;\n case PluginErrorCode.missingSignature:\n return PluginSignatureStatus.missing;\n case PluginErrorCode.modifiedSignature:\n return PluginSignatureStatus.modified;\n default:\n return PluginSignatureStatus.missing;\n }\n}\n\nfunction getSignatureDisplayModel(signature?: PluginSignatureStatus): BadgeProps {\n if (!signature) {\n signature = PluginSignatureStatus.invalid;\n }\n\n switch (signature) {\n case PluginSignatureStatus.internal:\n return { text: 'Core', icon: 'cube', color: 'blue', tooltip: 'Core plugin that is bundled with Grafana' };\n case PluginSignatureStatus.valid:\n return { text: 'Signed', icon: 'lock', color: 'green', tooltip: 'Signed and verified plugin' };\n case PluginSignatureStatus.invalid:\n return {\n text: 'Invalid signature',\n icon: 'exclamation-triangle',\n color: 'red',\n tooltip: 'Invalid plugin signature',\n };\n case PluginSignatureStatus.modified:\n return {\n text: 'Modified signature',\n icon: 'exclamation-triangle',\n color: 'red',\n tooltip: 'Valid signature but content has been modified',\n };\n case PluginSignatureStatus.missing:\n return {\n text: 'Missing signature',\n icon: 'exclamation-triangle',\n color: 'red',\n tooltip: 'Missing plugin signature',\n };\n }\n\n return { text: 'Unsigned', icon: 'exclamation-triangle', color: 'red', tooltip: 'Unsigned external plugin' };\n}\n\nPluginSignatureBadge.displayName = 'PluginSignatureBadge';\n","// Libraries\nimport React, { PureComponent } from 'react';\n\n// Components\nimport { HorizontalGroup, Select } from '@grafana/ui';\nimport { SelectableValue, DataSourceInstanceSettings } from '@grafana/data';\nimport { selectors } from '@grafana/e2e-selectors';\nimport { isUnsignedPluginSignature, PluginSignatureBadge } from './PluginSignatureBadge';\nimport { getDataSourceSrv } from '@grafana/runtime';\n\nexport interface Props {\n onChange: (ds: DataSourceInstanceSettings) => void;\n current: string | null;\n hideTextValue?: boolean;\n onBlur?: () => void;\n autoFocus?: boolean;\n openMenuOnFocus?: boolean;\n placeholder?: string;\n tracing?: boolean;\n mixed?: boolean;\n dashboard?: boolean;\n metrics?: boolean;\n annotations?: boolean;\n variables?: boolean;\n pluginId?: string;\n noDefault?: boolean;\n}\n\nexport interface State {\n error?: string;\n}\n\nexport class DataSourcePicker extends PureComponent {\n dataSourceSrv = getDataSourceSrv();\n\n static defaultProps: Partial = {\n autoFocus: false,\n openMenuOnFocus: false,\n placeholder: 'Select datasource',\n };\n\n state: State = {};\n\n constructor(props: Props) {\n super(props);\n }\n\n componentDidMount() {\n const { current } = this.props;\n // @ts-ignore\n const dsSettings = this.dataSourceSrv.getInstanceSettings(current);\n if (!dsSettings) {\n this.setState({ error: 'Could not find data source ' + current });\n }\n }\n\n onChange = (item: SelectableValue) => {\n // @ts-ignore\n const dsSettings = this.dataSourceSrv.getInstanceSettings(item.value);\n\n if (dsSettings) {\n this.props.onChange(dsSettings);\n this.setState({ error: undefined });\n }\n };\n\n private getCurrentValue() {\n const { current, hideTextValue, noDefault } = this.props;\n\n if (!current && noDefault) {\n return null;\n }\n\n // @ts-ignore\n const ds = this.dataSourceSrv.getInstanceSettings(current);\n\n if (ds) {\n return {\n label: ds.name.substr(0, 37),\n value: ds.name,\n imgUrl: ds.meta.info.logos.small,\n hideText: hideTextValue,\n meta: ds.meta,\n };\n }\n\n return {\n label: (current ?? 'no name') + ' - not found',\n value: current,\n imgUrl: '',\n hideText: hideTextValue,\n };\n }\n\n getDataSourceOptions() {\n const { tracing, metrics, mixed, dashboard, variables, annotations, pluginId } = this.props;\n const options = this.dataSourceSrv\n // @ts-ignore\n .getList({\n tracing,\n metrics,\n dashboard,\n mixed,\n variables,\n annotations,\n pluginId,\n })\n .map(ds => ({\n value: ds.name,\n label: `${ds.name}${ds.isDefault ? ' (default)' : ''}`,\n imgUrl: ds.meta.info.logos.small,\n meta: ds.meta,\n }));\n\n return options;\n }\n\n render() {\n const { autoFocus, onBlur, openMenuOnFocus, placeholder } = this.props;\n const { error } = this.state;\n const options = this.getDataSourceOptions();\n const value = this.getCurrentValue();\n\n return (\n
\n {\n if (o.meta && isUnsignedPluginSignature(o.meta.signature) && o !== value) {\n return (\n \n {o.label} \n \n );\n }\n return o.label || '';\n }}\n />\n
\n );\n }\n}\n","import React, { Dispatch, SetStateAction, useEffect, useState } from 'react';\nimport { css } from 'emotion';\nimport { VariableSuggestion } from '@grafana/data';\nimport { Button, LegacyForms, DataLinkInput, stylesFactory } from '@grafana/ui';\nconst { FormField, Switch } = LegacyForms;\nimport { DataLinkConfig } from '../types';\nimport { usePrevious } from 'react-use';\nimport { DataSourcePicker } from '../dependencies/DataSourcePicker';\n\nconst getStyles = stylesFactory(() => ({\n firstRow: css`\n display: flex;\n `,\n nameField: css`\n flex: 2;\n `,\n regexField: css`\n flex: 3;\n `,\n row: css`\n display: flex;\n align-items: baseline;\n `,\n}));\n\ntype Props = {\n value: DataLinkConfig;\n onChange: (value: DataLinkConfig) => void;\n onDelete: () => void;\n suggestions: VariableSuggestion[];\n className?: string;\n};\nexport const DataLink = (props: Props) => {\n const { value, onChange, onDelete, suggestions, className } = props;\n const styles = getStyles();\n const [showInternalLink, setShowInternalLink] = useInternalLink(value.datasourceUid);\n\n const handleChange = (field: keyof typeof value) => (event: React.ChangeEvent) => {\n onChange({\n ...value,\n [field]: event.currentTarget.value,\n });\n };\n\n return (\n
\n
\n \n {\n event.preventDefault();\n onDelete();\n }}\n />\n
\n
\n \n onChange({\n ...value,\n url: newValue,\n })\n }\n suggestions={suggestions}\n />\n }\n className={css`\n width: 100%;\n `}\n />\n
\n\n
\n {\n if (showInternalLink) {\n onChange({\n ...value,\n datasourceUid: undefined,\n });\n }\n setShowInternalLink(!showInternalLink);\n }}\n />\n\n {showInternalLink && (\n {\n onChange({\n ...value,\n datasourceUid: ds.uid,\n });\n }}\n current={value.datasourceUid}\n />\n )}\n
\n
\n );\n};\n\nfunction useInternalLink(datasourceUid?: string): [boolean, Dispatch>] {\n const [showInternalLink, setShowInternalLink] = useState(!!datasourceUid);\n const previousUid = usePrevious(datasourceUid);\n\n // Force internal link visibility change if uid changed outside of this component.\n useEffect(() => {\n if (!previousUid && datasourceUid && !showInternalLink) {\n setShowInternalLink(true);\n }\n if (previousUid && !datasourceUid && showInternalLink) {\n setShowInternalLink(false);\n }\n }, [previousUid, datasourceUid, showInternalLink]);\n\n return [showInternalLink, setShowInternalLink];\n}\n","import React from 'react';\nimport { css } from 'emotion';\nimport { Button, stylesFactory, useTheme } from '@grafana/ui';\nimport { GrafanaTheme, VariableOrigin, DataLinkBuiltInVars } from '@grafana/data';\nimport { DataLinkConfig } from '../types';\nimport { DataLink } from './DataLink';\n\nconst getStyles = stylesFactory((theme: GrafanaTheme) => ({\n infoText: css`\n padding-bottom: ${theme.spacing.md};\n color: ${theme.colors.textWeak};\n `,\n dataLink: css`\n margin-bottom: ${theme.spacing.sm};\n `,\n}));\n\ntype Props = {\n value?: DataLinkConfig[];\n onChange: (value: DataLinkConfig[]) => void;\n};\nexport const DataLinks = (props: Props) => {\n const { value, onChange } = props;\n const theme = useTheme();\n const styles = getStyles(theme);\n\n return (\n <>\n

Data links

\n\n
\n Add links to existing fields. Links will be shown in log row details next to the field value.\n
\n\n {value && value.length > 0 && (\n
\n {value.map((field, index) => {\n return (\n {\n const newDataLinks = [...value];\n newDataLinks.splice(index, 1, newField);\n onChange(newDataLinks);\n }}\n onDelete={() => {\n const newDataLinks = [...value];\n newDataLinks.splice(index, 1);\n onChange(newDataLinks);\n }}\n suggestions={[\n {\n value: DataLinkBuiltInVars.valueRaw,\n label: 'Raw value',\n documentation: 'Raw value of the field',\n origin: VariableOrigin.Value,\n },\n ]}\n />\n );\n })}\n
\n )}\n\n {\n event.preventDefault();\n const newDataLinks = [...(value || []), { field: '', url: '' }];\n onChange(newDataLinks);\n }}\n >\n Add\n \n \n );\n};\n","import { createContext, useCallback, useContext } from 'react';\n\nexport interface Action {\n type: T;\n}\n\nexport type Reducer = (state: S, action: A) => S;\n\nexport const combineReducers = (reducers: { [P in keyof S]: Reducer }) => (\n state: S,\n action: A\n): Partial => {\n const newState = {} as S;\n for (const key in reducers) {\n newState[key] = reducers[key](state[key], action);\n }\n return newState;\n};\n\nexport const useStatelessReducer = (\n onChange: (value: State) => void,\n state: State,\n reducer: (state: State, action: A) => State\n) => {\n const dispatch = useCallback(\n (action: A) => {\n onChange(reducer(state, action));\n },\n [onChange, state, reducer]\n );\n\n return dispatch;\n};\n\nexport const DispatchContext = createContext<((action: Action) => void) | undefined>(undefined);\n\nexport const useDispatch = (): ((action: T) => void) => {\n const dispatch = useContext(DispatchContext);\n\n if (!dispatch) {\n throw new Error('Use DispatchContext first.');\n }\n\n return dispatch;\n};\n","import { Action } from '../../hooks/useStatelessReducer';\n\nexport const INIT = 'init';\nconst CHANGE_QUERY = 'change_query';\nconst CHANGE_ALIAS_PATTERN = 'change_alias_pattern';\n\nexport interface InitAction extends Action {}\n\ninterface ChangeQueryAction extends Action {\n payload: {\n query: string;\n };\n}\n\ninterface ChangeAliasPatternAction extends Action {\n payload: {\n aliasPattern: string;\n };\n}\n\nexport const initQuery = (): InitAction => ({ type: INIT });\n\nexport const changeQuery = (query: string): ChangeQueryAction => ({\n type: CHANGE_QUERY,\n payload: {\n query,\n },\n});\n\nexport const changeAliasPattern = (aliasPattern: string): ChangeAliasPatternAction => ({\n type: CHANGE_ALIAS_PATTERN,\n payload: {\n aliasPattern,\n },\n});\n\nexport const queryReducer = (prevQuery: string, action: ChangeQueryAction | InitAction) => {\n switch (action.type) {\n case CHANGE_QUERY:\n return action.payload.query;\n\n case INIT:\n return '';\n\n default:\n return prevQuery;\n }\n};\n\nexport const aliasPatternReducer = (prevAliasPattern: string, action: ChangeAliasPatternAction | InitAction) => {\n switch (action.type) {\n case CHANGE_ALIAS_PATTERN:\n return action.payload.aliasPattern;\n\n case INIT:\n return '';\n\n default:\n return prevAliasPattern;\n }\n};\n","import { defaultMetricAgg } from '../../../../query_def';\nimport { ElasticsearchQuery } from '../../../../types';\nimport { removeEmpty } from '../../../../utils';\nimport { INIT, InitAction } from '../../state';\nimport { isMetricAggregationWithMeta, isMetricAggregationWithSettings, MetricAggregation } from '../aggregations';\nimport { getChildren, metricAggregationConfig } from '../utils';\nimport {\n ADD_METRIC,\n CHANGE_METRIC_TYPE,\n REMOVE_METRIC,\n TOGGLE_METRIC_VISIBILITY,\n MetricAggregationAction,\n CHANGE_METRIC_FIELD,\n CHANGE_METRIC_SETTING,\n CHANGE_METRIC_META,\n CHANGE_METRIC_ATTRIBUTE,\n} from './types';\n\nexport const reducer = (\n state: MetricAggregation[],\n action: MetricAggregationAction | InitAction\n): ElasticsearchQuery['metrics'] => {\n switch (action.type) {\n case ADD_METRIC:\n return [...state, defaultMetricAgg(action.payload.id)];\n\n case REMOVE_METRIC:\n const metricToRemove = state.find(m => m.id === action.payload.id)!;\n const metricsToRemove = [metricToRemove, ...getChildren(metricToRemove, state)];\n const resultingMetrics = state.filter(metric => !metricsToRemove.some(toRemove => toRemove.id === metric.id));\n if (resultingMetrics.length === 0) {\n return [defaultMetricAgg('1')];\n }\n return resultingMetrics;\n\n case CHANGE_METRIC_TYPE:\n return state\n .filter(metric =>\n // When the new metric type is `isSingleMetric` we remove all other metrics from the query\n // leaving only the current one.\n !!metricAggregationConfig[action.payload.type].isSingleMetric ? metric.id === action.payload.id : true\n )\n .map(metric => {\n if (metric.id !== action.payload.id) {\n return metric;\n }\n\n /*\n TODO: The previous version of the query editor was keeping some of the old metric's configurations\n in the new selected one (such as field or some settings).\n It the future would be nice to have the same behavior but it's hard without a proper definition,\n as Elasticsearch will error sometimes if some settings are not compatible.\n */\n return {\n id: metric.id,\n type: action.payload.type,\n ...metricAggregationConfig[action.payload.type].defaults,\n } as MetricAggregation;\n });\n\n case CHANGE_METRIC_FIELD:\n return state.map(metric => {\n if (metric.id !== action.payload.id) {\n return metric;\n }\n\n return {\n ...metric,\n field: action.payload.field,\n };\n });\n\n case TOGGLE_METRIC_VISIBILITY:\n return state.map(metric => {\n if (metric.id !== action.payload.id) {\n return metric;\n }\n\n return {\n ...metric,\n hide: !metric.hide,\n };\n });\n case CHANGE_METRIC_SETTING:\n // @ts-ignore\n return state.map(metric => {\n if (metric.id !== action.payload.metric.id) {\n return metric;\n }\n\n // TODO: Here, instead of this if statement, we should assert that metric is MetricAggregationWithSettings\n if (isMetricAggregationWithSettings(metric)) {\n const newSettings = removeEmpty({\n ...metric.settings,\n [action.payload.settingName]: action.payload.newValue,\n });\n\n return {\n ...metric,\n settings: {\n ...newSettings,\n },\n };\n }\n\n // This should never happen.\n return metric;\n });\n\n case CHANGE_METRIC_META:\n return state.map(metric => {\n if (metric.id !== action.payload.metric.id) {\n return metric;\n }\n\n // TODO: Here, instead of this if statement, we should assert that metric is MetricAggregationWithMeta\n if (isMetricAggregationWithMeta(metric)) {\n return {\n ...metric,\n meta: {\n ...metric.meta,\n [action.payload.meta]: action.payload.newValue,\n },\n };\n }\n\n // This should never happen.\n return metric;\n });\n\n case CHANGE_METRIC_ATTRIBUTE:\n return state.map(metric => {\n if (metric.id !== action.payload.metric.id) {\n return metric;\n }\n\n return {\n ...metric,\n [action.payload.attribute]: action.payload.newValue,\n };\n });\n\n case INIT:\n return [defaultMetricAgg()];\n\n default:\n return state;\n }\n};\n","import { Action } from '../../../../hooks/useStatelessReducer';\nimport { SettingKeyOf } from '../../../types';\nimport {\n MetricAggregation,\n MetricAggregationWithMeta,\n MetricAggregationWithSettings,\n MetricAggregationWithField,\n} from '../aggregations';\n\nexport const ADD_METRIC = '@metrics/add';\nexport const REMOVE_METRIC = '@metrics/remove';\nexport const CHANGE_METRIC_TYPE = '@metrics/change_type';\nexport const CHANGE_METRIC_FIELD = '@metrics/change_field';\nexport const CHANGE_METRIC_SETTING = '@metrics/change_setting';\nexport const CHANGE_METRIC_META = '@metrics/change_meta';\nexport const CHANGE_METRIC_ATTRIBUTE = '@metrics/change_attr';\nexport const TOGGLE_METRIC_VISIBILITY = '@metrics/toggle_visibility';\n\nexport interface AddMetricAction extends Action {\n payload: {\n id: MetricAggregation['id'];\n };\n}\n\nexport interface RemoveMetricAction extends Action {\n payload: {\n id: MetricAggregation['id'];\n };\n}\n\nexport interface ChangeMetricTypeAction extends Action {\n payload: {\n id: MetricAggregation['id'];\n type: MetricAggregation['type'];\n };\n}\n\nexport interface ChangeMetricFieldAction extends Action {\n payload: {\n id: MetricAggregation['id'];\n field: MetricAggregationWithField['field'];\n };\n}\nexport interface ToggleMetricVisibilityAction extends Action {\n payload: {\n id: MetricAggregation['id'];\n };\n}\n\nexport interface ChangeMetricSettingAction\n extends Action {\n payload: {\n metric: T;\n settingName: SettingKeyOf;\n newValue: unknown;\n };\n}\n\nexport interface ChangeMetricMetaAction extends Action {\n payload: {\n metric: T;\n meta: Extract['meta'], string>;\n newValue: string | number | boolean;\n };\n}\n\nexport interface ChangeMetricAttributeAction<\n T extends MetricAggregation,\n K extends Extract = Extract\n> extends Action {\n payload: {\n metric: T;\n attribute: K;\n newValue: T[K];\n };\n}\n\ntype CommonActions =\n | AddMetricAction\n | RemoveMetricAction\n | ChangeMetricTypeAction\n | ChangeMetricFieldAction\n | ToggleMetricVisibilityAction;\n\nexport type MetricAggregationAction =\n | (T extends MetricAggregationWithSettings ? ChangeMetricSettingAction : never)\n | (T extends MetricAggregationWithMeta ? ChangeMetricMetaAction : never)\n | ChangeMetricAttributeAction\n | CommonActions;\n","import { defaultBucketAgg } from '../../../../query_def';\nimport { ElasticsearchQuery } from '../../../../types';\nimport { ChangeMetricTypeAction, CHANGE_METRIC_TYPE } from '../../MetricAggregationsEditor/state/types';\nimport { metricAggregationConfig } from '../../MetricAggregationsEditor/utils';\nimport { BucketAggregation, Terms } from '../aggregations';\nimport { INIT, InitAction } from '../../state';\nimport {\n ADD_BUCKET_AGG,\n REMOVE_BUCKET_AGG,\n CHANGE_BUCKET_AGG_TYPE,\n CHANGE_BUCKET_AGG_FIELD,\n CHANGE_BUCKET_AGG_SETTING,\n BucketAggregationAction,\n} from './types';\nimport { bucketAggregationConfig } from '../utils';\nimport { removeEmpty } from '../../../../utils';\n\nexport const reducer = (\n state: BucketAggregation[],\n action: BucketAggregationAction | ChangeMetricTypeAction | InitAction\n): ElasticsearchQuery['bucketAggs'] => {\n switch (action.type) {\n case ADD_BUCKET_AGG:\n const newAgg: Terms = {\n id: action.payload.id,\n type: 'terms',\n settings: bucketAggregationConfig['terms'].defaultSettings,\n };\n\n // If the last bucket aggregation is a `date_histogram` we add the new one before it.\n const lastAgg = state[state.length - 1];\n if (lastAgg?.type === 'date_histogram') {\n return [...state.slice(0, state.length - 1), newAgg, lastAgg];\n }\n\n return [...state, newAgg];\n\n case REMOVE_BUCKET_AGG:\n return state.filter(bucketAgg => bucketAgg.id !== action.payload.id);\n\n case CHANGE_BUCKET_AGG_TYPE:\n return state.map(bucketAgg => {\n if (bucketAgg.id !== action.payload.id) {\n return bucketAgg;\n }\n\n /*\n TODO: The previous version of the query editor was keeping some of the old bucket aggregation's configurations\n in the new selected one (such as field or some settings).\n It the future would be nice to have the same behavior but it's hard without a proper definition,\n as Elasticsearch will error sometimes if some settings are not compatible.\n */\n return {\n id: bucketAgg.id,\n type: action.payload.newType,\n settings: bucketAggregationConfig[action.payload.newType].defaultSettings,\n } as BucketAggregation;\n });\n\n case CHANGE_BUCKET_AGG_FIELD:\n return state.map(bucketAgg => {\n if (bucketAgg.id !== action.payload.id) {\n return bucketAgg;\n }\n\n return {\n ...bucketAgg,\n field: action.payload.newField,\n };\n });\n\n case CHANGE_METRIC_TYPE:\n // If we are switching to a metric which requires the absence of bucket aggregations\n // we remove all of them.\n if (metricAggregationConfig[action.payload.type].isSingleMetric) {\n return [];\n } else if (state.length === 0) {\n // Else, if there are no bucket aggregations we restore a default one.\n // This happens when switching from a metric that requires the absence of bucket aggregations to\n // one that requires it.\n return [defaultBucketAgg()];\n }\n return state;\n\n case CHANGE_BUCKET_AGG_SETTING:\n // @ts-ignore\n return state.map(bucketAgg => {\n if (bucketAgg.id !== action.payload.bucketAgg.id) {\n return bucketAgg;\n }\n\n const newSettings = removeEmpty({\n ...bucketAgg.settings,\n [action.payload.settingName]: action.payload.newValue,\n });\n\n return {\n ...bucketAgg,\n settings: {\n ...newSettings,\n },\n };\n });\n\n case INIT:\n return [defaultBucketAgg()];\n\n default:\n return state;\n }\n};\n","import { Action } from '../../../../hooks/useStatelessReducer';\nimport { SettingKeyOf } from '../../../types';\nimport { BucketAggregation, BucketAggregationWithField } from '../aggregations';\n\nexport const ADD_BUCKET_AGG = '@bucketAggs/add';\nexport const REMOVE_BUCKET_AGG = '@bucketAggs/remove';\nexport const CHANGE_BUCKET_AGG_TYPE = '@bucketAggs/change_type';\nexport const CHANGE_BUCKET_AGG_FIELD = '@bucketAggs/change_field';\nexport const CHANGE_BUCKET_AGG_SETTING = '@bucketAggs/change_setting';\n\nexport interface AddBucketAggregationAction extends Action {\n payload: {\n id: BucketAggregation['id'];\n };\n}\n\nexport interface RemoveBucketAggregationAction extends Action {\n payload: {\n id: BucketAggregation['id'];\n };\n}\n\nexport interface ChangeBucketAggregationTypeAction extends Action {\n payload: {\n id: BucketAggregation['id'];\n newType: BucketAggregation['type'];\n };\n}\n\nexport interface ChangeBucketAggregationFieldAction extends Action {\n payload: {\n id: BucketAggregation['id'];\n newField: BucketAggregationWithField['field'];\n };\n}\n\nexport interface ChangeBucketAggregationSettingAction\n extends Action {\n payload: {\n bucketAgg: T;\n settingName: SettingKeyOf;\n newValue: unknown;\n };\n}\n\nexport type BucketAggregationAction =\n | AddBucketAggregationAction\n | RemoveBucketAggregationAction\n | ChangeBucketAggregationTypeAction\n | ChangeBucketAggregationFieldAction\n | ChangeBucketAggregationSettingAction;\n","/*\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n *\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 * A copy of the License is located at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * or in the \"license\" file accompanying this file. This file is distributed\n * on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n * express or implied. See the License for the specific language governing\n * permissions and limitations under the License.\n */\n\nimport { Action } from '../../../hooks/useStatelessReducer';\nimport { ElasticsearchQueryType } from '../../../types';\nimport { INIT, InitAction } from '../state';\n\nexport const CHANGE_QUERY_TYPE = 'change_query_type';\n\nexport interface ChangeQueryTypeAction extends Action {\n payload: {\n queryType: ElasticsearchQueryType;\n };\n}\n\nexport const changeQueryType = (queryType: ElasticsearchQueryType): ChangeQueryTypeAction => ({\n type: CHANGE_QUERY_TYPE,\n payload: {\n queryType,\n },\n});\n\nexport const queryTypeReducer = (prevQueryType: ElasticsearchQueryType, action: ChangeQueryTypeAction | InitAction) => {\n switch (action.type) {\n case CHANGE_QUERY_TYPE:\n return action.payload.queryType;\n\n case INIT:\n return ElasticsearchQueryType.Lucene;\n\n default:\n return prevQueryType;\n }\n};\n","/*\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n *\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 * A copy of the License is located at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * or in the \"license\" file accompanying this file. This file is distributed\n * on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n * express or implied. See the License for the specific language governing\n * permissions and limitations under the License.\n */\n\nimport { Action } from '../../../hooks/useStatelessReducer';\nimport { INIT, InitAction } from '../state';\nimport { PPLFormatType } from './formats';\n\nexport const CHANGE_FORMAT = 'change_format';\n\nexport interface ChangeFormatAction extends Action {\n payload: {\n format: PPLFormatType;\n };\n}\n\nexport const changeFormat = (format: PPLFormatType): ChangeFormatAction => ({\n type: CHANGE_FORMAT,\n payload: {\n format,\n },\n});\n\nexport const formatReducer = (prevFormat: PPLFormatType, action: ChangeFormatAction | InitAction) => {\n switch (action.type) {\n case CHANGE_FORMAT:\n return action.payload.format;\n\n case INIT:\n return 'table';\n\n default:\n return prevFormat;\n }\n};\n","import React, { createContext, FunctionComponent, useContext } from 'react';\nimport { ElasticDatasource } from '../../datasource';\nimport { combineReducers, useStatelessReducer, DispatchContext } from '../../hooks/useStatelessReducer';\nimport { ElasticsearchQuery } from '../../types';\n\nimport { reducer as metricsReducer } from './MetricAggregationsEditor/state/reducer';\nimport { reducer as bucketAggsReducer } from './BucketAggregationsEditor/state/reducer';\nimport { queryTypeReducer } from './QueryTypeEditor/state';\nimport { formatReducer } from './PPLFormatEditor/state';\nimport { aliasPatternReducer, queryReducer, initQuery } from './state';\n\nconst DatasourceContext = createContext(undefined);\nconst QueryContext = createContext(undefined);\n\ninterface Props {\n query: ElasticsearchQuery;\n onChange: (query: ElasticsearchQuery) => void;\n datasource: ElasticDatasource;\n}\n\nexport const ElasticsearchProvider: FunctionComponent = ({ children, onChange, query, datasource }) => {\n const reducer = combineReducers({\n query: queryReducer,\n queryType: queryTypeReducer,\n alias: aliasPatternReducer,\n metrics: metricsReducer,\n bucketAggs: bucketAggsReducer,\n format: formatReducer,\n });\n\n const dispatch = useStatelessReducer(\n // timeField is part of the query model, but its value is always set to be the one from datasource settings.\n newState => onChange({ ...query, ...newState, timeField: datasource.timeField }),\n query,\n reducer\n );\n\n // This initializes the query by dispatching an init action to each reducer.\n // useStatelessReducer will then call `onChange` with the newly generated query\n if (!query.metrics && !query.bucketAggs) {\n dispatch(initQuery());\n\n return null;\n }\n\n return (\n \n \n {children}\n \n \n );\n};\n\nexport const useQuery = (): ElasticsearchQuery => {\n const query = useContext(QueryContext);\n\n if (!query) {\n throw new Error('use ElasticsearchProvider first.');\n }\n\n return query;\n};\n\nexport const useDatasource = () => {\n const datasource = useContext(DatasourceContext);\n if (!datasource) {\n throw new Error('use ElasticsearchProvider first.');\n }\n\n return datasource;\n};\n","/*\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n *\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 * A copy of the License is located at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * or in the \"license\" file accompanying this file. This file is distributed\n * on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n * express or implied. See the License for the specific language governing\n * permissions and limitations under the License.\n */\n\nimport { SelectableValue } from '@grafana/data';\nimport { ElasticsearchQueryType, QueryTypeConfiguration } from '../../../types';\n\nexport const queryTypeConfig: QueryTypeConfiguration = {\n [ElasticsearchQueryType.Lucene]: { label: 'Lucene' },\n [ElasticsearchQueryType.PPL]: { label: 'PPL' },\n};\n\nexport const getQueryTypeOptions = (\n supportedTypes: ElasticsearchQueryType[]\n): Array> => {\n return Object.entries(queryTypeConfig)\n .filter(([queryType, _]) => supportedTypes.includes(queryType as ElasticsearchQueryType))\n .map(([key, { label }]) => ({\n label,\n value: key as ElasticsearchQueryType,\n }));\n};\n","import { css } from 'emotion';\n\nexport const segmentStyles = css`\n min-width: 150px;\n`;\n","/*\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n *\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 * A copy of the License is located at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * or in the \"license\" file accompanying this file. This file is distributed\n * on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n * express or implied. See the License for the specific language governing\n * permissions and limitations under the License.\n */\n\nimport React, { FunctionComponent } from 'react';\nimport { Segment } from '@grafana/ui';\nimport { useDatasource } from '../ElasticsearchQueryContext';\nimport { useDispatch } from '../../../hooks/useStatelessReducer';\nimport { changeQueryType } from './state';\nimport { queryTypeConfig, getQueryTypeOptions } from './utils';\nimport { segmentStyles } from '../styles';\nimport { ElasticsearchQueryType } from '../../../types';\n\nconst toOption = (queryType: ElasticsearchQueryType) => ({\n label: queryTypeConfig[queryType].label,\n value: queryType,\n});\n\ninterface Props {\n value: ElasticsearchQueryType;\n}\n\nexport const QueryTypeEditor: FunctionComponent = ({ value }) => {\n const datasource = useDatasource();\n const dispatch = useDispatch();\n\n return (\n dispatch(changeQueryType(e.value!))}\n value={toOption(value)}\n />\n );\n};\n","import { GrafanaTheme } from '@grafana/data';\nimport { stylesFactory } from '@grafana/ui';\nimport { css } from 'emotion';\n\nexport const getStyles = stylesFactory((theme: GrafanaTheme, hidden: boolean) => ({\n color:\n hidden &&\n css`\n &,\n &:hover,\n label,\n a {\n color: ${hidden ? theme.colors.textFaint : theme.colors.text};\n }\n `,\n}));\n","import { SettingKeyOf } from '../../../types';\nimport { MetricAggregation, MetricAggregationWithMeta, MetricAggregationWithSettings } from '../aggregations';\nimport {\n ADD_METRIC,\n CHANGE_METRIC_FIELD,\n CHANGE_METRIC_TYPE,\n REMOVE_METRIC,\n TOGGLE_METRIC_VISIBILITY,\n CHANGE_METRIC_SETTING,\n CHANGE_METRIC_META,\n CHANGE_METRIC_ATTRIBUTE,\n MetricAggregationAction,\n ChangeMetricAttributeAction,\n ChangeMetricSettingAction,\n ChangeMetricMetaAction,\n} from './types';\n\nexport const addMetric = (id: MetricAggregation['id']): MetricAggregationAction => ({\n type: ADD_METRIC,\n payload: {\n id,\n },\n});\n\nexport const removeMetric = (id: MetricAggregation['id']): MetricAggregationAction => ({\n type: REMOVE_METRIC,\n payload: {\n id,\n },\n});\n\nexport const changeMetricType = (\n id: MetricAggregation['id'],\n type: MetricAggregation['type']\n): MetricAggregationAction => ({\n type: CHANGE_METRIC_TYPE,\n payload: {\n id,\n type,\n },\n});\n\nexport const changeMetricField = (id: MetricAggregation['id'], field: string): MetricAggregationAction => ({\n type: CHANGE_METRIC_FIELD,\n payload: {\n id,\n field,\n },\n});\n\nexport const toggleMetricVisibility = (id: MetricAggregation['id']): MetricAggregationAction => ({\n type: TOGGLE_METRIC_VISIBILITY,\n payload: {\n id,\n },\n});\n\nexport const changeMetricAttribute = >(\n metric: T,\n attribute: K,\n newValue: T[K]\n): ChangeMetricAttributeAction => ({\n type: CHANGE_METRIC_ATTRIBUTE,\n payload: {\n metric,\n attribute,\n newValue,\n },\n});\n\nexport const changeMetricSetting = >(\n metric: T,\n settingName: K,\n // Maybe this could have been NonNullable[K], but it doesn't seem to work really well\n newValue: NonNullable[K]\n): ChangeMetricSettingAction => ({\n type: CHANGE_METRIC_SETTING,\n payload: {\n metric,\n settingName,\n newValue,\n },\n});\n\nexport const changeMetricMeta = (\n metric: T,\n meta: Extract['meta'], string>,\n newValue: string | number | boolean\n): ChangeMetricMetaAction => ({\n type: CHANGE_METRIC_META,\n payload: {\n metric,\n meta,\n newValue,\n },\n});\n","import { Icon } from '@grafana/ui';\nimport { cx, css } from 'emotion';\nimport React, { FunctionComponent, ComponentProps, ButtonHTMLAttributes } from 'react';\n\nconst SROnly = css`\n clip: rect(0 0 0 0);\n clip-path: inset(50%);\n height: 1px;\n overflow: hidden;\n position: absolute;\n white-space: nowrap;\n width: 1px;\n`;\n\ninterface Props {\n iconName: ComponentProps['name'];\n onClick: () => void;\n className?: string;\n label: string;\n}\n\nexport const IconButton: FunctionComponent> = ({\n iconName,\n onClick,\n className,\n label,\n ...buttonProps\n}) => (\n \n);\n","import { css } from 'emotion';\nimport React, { FunctionComponent } from 'react';\nimport { IconButton } from './IconButton';\n\ninterface Props {\n index: number;\n elements: any[];\n onAdd: () => void;\n onRemove: () => void;\n}\n\n/**\n * A component used to show add & remove buttons for mutable lists of values. Wether to show or not the add or the remove buttons\n * depends on the `index` and `elements` props. This enforces a consistent experience whenever this pattern is used.\n */\nexport const AddRemove: FunctionComponent = ({ index, onAdd, onRemove, elements }) => {\n return (\n \n {index === 0 && }\n\n {elements.length >= 2 && }\n \n );\n};\n","import React, { FunctionComponent } from 'react';\nimport { css, cx } from 'emotion';\nimport { SelectableValue } from '@grafana/data';\nimport { Segment } from '@grafana/ui';\nimport { describeMetric } from '../utils';\nimport { MetricAggregation } from './QueryEditor/MetricAggregationsEditor/aggregations';\n\nconst noWrap = css`\n white-space: nowrap;\n`;\n\nconst toOption = (metric: MetricAggregation) => ({\n label: describeMetric(metric),\n value: metric,\n});\n\nconst toOptions = (metrics: MetricAggregation[]): Array> => metrics.map(toOption);\n\ninterface Props {\n options: MetricAggregation[];\n onChange: (e: SelectableValue) => void;\n className?: string;\n value?: string;\n}\n\nexport const MetricPicker: FunctionComponent = ({ options, onChange, className, value }) => (\n option.id === value)!) : null}\n />\n);\n","import { PipelineVariable } from '../../../aggregations';\nimport { defaultPipelineVariable } from '../utils';\nimport {\n PipelineVariablesAction,\n REMOVE_PIPELINE_VARIABLE,\n ADD_PIPELINE_VARIABLE,\n RENAME_PIPELINE_VARIABLE,\n CHANGE_PIPELINE_VARIABLE_METRIC,\n} from './types';\n\nexport const reducer = (state: PipelineVariable[] = [], action: PipelineVariablesAction) => {\n switch (action.type) {\n case ADD_PIPELINE_VARIABLE:\n return [...state, defaultPipelineVariable()];\n\n case REMOVE_PIPELINE_VARIABLE:\n return state.slice(0, action.payload.index).concat(state.slice(action.payload.index + 1));\n\n case RENAME_PIPELINE_VARIABLE:\n return state.map((pipelineVariable, index) => {\n if (index !== action.payload.index) {\n return pipelineVariable;\n }\n\n return {\n ...pipelineVariable,\n name: action.payload.newName,\n };\n });\n\n case CHANGE_PIPELINE_VARIABLE_METRIC:\n return state.map((pipelineVariable, index) => {\n if (index !== action.payload.index) {\n return pipelineVariable;\n }\n\n return {\n ...pipelineVariable,\n pipelineAgg: action.payload.newMetric,\n };\n });\n\n default:\n return state;\n }\n};\n","import { Action } from '../../../../../../hooks/useStatelessReducer';\n\nexport const ADD_PIPELINE_VARIABLE = '@pipelineVariables/add';\nexport const REMOVE_PIPELINE_VARIABLE = '@pipelineVariables/remove';\nexport const RENAME_PIPELINE_VARIABLE = '@pipelineVariables/rename';\nexport const CHANGE_PIPELINE_VARIABLE_METRIC = '@pipelineVariables/change_metric';\n\nexport type AddPipelineVariableAction = Action;\n\nexport interface RemovePipelineVariableAction extends Action {\n payload: {\n index: number;\n };\n}\n\nexport interface RenamePipelineVariableAction extends Action {\n payload: {\n index: number;\n newName: string;\n };\n}\n\nexport interface ChangePipelineVariableMetricAction extends Action {\n payload: {\n index: number;\n newMetric: string;\n };\n}\n\nexport type PipelineVariablesAction =\n | AddPipelineVariableAction\n | RemovePipelineVariableAction\n | RenamePipelineVariableAction\n | ChangePipelineVariableMetricAction;\n","import React, { ComponentProps, useState } from 'react';\nimport { InlineField, Input } from '@grafana/ui';\nimport { useDispatch } from '../../../../hooks/useStatelessReducer';\nimport { changeMetricSetting } from '../state/actions';\nimport { ChangeMetricSettingAction } from '../state/types';\nimport { SettingKeyOf } from '../../../types';\nimport { MetricAggregationWithSettings } from '../aggregations';\nimport { uniqueId } from 'lodash';\n\ninterface Props> {\n label: string;\n settingName: K;\n metric: T;\n placeholder?: ComponentProps['placeholder'];\n tooltip?: ComponentProps['tooltip'];\n}\n\nexport function SettingField>({\n label,\n settingName,\n metric,\n placeholder,\n tooltip,\n}: Props) {\n const dispatch = useDispatch>();\n const [id] = useState(uniqueId(`es-field-id-`));\n const settings = metric.settings;\n\n return (\n \n dispatch(changeMetricSetting(metric, settingName, e.target.value as any))}\n defaultValue={settings?.[settingName as keyof typeof settings]}\n />\n \n );\n}\n","import React, { Fragment, FunctionComponent, useEffect } from 'react';\nimport { Input, InlineLabel } from '@grafana/ui';\nimport { MetricAggregationAction } from '../../state/types';\nimport { changeMetricAttribute } from '../../state/actions';\nimport { css } from 'emotion';\nimport { AddRemove } from '../../../../AddRemove';\nimport { useStatelessReducer, useDispatch } from '../../../../../hooks/useStatelessReducer';\nimport { MetricPicker } from '../../../../MetricPicker';\nimport { reducer } from './state/reducer';\nimport {\n addPipelineVariable,\n removePipelineVariable,\n renamePipelineVariable,\n changePipelineVariableMetric,\n} from './state/actions';\nimport { SettingField } from '../SettingField';\nimport { BucketScript, MetricAggregation } from '../../aggregations';\n\ninterface Props {\n value: BucketScript;\n previousMetrics: MetricAggregation[];\n}\n\nexport const BucketScriptSettingsEditor: FunctionComponent = ({ value, previousMetrics }) => {\n const upperStateDispatch = useDispatch>();\n\n const dispatch = useStatelessReducer(\n newState => upperStateDispatch(changeMetricAttribute(value, 'pipelineVariables', newState)),\n value.pipelineVariables,\n reducer\n );\n\n // The model might not have pipeline variables (or an empty array of pipeline vars) in it because of the way it was built in previous versions of the datasource.\n // If this is the case we add a default one.\n useEffect(() => {\n if (!value.pipelineVariables?.length) {\n dispatch(addPipelineVariable());\n }\n }, []);\n\n return (\n <>\n \n Variables\n \n {value.pipelineVariables!.map((pipelineVar, index) => (\n \n \n dispatch(renamePipelineVariable(e.target.value, index))}\n />\n dispatch(changePipelineVariableMetric(e.value!.id, index))}\n options={previousMetrics}\n value={pipelineVar.pipelineAgg}\n />\n \n\n dispatch(addPipelineVariable())}\n onRemove={() => dispatch(removePipelineVariable(index))}\n />\n \n ))}\n \n \n\n to reference a variable. Elasticsearch pre-v5.0: Scripting language is per default Groovy if not changed. For Groovy use to reference a variable.\"\n placeholder=\"params.var1 / params.var2\"\n />\n \n );\n};\n","import {\n ADD_PIPELINE_VARIABLE,\n REMOVE_PIPELINE_VARIABLE,\n PipelineVariablesAction,\n RENAME_PIPELINE_VARIABLE,\n CHANGE_PIPELINE_VARIABLE_METRIC,\n} from './types';\n\nexport const addPipelineVariable = (): PipelineVariablesAction => ({\n type: ADD_PIPELINE_VARIABLE,\n});\n\nexport const removePipelineVariable = (index: number): PipelineVariablesAction => ({\n type: REMOVE_PIPELINE_VARIABLE,\n payload: {\n index,\n },\n});\n\nexport const renamePipelineVariable = (newName: string, index: number): PipelineVariablesAction => ({\n type: RENAME_PIPELINE_VARIABLE,\n payload: {\n index,\n newName,\n },\n});\n\nexport const changePipelineVariableMetric = (newMetric: string, index: number): PipelineVariablesAction => ({\n type: CHANGE_PIPELINE_VARIABLE_METRIC,\n payload: {\n index,\n newMetric,\n },\n});\n","import { GrafanaTheme } from '@grafana/data';\nimport { Icon, stylesFactory, useTheme } from '@grafana/ui';\nimport { css, cx } from 'emotion';\nimport React, { FunctionComponent, useState } from 'react';\nimport { segmentStyles } from './styles';\n\nconst getStyles = stylesFactory((theme: GrafanaTheme, hidden: boolean) => {\n return {\n wrapper: css`\n display: flex;\n flex-direction: column;\n `,\n settingsWrapper: css`\n padding-top: ${theme.spacing.xs};\n `,\n icon: css`\n margin-right: ${theme.spacing.xs};\n `,\n button: css`\n justify-content: start;\n ${hidden &&\n css`\n color: ${theme.colors.textFaint};\n `}\n `,\n };\n});\ninterface Props {\n label: string;\n hidden?: boolean;\n}\n\nexport const SettingsEditorContainer: FunctionComponent = ({ label, children, hidden = false }) => {\n const [open, setOpen] = useState(false);\n\n const styles = getStyles(useTheme(), hidden);\n\n return (\n
\n setOpen(!open)}\n aria-expanded={open}\n >\n \n {label}\n \n\n {open &&
{children}
}\n
\n );\n};\n","import { Input, InlineField, Select, Switch } from '@grafana/ui';\nimport React, { FunctionComponent } from 'react';\nimport { useDispatch } from '../../../../hooks/useStatelessReducer';\nimport { movingAvgModelOptions } from '../../../../query_def';\nimport { isEWMAMovingAverage, isHoltMovingAverage, isHoltWintersMovingAverage, MovingAverage } from '../aggregations';\nimport { changeMetricSetting } from '../state/actions';\n\ninterface Props {\n metric: MovingAverage;\n}\n\n// The way we handle changes for those settings is not ideal compared to the other components in the editor\nexport const MovingAverageSettingsEditor: FunctionComponent = ({ metric }) => {\n const dispatch = useDispatch();\n\n return (\n <>\n \n dispatch(changeMetricSetting(metric, 'model', value.value!))}\n options={movingAvgModelOptions}\n value={metric.settings?.model}\n />\n \n\n \n dispatch(changeMetricSetting(metric, 'window', parseInt(e.target.value!, 10)))}\n defaultValue={metric.settings?.window}\n />\n \n\n \n dispatch(changeMetricSetting(metric, 'predict', parseInt(e.target.value!, 10)))}\n defaultValue={metric.settings?.predict}\n />\n \n\n {isEWMAMovingAverage(metric) && (\n <>\n \n dispatch(changeMetricSetting(metric, 'alpha', parseInt(e.target.value!, 10)))}\n defaultValue={metric.settings?.alpha}\n />\n \n\n \n ) =>\n dispatch(changeMetricSetting(metric, 'minimize', e.target.checked))\n }\n checked={!!metric.settings?.minimize}\n />\n \n \n )}\n\n {isHoltMovingAverage(metric) && (\n <>\n \n \n dispatch(\n changeMetricSetting(metric, 'settings', {\n ...metric.settings?.settings,\n alpha: parseInt(e.target.value!, 10),\n })\n )\n }\n defaultValue={metric.settings?.settings?.alpha}\n />\n \n \n \n dispatch(\n changeMetricSetting(metric, 'settings', {\n ...metric.settings?.settings,\n beta: parseInt(e.target.value!, 10),\n })\n )\n }\n defaultValue={metric.settings?.settings?.beta}\n />\n \n\n \n ) =>\n dispatch(changeMetricSetting(metric, 'minimize', e.target.checked))\n }\n checked={!!metric.settings?.minimize}\n />\n \n \n )}\n\n {isHoltWintersMovingAverage(metric) && (\n <>\n \n \n dispatch(\n changeMetricSetting(metric, 'settings', {\n ...metric.settings?.settings,\n alpha: parseInt(e.target.value!, 10),\n })\n )\n }\n defaultValue={metric.settings?.settings?.alpha}\n />\n \n \n \n dispatch(\n changeMetricSetting(metric, 'settings', {\n ...metric.settings?.settings,\n beta: parseInt(e.target.value!, 10),\n })\n )\n }\n defaultValue={metric.settings?.settings?.beta}\n />\n \n \n \n dispatch(\n changeMetricSetting(metric, 'settings', {\n ...metric.settings?.settings,\n gamma: parseInt(e.target.value!, 10),\n })\n )\n }\n defaultValue={metric.settings?.settings?.gamma}\n />\n \n \n \n dispatch(\n changeMetricSetting(metric, 'settings', {\n ...metric.settings?.settings,\n period: parseInt(e.target.value!, 10),\n })\n )\n }\n defaultValue={metric.settings?.settings?.period}\n />\n \n\n \n ) =>\n dispatch(\n changeMetricSetting(metric, 'settings', { ...metric.settings?.settings, pad: e.target.checked })\n )\n }\n checked={!!metric.settings?.settings?.pad}\n />\n \n\n \n ) =>\n dispatch(changeMetricSetting(metric, 'minimize', e.target.checked))\n }\n checked={!!metric.settings?.minimize}\n />\n \n \n )}\n \n );\n};\n","import { InlineField, Input, Switch } from '@grafana/ui';\nimport React, { FunctionComponent, ComponentProps, useState } from 'react';\nimport { extendedStats } from '../../../../query_def';\nimport { useDispatch } from '../../../../hooks/useStatelessReducer';\nimport { changeMetricMeta, changeMetricSetting } from '../state/actions';\nimport {\n MetricAggregation,\n isMetricAggregationWithInlineScript,\n isMetricAggregationWithMissingSupport,\n ExtendedStat,\n} from '../aggregations';\nimport { BucketScriptSettingsEditor } from './BucketScriptSettingsEditor';\nimport { SettingField } from './SettingField';\nimport { SettingsEditorContainer } from '../../SettingsEditorContainer';\nimport { useDescription } from './useDescription';\nimport { MovingAverageSettingsEditor } from './MovingAverageSettingsEditor';\nimport { uniqueId } from 'lodash';\nimport { metricAggregationConfig } from '../utils';\n\n// TODO: Move this somewhere and share it with BucketsAggregation Editor\nconst inlineFieldProps: Partial> = {\n labelWidth: 16,\n};\n\ninterface Props {\n metric: MetricAggregation;\n previousMetrics: MetricAggregation[];\n}\n\nexport const SettingsEditor: FunctionComponent = ({ metric, previousMetrics }) => {\n const dispatch = useDispatch();\n const description = useDescription(metric);\n\n return (\n \n );\n};\n\ninterface ExtendedStatSettingProps {\n stat: ExtendedStat;\n onChange: (checked: boolean) => void;\n value: boolean;\n}\nconst ExtendedStatSetting: FunctionComponent = ({ stat, onChange, value }) => {\n // this is needed for the htmlFor prop in the label so that clicking the label will toggle the switch state.\n const [id] = useState(uniqueId(`es-field-id-`));\n\n return (\n \n ) => onChange(e.target.checked)} value={value} />\n \n );\n};\n","import { extendedStats } from '../../../../query_def';\nimport { MetricAggregation } from '../aggregations';\n\nconst hasValue = (value: string) => (object: { value: string }) => object.value === value;\n\n// FIXME: All the defaults and validations down here should be defined somewhere else\n// as they are also the defaults that are gonna be applied to the query.\n// In the previous version, the same method was taking care of describing the settings and setting defaults.\nexport const useDescription = (metric: MetricAggregation): string => {\n switch (metric.type) {\n case 'cardinality': {\n const precisionThreshold = metric.settings?.precision_threshold || '';\n return `Precision threshold: ${precisionThreshold}`;\n }\n\n case 'percentiles':\n if (metric.settings?.percents && metric.settings?.percents?.length >= 1) {\n return `Values: ${metric.settings?.percents}`;\n }\n\n return 'Percents: Default';\n\n case 'extended_stats': {\n const selectedStats = Object.entries(metric.meta || {})\n .map(([key, value]) => value && extendedStats.find(hasValue(key))?.label)\n .filter(Boolean);\n\n return `Stats: ${selectedStats.length > 0 ? selectedStats.join(', ') : 'None selected'}`;\n }\n\n case 'raw_document':\n case 'raw_data': {\n const size = metric.settings?.size || 500;\n return `Size: ${size}`;\n }\n\n default:\n return 'Options';\n }\n};\n","import { MetricFindValue, SelectableValue } from '@grafana/data';\nimport { Segment, SegmentAsync, useTheme } from '@grafana/ui';\nimport { cx } from 'emotion';\nimport React, { FunctionComponent } from 'react';\nimport { useDatasource, useQuery } from '../ElasticsearchQueryContext';\nimport { useDispatch } from '../../../hooks/useStatelessReducer';\nimport { getStyles } from './styles';\nimport { SettingsEditor } from './SettingsEditor';\nimport { MetricAggregationAction } from './state/types';\nimport { metricAggregationConfig } from './utils';\nimport { changeMetricField, changeMetricType } from './state/actions';\nimport { MetricPicker } from '../../MetricPicker';\nimport { segmentStyles } from '../styles';\nimport {\n isMetricAggregationWithField,\n isMetricAggregationWithSettings,\n isPipelineAggregation,\n isPipelineAggregationWithMultipleBucketPaths,\n MetricAggregation,\n MetricAggregationType,\n} from './aggregations';\n\nconst toOption = (metric: MetricAggregation) => ({\n label: metricAggregationConfig[metric.type].label,\n value: metric.type,\n});\n\n// @ts-ignore\nconst toSelectableValue = ({ value, text }: MetricFindValue): SelectableValue => ({\n label: text,\n value: `${value || text}`,\n});\n\ninterface Props {\n value: MetricAggregation;\n}\n\n// If a metric is a Pipeline Aggregation (https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-pipeline.html)\n// it doesn't make sense to show it in the type picker when there is no non-pipeline-aggregation previously selected\n// as they work on the outputs produced from other aggregations rather than from documents or fields.\n// This means we should filter them out from the type picker if there's no other \"basic\" aggregation before the current one.\nconst isBasicAggregation = (metric: MetricAggregation) => !metricAggregationConfig[metric.type].isPipelineAgg;\n\nconst getTypeOptions = (\n previousMetrics: MetricAggregation[],\n esVersion: number\n): Array> => {\n // we'll include Pipeline Aggregations only if at least one previous metric is a \"Basic\" one\n const includePipelineAggregations = previousMetrics.some(isBasicAggregation);\n\n return (\n Object.entries(metricAggregationConfig)\n // Only showing metrics type supported by the configured version of ES\n .filter(([_, { minVersion = 0, maxVersion = esVersion }]) => {\n // TODO: Double check this\n return esVersion >= minVersion && esVersion <= maxVersion;\n })\n // Filtering out Pipeline Aggregations if there's no basic metric selected before\n .filter(([_, config]) => includePipelineAggregations || !config.isPipelineAgg)\n .map(([key, { label }]) => ({\n label,\n value: key as MetricAggregationType,\n }))\n );\n};\n\nexport const MetricEditor: FunctionComponent = ({ value }) => {\n const styles = getStyles(useTheme(), !!value.hide);\n const datasource = useDatasource();\n const query = useQuery();\n const dispatch = useDispatch();\n\n const previousMetrics = query.metrics!.slice(\n 0,\n query.metrics!.findIndex(m => m.id === value.id)\n );\n\n // TODO: This could be common with the one in BucketAggregationEditor\n const getFields = async () => {\n const get = () => {\n if (value.type === 'cardinality') {\n return datasource.getFields();\n }\n return datasource.getFields('number');\n };\n\n return (await get()).map(toSelectableValue);\n };\n\n return (\n <>\n dispatch(changeMetricType(value.id, e.value!))}\n value={toOption(value)}\n />\n\n {isMetricAggregationWithField(value) && !isPipelineAggregation(value) && (\n dispatch(changeMetricField(value.id, e.value!))}\n placeholder=\"Select Field\"\n value={value.field}\n />\n )}\n\n {isPipelineAggregation(value) && !isPipelineAggregationWithMultipleBucketPaths(value) && (\n dispatch(changeMetricField(value.id, e.value?.id!))}\n options={previousMetrics}\n value={value.field}\n />\n )}\n\n {isMetricAggregationWithSettings(value) && }\n \n );\n};\n","import { GrafanaTheme } from '@grafana/data';\nimport { IconButton, InlineFieldRow, InlineLabel, stylesFactory, useTheme, InlineSegmentGroup } from '@grafana/ui';\nimport { css } from 'emotion';\nimport { noop } from 'lodash';\nimport React, { FunctionComponent } from 'react';\n\ninterface Props {\n label: string;\n onRemoveClick?: false | (() => void);\n onHideClick?: false | (() => void);\n hidden?: boolean;\n disableRemove?: boolean;\n}\n\nexport const QueryEditorRow: FunctionComponent = ({\n children,\n label,\n onRemoveClick,\n onHideClick,\n hidden = false,\n disableRemove = false,\n}) => {\n const theme = useTheme();\n const styles = getStyles(theme);\n\n return (\n \n \n \n {label}\n \n {onHideClick && (\n \n )}\n {onRemoveClick && (\n \n )}\n \n \n \n {children}\n \n );\n};\n\nconst getStyles = stylesFactory((theme: GrafanaTheme) => {\n return {\n iconWrapper: css`\n display: flex;\n `,\n icon: css`\n color: ${theme.colors.textWeak};\n margin-left: ${theme.spacing.xxs};\n `,\n };\n});\n","import React, { FunctionComponent } from 'react';\nimport { MetricEditor } from './MetricEditor';\nimport { useDispatch } from '../../../hooks/useStatelessReducer';\nimport { MetricAggregationAction } from './state/types';\nimport { metricAggregationConfig } from './utils';\nimport { addMetric, removeMetric, toggleMetricVisibility } from './state/actions';\nimport { MetricAggregation } from './aggregations';\nimport { useQuery } from '../ElasticsearchQueryContext';\nimport { QueryEditorRow } from '../QueryEditorRow';\nimport { IconButton } from '../../IconButton';\n\ninterface Props {\n nextId: MetricAggregation['id'];\n}\n\nexport const MetricAggregationsEditor: FunctionComponent = ({ nextId }) => {\n const dispatch = useDispatch();\n const { metrics } = useQuery();\n const totalMetrics = metrics?.length || 0;\n\n return (\n <>\n {metrics?.map((metric, index) => (\n