azureMonitorPlugin.dcdd38e4ee204b628148.js 135 KB

12
  1. "use strict";(self.webpackChunkgrafana=self.webpackChunkgrafana||[]).push([[2364],{79462:(e,t,r)=>{r.r(t),r.d(t,{plugin:()=>pr});var s=r(43215),o=r(68404),i=r(90923),a=r(69783),n=r(82897),c=r.n(n);class u{static createISO8601Duration(e,t){return(0,n.includes)(["hour","minute","h","m"],t)?`PT${e}${t[0].toUpperCase()}`:`P${e}${t[0].toUpperCase()}`}static createISO8601DurationFromInterval(e){const t=+e.slice(0,e.length-1),r=e[e.length-1];if(e.indexOf("ms")>-1)return u.createISO8601Duration(1,"m");if("s"===e[e.length-1]){let e=60*t%60;return e<1&&(e=1),u.createISO8601Duration(e,"m")}return u.createISO8601Duration(t,r)}static findClosestTimeGrain(e,t){const r=(0,n.filter)(t,(e=>"auto"!==e));let o=r[0];const i=s.rangeUtil.intervalToMs(e);for(let e=0;e<r.length;e++)i>s.rangeUtil.intervalToMs(r[e])&&(o=e+1<r.length?r[e+1]:r[e]);return o}static createTimeGrainFromISO8601Duration(e){let t=1;"PT"===e.substring(0,2)&&(t=2);const r=e.substring(t,e.length-1),s=e.substring(e.length-1);return r+" "+u.timeUnitToText(+r,s)}static timeUnitToText(e,t){let r="";return"S"===t&&(r="second"),"M"===t&&(r="minute"),"H"===t&&(r="hour"),"D"===t&&(r="day"),e>1?r+"s":r}static createKbnUnitFromISO8601Duration(e){if("auto"===e)return"auto";let t=1;"PT"===e.substring(0,2)&&(t=2);const r=e.substring(t,e.length-1),s=e.substring(e.length-1);return r+u.timeUnitToKbn(+r,s)}static timeUnitToKbn(e,t){return"S"===t?"s":"M"===t?"m":"H"===t?"h":"D"===t?"d":""}}class l{static parseResponseValues(e,t,r){const s=[];if(!e)return s;for(let o=0;o<e.value.length;o++)if(!(0,n.find)(s,["value",(0,n.get)(e.value[o],r)])){const i=(0,n.get)(e.value[o],r),a=(0,n.get)(e.value[o],t,i);s.push({text:a,value:i})}return s}static parseResourceNames(e,t){const r=[];if(!e)return r;for(let s=0;s<e.value.length;s++)"string"==typeof e.value[s].type&&e.value[s].type.toLocaleLowerCase()===t.toLocaleLowerCase()&&r.push({text:e.value[s].name,value:e.value[s].name});return r}static parseMetadata(e,t){var r,s;const o=["None","Average","Minimum","Maximum","Total","Count"],i=null==e?void 0:e.value.find((e=>e.name.value===t));return i?{primaryAggType:i.primaryAggregationType,supportedAggTypes:i.supportedAggregationTypes||o,supportedTimeGrains:[{label:"Auto",value:"auto"},...l.parseTimeGrains(null!==(r=i.metricAvailabilities)&&void 0!==r?r:[])],dimensions:l.parseDimensions(null!==(s=i.dimensions)&&void 0!==s?s:[])}:{primaryAggType:"",supportedAggTypes:o,supportedTimeGrains:[],dimensions:[]}}static parseTimeGrains(e){const t=[];return e?(e.forEach((e=>{e.timeGrain&&t.push({label:u.createTimeGrainFromISO8601Duration(e.timeGrain),value:e.timeGrain})})),t):t}static parseDimensions(e){return e.map((e=>({label:e.localizedValue||e.value,value:e.value})))}static parseSubscriptions(e){const t=[];if(!e)return t;const r="subscriptionId";for(let s=0;s<e.value.length;s++)(0,n.find)(t,["value",(0,n.get)(e.value[s],r)])||t.push({text:`${(0,n.get)(e.value[s],"displayName")}`,value:(0,n.get)(e.value[s],r)});return t}static parseSubscriptionsForSelect(e){const t=[];if(!e)return t;const r="subscriptionId";for(let s=0;s<e.data.value.length;s++)(0,n.find)(t,["value",(0,n.get)(e.data.value[s],r)])||t.push({label:`${(0,n.get)(e.data.value[s],"displayName")} - ${(0,n.get)(e.data.value[s],r)}`,value:(0,n.get)(e.data.value[s],r)});return t}static parseWorkspacesForSelect(e){const t=[];if(!e)return t;const r="customerId";for(let s=0;s<e.data.value.length;s++)(0,n.find)(t,["value",(0,n.get)(e.data.value[s].properties,r)])||t.push({label:(0,n.get)(e.data.value[s],"name"),value:(0,n.get)(e.data.value[s].properties,r)});return t}}const p=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];if(0===t.length)return[];const r=t.reduce(((e,t)=>(e.add(t),e)),new Set);return e.filter((e=>r.has(e.value)))},m=e=>({value:e.value,label:e.text});const d="azuremonitor",f="loganalytics",g="resourcegraph";function h(e,t){if("string"==typeof e)return t.multi||t.includeAll&&!t.allValue?"'"+e+"'":e;if("number"==typeof e)return e;return(0,n.map)(e,(t=>"number"==typeof e?e:"'"+t+"'")).join(",")}let v,b;!function(e){e.AzureMonitor="Azure Monitor",e.LogAnalytics="Azure Log Analytics",e.AzureResourceGraph="Azure Resource Graph",e.GrafanaTemplateVariableFn="Grafana Template Variable Function"}(v||(v={})),function(e){e.Public="AzureCloud",e.China="AzureChinaCloud",e.USGovernment="AzureUSGovernment",e.Germany="AzureGermanCloud",e.None=""}(b||(b={}));const y=Symbol("Concealed client secret");function w(e){return e.jsonData.azureAuthType?e.jsonData.azureAuthType:e.jsonData.tenantId&&e.jsonData.clientId?"clientsecret":i.config.azure.managedIdentityEnabled?"msi":"clientsecret"}function S(){switch(i.config.azure.cloud){case b.Public:case b.None:case void 0:return"azuremonitor";case b.China:return"chinaazuremonitor";case b.USGovernment:return"govazuremonitor";case b.Germany:return"germanyazuremonitor";default:throw new Error(`The cloud '${i.config.azure.cloud}' not supported.`)}}function k(e){switch(e){case"azuremonitor":return"https://portal.azure.com";case"chinaazuremonitor":return"https://portal.azure.cn";case"govazuremonitor":return"https://portal.azure.us";case"germanyazuremonitor":return"https://portal.microsoftazure.de";default:throw new Error("The cloud not supported.")}}function M(e){switch(w(e)){case"msi":return S();case"clientsecret":return e.jsonData.cloudName||S()}}function A(e){if(e.secureJsonFields.clientSecret)return y;{var t;const r=null===(t=e.secureJsonData)||void 0===t?void 0:t.clientSecret;return"string"==typeof r&&r.length>0?r:void 0}}var j,z,x,N,C,I,D,G=r(45916);const{Input:T}=a.LegacyForms,L=[{value:"msi",label:"Managed Identity"},{value:"clientsecret",label:"App Registration"}],R=e=>{const{credentials:t,azureCloudOptions:r,onCredentialsChange:s,getSubscriptions:i,disabled:n}=e,c=function(e){switch(e.authType){case"msi":return!0;case"clientsecret":return!!(e.azureCloud&&e.tenantId&&e.clientId&&e.clientSecret)}}(t),[u,l]=(0,o.useState)([]),[p,m]=(0,o.useReducer)((e=>e+1),0);(0,o.useEffect)((()=>{if(!i||!c)return void d([]);let e=!1;return i().then((t=>{e||d(t,p)})),()=>{e=!0}}),[p]);const d=function(e){let r=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(l(e),i)if(r&&!t.defaultSubscriptionId&&e.length>0)f(e[0]);else if(t.defaultSubscriptionId){e.find((e=>e.value===t.defaultSubscriptionId))||f(void 0)}},f=e=>{if(s){const r=Object.assign({},t,{defaultSubscriptionId:null==e?void 0:e.value});s(r)}};return(0,G.jsxs)("div",{className:"gf-form-group",children:[e.managedIdentityEnabled&&(0,G.jsx)("div",{className:"gf-form-inline",children:(0,G.jsxs)("div",{className:"gf-form",children:[j||(j=(0,G.jsx)(a.InlineFormLabel,{className:"width-12",tooltip:"Choose the type of authentication to Azure services",children:"Authentication"})),(0,G.jsx)(a.Select,{className:"width-15",value:L.find((e=>e.value===t.authType)),options:L,onChange:e=>{if(s){l([]);const r=Object.assign({},t,{authType:e.value||"msi",defaultSubscriptionId:void 0});s(r)}},disabled:n})]})}),"clientsecret"===t.authType&&(0,G.jsxs)(G.Fragment,{children:[r&&(0,G.jsx)("div",{className:"gf-form-inline",children:(0,G.jsxs)("div",{className:"gf-form",children:[z||(z=(0,G.jsx)(a.InlineFormLabel,{className:"width-12",tooltip:"Choose an Azure Cloud",children:"Azure Cloud"})),(0,G.jsx)(a.Select,{"aria-label":"Azure Cloud",className:"width-15",value:r.find((e=>e.value===t.azureCloud)),options:r,onChange:e=>{if(s&&"clientsecret"===t.authType){l([]);const r=Object.assign({},t,{azureCloud:e.value,defaultSubscriptionId:void 0});s(r)}},disabled:n})]})}),(0,G.jsx)("div",{className:"gf-form-inline",children:(0,G.jsxs)("div",{className:"gf-form",children:[x||(x=(0,G.jsx)(a.InlineFormLabel,{className:"width-12",children:"Directory (tenant) ID"})),(0,G.jsx)("div",{className:"width-15",children:(0,G.jsx)(T,{className:"width-30",placeholder:"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",value:t.tenantId||"",onChange:e=>{if(s&&"clientsecret"===t.authType){l([]);const r=Object.assign({},t,{tenantId:e.target.value,defaultSubscriptionId:void 0});s(r)}},disabled:n})})]})}),(0,G.jsx)("div",{className:"gf-form-inline",children:(0,G.jsxs)("div",{className:"gf-form",children:[N||(N=(0,G.jsx)(a.InlineFormLabel,{className:"width-12",children:"Application (client) ID"})),(0,G.jsx)("div",{className:"width-15",children:(0,G.jsx)(T,{className:"width-30",placeholder:"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",value:t.clientId||"",onChange:e=>{if(s&&"clientsecret"===t.authType){l([]);const r=Object.assign({},t,{clientId:e.target.value,defaultSubscriptionId:void 0});s(r)}},disabled:n})})]})}),!n&&("symbol"==typeof t.clientSecret?(0,G.jsxs)("div",{className:"gf-form-inline",children:[C||(C=(0,G.jsxs)("div",{className:"gf-form",children:[(0,G.jsx)(a.InlineFormLabel,{className:"width-12",children:"Client Secret"}),(0,G.jsx)(T,{"data-testid":"client-secret",className:"width-25",placeholder:"configured",disabled:!0})]})),(0,G.jsx)("div",{className:"gf-form",children:(0,G.jsx)("div",{className:"max-width-30 gf-form-inline",children:(0,G.jsx)(a.Button,{variant:"secondary",type:"button",onClick:()=>{if(s&&"clientsecret"===t.authType){l([]);const e=Object.assign({},t,{clientSecret:"",defaultSubscriptionId:void 0});s(e)}},disabled:n,children:"reset"})})})]}):(0,G.jsx)("div",{className:"gf-form-inline",children:(0,G.jsxs)("div",{className:"gf-form",children:[I||(I=(0,G.jsx)(a.InlineFormLabel,{className:"width-12",children:"Client Secret"})),(0,G.jsx)("div",{className:"width-15",children:(0,G.jsx)(T,{className:"width-30",placeholder:"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",value:t.clientSecret||"",onChange:e=>{if(s&&"clientsecret"===t.authType){l([]);const r=Object.assign({},t,{clientSecret:e.target.value,defaultSubscriptionId:void 0});s(r)}},disabled:n})})]})}))]}),i&&(0,G.jsxs)(G.Fragment,{children:[(0,G.jsx)("div",{className:"gf-form-inline",children:(0,G.jsxs)("div",{className:"gf-form",children:[D||(D=(0,G.jsx)(a.InlineFormLabel,{className:"width-12",children:"Default Subscription"})),(0,G.jsx)("div",{className:"width-30",children:(0,G.jsx)(a.Select,{"aria-label":"Default Subscription",value:t.defaultSubscriptionId?u.find((e=>e.value===t.defaultSubscriptionId)):void 0,options:u,onChange:f,disabled:n})})]})}),!n&&(0,G.jsx)("div",{className:"gf-form-inline",children:(0,G.jsx)("div",{className:"gf-form",children:(0,G.jsx)("div",{className:"max-width-30 gf-form-inline",children:(0,G.jsx)(a.Button,{variant:"secondary",size:"sm",type:"button",onClick:m,disabled:!c,children:"Load Subscriptions"})})})})]}),e.children]})};var P;const O=[{value:"azuremonitor",label:"Azure"},{value:"govazuremonitor",label:"Azure US Government"},{value:"germanyazuremonitor",label:"Azure Germany"},{value:"chinaazuremonitor",label:"Azure China"}],q=e=>{const{updateOptions:t,getSubscriptions:r}=e,s=(0,o.useMemo)((()=>function(e){switch(w(e)){case"msi":return i.config.azure.managedIdentityEnabled?{authType:"msi",defaultSubscriptionId:e.jsonData.subscriptionId}:{authType:"clientsecret",azureCloud:S()};case"clientsecret":return{authType:"clientsecret",azureCloud:e.jsonData.cloudName||S(),tenantId:e.jsonData.tenantId,clientId:e.jsonData.clientId,clientSecret:A(e),defaultSubscriptionId:e.jsonData.subscriptionId}}}(e.options)),[e.options]);return(0,G.jsxs)(G.Fragment,{children:[P||(P=(0,G.jsx)("h3",{className:"page-heading",children:"Authentication"})),(0,G.jsx)(R,{managedIdentityEnabled:i.config.azure.managedIdentityEnabled,credentials:s,azureCloudOptions:O,onCredentialsChange:e=>{t((t=>function(e,t){switch(t.authType){case"msi":if(!i.config.azure.managedIdentityEnabled)throw new Error("Managed Identity authentication is not enabled in Grafana config.");return Object.assign({},e,{jsonData:Object.assign({},e.jsonData,{azureAuthType:"msi",subscriptionId:t.defaultSubscriptionId})});case"clientsecret":return Object.assign({},e,{jsonData:Object.assign({},e.jsonData,{azureAuthType:"clientsecret",cloudName:t.azureCloud||S(),tenantId:t.tenantId,clientId:t.clientId,subscriptionId:t.defaultSubscriptionId}),secureJsonData:Object.assign({},e.secureJsonData,{clientSecret:"string"==typeof t.clientSecret&&t.clientSecret.length>0?t.clientSecret:void 0}),secureJsonFields:Object.assign({},e.secureJsonFields,{clientSecret:"symbol"==typeof t.clientSecret})})}}(t,e)))},getSubscriptions:r,disabled:e.options.readOnly})]})};function E(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}class F extends o.PureComponent{constructor(e){super(e),E(this,"templateSrv",(0,i.getTemplateSrv)()),E(this,"baseURL",void 0),E(this,"updateOptions",(e=>{const t=e(this.props.options);this.props.onOptionsChange(t),this.setState({unsaved:!0})})),E(this,"saveOptions",(async()=>{this.state.unsaved&&(await(0,i.getBackendSrv)().put(`/api/datasources/${this.props.options.id}`,this.props.options).then((e=>{(0,s.updateDatasourcePluginOption)(this.props,"version",e.datasource.version)})),this.setState({unsaved:!1}))})),E(this,"getSubscriptions",(async()=>{await this.saveOptions();try{const e=await(0,i.getBackendSrv)().fetch({url:this.baseURL+"?api-version=2019-03-01",method:"GET"}).toPromise();return this.setState({error:void 0}),l.parseSubscriptionsForSelect(e)}catch(t){var e;return this.setState({error:{title:"Error requesting subscriptions",description:"Could not request subscriptions from Azure. Check your credentials and try again.",details:null==t||null===(e=t.data)||void 0===e?void 0:e.message}}),Promise.resolve([])}})),this.state={unsaved:!1},this.baseURL=`/api/datasources/${this.props.options.id}/resources/${d}/subscriptions`}render(){const{options:e}=this.props,{error:t}=this.state;return(0,G.jsxs)(G.Fragment,{children:[(0,G.jsx)(q,{options:e,updateOptions:this.updateOptions,getSubscriptions:this.getSubscriptions}),t&&(0,G.jsxs)(a.Alert,{severity:"error",title:t.title,children:[(0,G.jsx)("p",{children:t.description}),t.details&&(0,G.jsx)("details",{style:{whiteSpace:"pre-wrap"},children:t.details})]})]})}}var V=r(48427);function $(){const[e,t]=(0,o.useState)([]),r=(0,o.useCallback)(((e,r)=>{t((t=>{const s=[...t],o=t.findIndex((t=>{let[r]=t;return r===e}));return o>-1&&s.splice(o,1),r&&s.unshift([e,r]),s}))}),[]);return[(0,o.useMemo)((()=>{const t=e[0];return t&&(0,V.O)(t[1])}),[e]),r]}var Q=r(90747);const W=["labelWidth","inlineField"];const U=e=>{const{labelWidth:t,inlineField:r}=e,s=function(e,t){if(null==e)return{};var r,s,o={},i=Object.keys(e);for(s=0;s<i.length;s++)r=i[s],t.indexOf(r)>=0||(o[r]=e[r]);return o}(e,W);return r?(0,G.jsx)(a.InlineField,Object.assign({labelWidth:t||18},s)):(0,G.jsx)(Q.EditorField,Object.assign({width:t||18},s))},X=e=>{let{query:t,subscriptions:r,variableOptionGroup:s,onQueryChange:i,multiSelect:n=!1}=e;const c=(0,o.useCallback)((e=>{if(!e.value)return;let r=Object.assign({},t,{subscription:e.value});t.queryType===v.AzureMonitor&&(r.azureMonitor=Object.assign({},r.azureMonitor,{resourceGroup:void 0,metricDefinition:void 0,metricNamespace:void 0,resourceName:void 0,metricName:void 0,aggregation:void 0,timeGrain:"",dimensionFilters:[]})),i(r)}),[t,i]),u=(0,o.useCallback)((e=>{e&&(t.subscriptions=e.map((e=>{var t;return null!==(t=e.value)&&void 0!==t?t:""})),i(t))}),[t,i]),l=(0,o.useMemo)((()=>[...r,s]),[r,s]);return n?(0,G.jsx)(U,{label:"Subscriptions",children:(0,G.jsx)(a.MultiSelect,{isClearable:!0,value:p([...r,...s.options],t.subscriptions),inputId:"azure-monitor-subscriptions-field",onChange:u,options:l,width:38})}):(0,G.jsx)(U,{label:"Subscription",children:(0,G.jsx)(a.Select,{value:t.subscription,inputId:"azure-monitor-subscriptions-field",onChange:c,options:l,width:38,allowCustomValue:!0})})},B=e=>{var t,r;let{query:s,onQueryChange:i}=e;const n=(0,o.useCallback)((e=>{i(Object.assign({},s,{azureResourceGraph:Object.assign({},s.azureResourceGraph,{query:e})}))}),[i,s]);return(0,G.jsx)(a.CodeEditor,{value:null!==(t=null===(r=s.azureResourceGraph)||void 0===r?void 0:r.query)&&void 0!==t?t:"",language:"kusto",height:200,width:"100%",showMiniMap:!1,onBlur:n,onSave:n})},H="arg-subscriptions",_=e=>{let{query:t,datasource:r,subscriptionId:s,variableOptionGroup:i,onChange:a,setError:n}=e;const c=(0,o.useRef)(!1),[u,l]=(0,o.useState)([]);return(0,o.useEffect)((()=>{c.current||(c.current=!0,r.azureMonitorDatasource.getSubscriptions().then((e=>{var r;const s=e.map((e=>({label:e.text,value:e.value,description:e.value})));var o;(l(s),n(H,void 0),null!==(r=t.subscriptions)&&void 0!==r&&r.length||null==s||!s.length)||a(Object.assign({},t,{subscriptions:[null!==(o=t.subscription)&&void 0!==o?o:s[0].value]}))})).catch((e=>n(H,e))))}),[r,a,t,n]),(0,G.jsxs)("span",{"data-testid":"azure-monitor-arg-query-editor-with-experimental-ui",children:[(0,G.jsx)(Q.EditorRows,{children:(0,G.jsx)(Q.EditorRow,{children:(0,G.jsx)(Q.EditorFieldGroup,{children:(0,G.jsx)(X,{multiSelect:!0,subscriptions:u,query:t,datasource:r,subscriptionId:s,variableOptionGroup:i,onQueryChange:a,setError:n})})})}),(0,G.jsx)(B,{query:t,datasource:r,subscriptionId:s,variableOptionGroup:i,onQueryChange:a,setError:n})]})};var K=r(36636),J=r(37784);const Z=e=>{const t=(0,a.useTheme2)(),r=Y(t,e);return(0,G.jsx)("span",{className:(0,K.cx)(r.wrapper)})};Z.defaultProps={v:0,h:0,layout:"block"};const Y=(0,a.stylesFactory)(((e,t)=>{var r,s;return{wrapper:(0,K.css)([{paddingRight:e.spacing(null!==(r=t.h)&&void 0!==r?r:0),paddingBottom:e.spacing(null!==(s=t.v)&&void 0!==s?s:0)},"inline"===t.layout&&{display:"inline-block"},"block"===t.layout&&{display:"block"}])}}));let ee;var te,re,se,oe;!function(e){e.Subscription="Subscription",e.ResourceGroup="ResourceGroup",e.Resource="Resource",e.VariableGroup="TemplateVariableGroup",e.Variable="TemplateVariable"}(ee||(ee={}));const ie=e=>{let{isOpen:t,entry:{type:r}}=e;switch(r){case ee.Subscription:return te||(te=(0,G.jsx)(a.Icon,{name:"layer-group"}));case ee.ResourceGroup:return(0,G.jsx)(a.Icon,{name:t?"folder-open":"folder"});case ee.Resource:return re||(re=(0,G.jsx)(a.Icon,{name:"cube"}));case ee.VariableGroup:return se||(se=(0,G.jsx)(a.Icon,{name:"x"}));case ee.Variable:return oe||(oe=(0,G.jsx)(a.Icon,{name:"x"}));default:return null}},ae=e=>({table:(0,K.css)({width:"100%",tableLayout:"fixed"}),tableScroller:(0,K.css)({maxHeight:"50vh",overflow:"auto"}),header:(0,K.css)({background:e.colors.background.secondary}),row:(0,K.css)({borderBottom:`1px solid ${e.colors.border.weak}`,"&:last-of-type":{borderBottomColor:e.colors.border.medium}}),disabledRow:(0,K.css)({opacity:.5}),cell:(0,K.css)({padding:e.spacing(1,1,1,0),width:"25%",overflow:"hidden",textOverflow:"ellipsis","&:first-of-type":{width:"50%",padding:e.spacing(1,1,1,2)}}),collapseButton:(0,K.css)({margin:0}),loadingCell:(0,K.css)({textAlign:"center"}),spinner:(0,K.css)({marginBottom:0}),nestedEntry:(0,K.css)({display:"flex",alignItems:"center"}),entryContentItem:(0,K.css)({margin:e.spacing(0,1,0,0)}),truncated:(0,K.css)({minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}),resourceField:(0,K.css)({maxWidth:e.spacing(36),overflow:"hidden"}),resourceFieldButton:(0,K.css)({padding:"7px",textAlign:"left"}),nestedRowCheckbox:(0,K.css)({zIndex:0}),selectionFooter:(0,K.css)({position:"sticky",bottom:0,background:e.colors.background.primary,paddingTop:e.spacing(2)}),loadingWrapper:(0,K.css)({textAlign:"center",paddingTop:e.spacing(2),paddingBottom:e.spacing(2),color:e.colors.text.secondary}),resultLimit:(0,K.css)({margin:"4px 0",fontStyle:"italic"}),modal:(0,K.css)({width:e.breakpoints.values.lg})});var ne,ce,ue,le;const pe=e=>{let{entry:t,isSelected:r,isDisabled:s,isOpen:i,isSelectable:n,level:c,scrollIntoView:u,onToggleCollapse:l,onSelectedChange:p}=e;const m=(0,a.useTheme2)(),d=(0,a.useStyles2)(ae),f=!!t.children,g=(0,o.useCallback)((()=>{l(t)}),[l,t]),h=(0,o.useCallback)((e=>{const r=e.target.checked;p(t,r)}),[t,p]),v=`${u?"table":"summary"}_checkbox_${t.uri}`;return(0,o.useEffect)((()=>{var e;r&&u&&(null===(e=document.getElementById(v))||void 0===e||e.scrollIntoView({behavior:"smooth",block:"center"}))}),[]),(0,G.jsxs)("div",{className:d.nestedEntry,style:{marginLeft:c*(3*m.spacing.gridSize)},children:[f?(0,G.jsx)(a.IconButton,{className:d.collapseButton,name:i?"angle-down":"angle-right","aria-label":i?`Collapse ${t.name}`:`Expand ${t.name}`,onClick:g,id:t.id}):ne||(ne=(0,G.jsx)(Z,{layout:"inline",h:2})),ce||(ce=(0,G.jsx)(Z,{layout:"inline",h:2})),n&&(0,G.jsxs)(G.Fragment,{children:[(0,G.jsx)(a.Checkbox,{id:v,onChange:h,disabled:s,value:r,className:d.nestedRowCheckbox}),ue||(ue=(0,G.jsx)(Z,{layout:"inline",h:2}))]}),(0,G.jsx)(ie,{entry:t,isOpen:i}),le||(le=(0,G.jsx)(Z,{layout:"inline",h:1})),(0,G.jsx)("label",{htmlFor:v,className:(0,K.cx)(d.entryContentItem,d.truncated),children:t.name})]})};var me=r(75973);const de=/\/subscriptions\/(?<subscriptionID>[^/]+)(?:\/resourceGroups\/(?<resourceGroup>[^/]+)(?:\/providers.+\/(?<resource>[^/]+))?)?/;function fe(e){var t;const r=de.exec(e),s=null!==(t=null==r?void 0:r.groups)&&void 0!==t?t:{},{subscriptionID:o,resourceGroup:i,resource:a}=s;if(o)return{subscriptionID:o,resourceGroup:i,resource:a}}function ge(e){return!!e.match(/^[A-Z0-9]+/i)}function he(e,t){for(const r of e){if(r.uri.toLowerCase()===t.toLowerCase())return r;if(r.children){const e=he(r.children,t);if(e)return e}}}function ve(e,t,r){return(0,me.ZP)(e,(e=>{const s=he(e,t);s&&(s.children=r)}))}const be=e=>{var t;let{row:r,selectedRows:s,level:i,requestNestedRows:n,onRowSelectedChange:c,selectableEntryTypes:u,scrollIntoView:l}=e;const p=(0,a.useStyles2)(ae),[m,d]=(0,o.useState)("closed"),f=!!s.find((e=>e.uri===r.uri)),g=s.length>0&&!f,h="open"===m;return(0,o.useEffect)((()=>{var e;const t=s[0];t&&!!he(null!==(e=r.children)&&void 0!==e?e:[],t.uri)&&d("open")}),[s,r]),(0,G.jsxs)(G.Fragment,{children:[(0,G.jsxs)("tr",{className:(0,K.cx)(p.row,g&&p.disabledRow),children:[(0,G.jsx)("td",{className:p.cell,children:(0,G.jsx)(pe,{level:i,isSelected:f,isDisabled:g,isOpen:h,entry:r,onToggleCollapse:async()=>{"open"!==m?(d("loading"),n(r).then((()=>d("open"))).catch((()=>d("closed")))):d("closed")},onSelectedChange:c,isSelectable:u.some((e=>e===r.type)),scrollIntoView:l})}),(0,G.jsx)("td",{className:p.cell,children:r.typeLabel}),(0,G.jsx)("td",{className:p.cell,children:null!==(t=r.location)&&void 0!==t?t:"-"})]},r.id),h&&r.children&&Object.keys(r.children).length>0&&r.children.map((e=>(0,G.jsx)(be,{row:e,selectedRows:s,level:i+1,requestNestedRows:n,onRowSelectedChange:c,selectableEntryTypes:u,scrollIntoView:l},e.uri))),(0,G.jsx)(a.FadeTransition,{visible:"loading"===m,children:(0,G.jsx)("tr",{children:(0,G.jsx)("td",{className:(0,K.cx)(p.cell,p.loadingCell),colSpan:3,children:(0,G.jsx)(a.LoadingPlaceholder,{text:"Loading...",className:p.spinner})})})})]})},ye=be;var we;const Se=e=>{let{searchFn:t}=e;const[r,s]=(0,o.useState)(""),i=(0,o.useMemo)((()=>(0,n.debounce)(t,600)),[t]);return(0,o.useEffect)((()=>()=>{i.cancel()}),[i]),(0,G.jsx)(a.Input,{"aria-label":"resource search",prefix:we||(we=(0,G.jsx)(a.Icon,{name:"search"})),value:r,onChange:e=>{const t=e.currentTarget.value;s(t),i(t)},placeholder:"search for a resource"})};var ke,Me,Ae,je,ze,xe,Ne,Ce,Ie;const De=e=>{let{resourcePickerData:t,resourceURI:r,onApply:s,onCancel:i,selectableEntryTypes:n,queryType:c}=e;const u=(0,a.useStyles2)(ae),[l,p]=(0,o.useState)(!1),[m,d]=(0,o.useState)([]),[f,g]=(0,o.useState)([]),[h,v]=(0,o.useState)(r),[b,y]=(0,o.useState)(void 0),[w,S]=(0,o.useState)(null==r?void 0:r.includes("$")),[k,M]=(0,o.useState)(!1);(0,o.useEffect)((()=>{v(r)}),[r]);const A=(0,o.useCallback)((async()=>{if(!l){try{p(!0);const e=await t.fetchInitialRows(c,h||"");d(e)}catch(e){y((0,V.Z)(e))}p(!1)}}),[h,l,t,c]);(0,J.Z)((()=>{A()})),(0,o.useEffect)((()=>{h||g([]);const e=h&&he(m,h);if(e)return g([Object.assign({},e,{children:void 0})])}),[h,m]);const j=(0,o.useCallback)((async e=>{var r;if(y(void 0),null===(r=e.children)||void 0===r||!r.length)try{const r=await t.fetchAndAppendNestedRow(m,e,c);d(r)}catch(e){throw y((0,V.Z)(e)),e}}),[t,m,c]),z=(0,o.useCallback)(((e,t)=>{v(t?e.uri:void 0)}),[]),x=(0,o.useCallback)((()=>{s(h)}),[h,s]),N=(0,o.useCallback)((async e=>{if(y(void 0),M(!1),e){try{p(!0);const r=await t.search(e,c);d(r),r.length>=t.resultLimit&&M(!0)}catch(e){y((0,V.Z)(e))}p(!1)}else A()}),[A,t,c]);return(0,G.jsxs)("div",{children:[(0,G.jsx)(Se,{searchFn:N}),k?(0,G.jsxs)("p",{className:u.resultLimit,children:["Showing first ",t.resultLimit," results"]}):ke||(ke=(0,G.jsx)(Z,{v:2})),(0,G.jsx)("table",{className:u.table,children:(0,G.jsx)("thead",{children:(0,G.jsxs)("tr",{className:(0,K.cx)(u.row,u.header),children:[(0,G.jsx)("td",{className:u.cell,children:"Scope"}),(0,G.jsx)("td",{className:u.cell,children:"Type"}),(0,G.jsx)("td",{className:u.cell,children:"Location"})]})})}),(0,G.jsx)("div",{className:u.tableScroller,children:(0,G.jsx)("table",{className:u.table,children:(0,G.jsxs)("tbody",{children:[l&&(0,G.jsx)("tr",{className:(0,K.cx)(u.row),children:(0,G.jsx)("td",{className:u.cell,children:Me||(Me=(0,G.jsx)(a.LoadingPlaceholder,{text:"Loading..."}))})}),!l&&0===m.length&&(0,G.jsx)("tr",{className:(0,K.cx)(u.row),children:(0,G.jsx)("td",{className:u.cell,"aria-live":"polite",children:"No resources found"})}),!l&&m.map((e=>(0,G.jsx)(ye,{row:e,selectedRows:f,level:0,requestNestedRows:j,onRowSelectedChange:z,selectableEntryTypes:n,scrollIntoView:!0},e.uri)))]})})}),(0,G.jsxs)("div",{className:u.selectionFooter,children:[f.length>0&&(0,G.jsxs)(G.Fragment,{children:[Ae||(Ae=(0,G.jsx)("h5",{children:"Selection"})),(0,G.jsx)("div",{className:u.tableScroller,children:(0,G.jsx)("table",{className:u.table,children:(0,G.jsx)("tbody",{children:f.map((e=>(0,G.jsx)(ye,{row:e,selectedRows:f,level:0,requestNestedRows:j,onRowSelectedChange:z,selectableEntryTypes:n},e.uri)))})})}),je||(je=(0,G.jsx)(Z,{v:2}))]}),(0,G.jsxs)(a.Collapse,{collapsible:!0,label:"Advanced",isOpen:w,onToggle:()=>S(!w),children:[(0,G.jsx)(a.Label,{htmlFor:`input-${h}`,children:ze||(ze=(0,G.jsxs)("h6",{children:["Resource URI"," ",(0,G.jsx)(a.Tooltip,{content:(0,G.jsxs)(G.Fragment,{children:["Manually edit the"," ",(0,G.jsxs)("a",{href:"https://docs.microsoft.com/en-us/azure/azure-monitor/logs/log-standard-columns#_resourceid",rel:"noopener noreferrer",target:"_blank",children:["resource uri."," "]}),"Supports the use of multiple template variables (ex: /subscriptions/$subId/resourceGroups/$rg)"]}),placement:"right",interactive:!0,children:(0,G.jsx)(a.Icon,{name:"info-circle"})})]}))}),(0,G.jsx)(a.Input,{id:`input-${h}`,value:h,onChange:e=>v(e.currentTarget.value),placeholder:"ex: /subscriptions/$subId"}),xe||(xe=(0,G.jsx)(Z,{v:2}))]}),Ne||(Ne=(0,G.jsx)(Z,{v:2})),(0,G.jsx)(a.Button,{disabled:!!b,onClick:x,children:"Apply"}),Ce||(Ce=(0,G.jsx)(Z,{layout:"inline",h:1})),(0,G.jsx)(a.Button,{onClick:i,variant:"secondary",children:"Cancel"})]}),b&&(0,G.jsxs)(G.Fragment,{children:[Ie||(Ie=(0,G.jsx)(Z,{v:2})),(0,G.jsx)(a.Alert,{severity:"error",title:"An error occurred while requesting resources from Azure Monitor",children:b})]})]})};var Ge,Te,Le,Re;function Pe(e){const t=fe(e);if(t)return{subscriptionName:t.subscriptionID,resourceGroupName:t.resourceGroup,resourceName:t.resource}}const Oe=e=>{let{resource:t,datasource:r}=e;const[s,i]=(0,o.useState)(Pe(null!=t?t:""));return(0,o.useEffect)((()=>{t&&Pe(t)?r.resourcePickerData.getResourceURIDisplayProperties(t).then(i):i(void 0)}),[r.resourcePickerData,t]),t?s?(0,G.jsx)(qe,{resource:s}):t.startsWith("$")?(0,G.jsxs)("span",{children:[Ge||(Ge=(0,G.jsx)(a.Icon,{name:"x"}))," ",t]}):(0,G.jsx)(G.Fragment,{children:t}):(0,G.jsx)(G.Fragment,{children:"Select a resource"})},qe=e=>{let{resource:t}=e;const r=(0,a.useStyles2)(ae);return t.resourceName?(0,G.jsxs)("span",{className:(0,K.cx)(r.truncated,r.resourceField),children:[Te||(Te=(0,G.jsx)(a.Icon,{name:"cube"}))," ",t.resourceName]}):t.resourceGroupName?(0,G.jsxs)("span",{children:[Le||(Le=(0,G.jsx)(a.Icon,{name:"folder"}))," ",t.resourceGroupName]}):(0,G.jsxs)("span",{children:[Re||(Re=(0,G.jsx)(a.Icon,{name:"layer-group"}))," ",t.subscriptionName]})},Ee=e=>{let{query:t,datasource:r,onQueryChange:s,setResource:i,selectableEntryTypes:n,queryType:c,resourceUri:u,inlineField:l,labelWidth:p}=e;const m=(0,a.useStyles2)(ae),[d,f]=(0,o.useState)(!1),g=(0,o.useCallback)((()=>{f(!0)}),[]),h=(0,o.useCallback)((()=>{f(!1)}),[]),v=(0,o.useCallback)((e=>{s(i(t,e)),h()}),[h,s,t,i]);return(0,G.jsxs)(G.Fragment,{children:[(0,G.jsx)(a.Modal,{className:m.modal,title:"Select a resource",isOpen:d,onDismiss:h,trapFocus:!1,children:(0,G.jsx)(De,{resourcePickerData:r.resourcePickerData,resourceURI:u,onApply:v,onCancel:h,selectableEntryTypes:n,queryType:c})}),(0,G.jsx)(U,{label:"Resource",inlineField:l,labelWidth:p,children:(0,G.jsx)(a.Button,{className:m.resourceFieldButton,variant:"secondary",onClick:g,type:"button",children:(0,G.jsx)(Oe,{resource:u,datasource:r})})})]})};function Fe(e,t){return Object.assign({},e,{azureLogAnalytics:Object.assign({},e.azureLogAnalytics,{query:t})})}function Ve(e,t){return Object.assign({},e,{azureLogAnalytics:Object.assign({},e.azureLogAnalytics,{resource:t})})}const $e=[{label:"Time series",value:"time_series"},{label:"Table",value:"table"}],Qe=e=>{var t;let{query:r,variableOptionGroup:s,onQueryChange:i}=e;const n=(0,o.useMemo)((()=>[...$e,s]),[s]),c=(0,o.useCallback)((e=>{const{value:t}=e;if(!t)return;const s=function(e,t){return Object.assign({},e,{azureLogAnalytics:Object.assign({},e.azureLogAnalytics,{resultFormat:t})})}(r,t);i(s)}),[i,r]);return(0,G.jsx)(U,{label:"Format as",children:(0,G.jsx)(a.Select,{inputId:"azure-monitor-logs-workspaces-field",value:null===(t=r.azureLogAnalytics)||void 0===t?void 0:t.resultFormat,onChange:c,options:n,width:38})})};function We(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}class Ue{constructor(){We(this,"resolve",void 0),We(this,"reject",void 0),We(this,"promise",void 0),this.resolve=void 0,this.reject=void 0,this.promise=new Promise(((e,t)=>{this.resolve=e,this.reject=t})),Object.freeze(this)}}const Xe=e=>{var t,r,s;let{query:i,datasource:n,onQueryChange:c}=e;const u=(0,o.useRef)();(0,o.useEffect)((()=>{var e;if(null===(e=i.azureLogAnalytics)||void 0===e||!e.resource)return;const t=[n.azureLogAnalyticsDatasource.getKustoSchema(i.azureLogAnalytics.resource),(u.current||(u.current=new Ue),u.current.promise)];Promise.all(t).then((e=>{let[t,{monaco:r,editor:s}]=e;r.languages.kusto.getKustoWorker().then((e=>{const t=s.getModel();return t&&e(t.uri)})).then((e=>{null==e||e.setSchema(t,"https://help.kusto.windows.net","Samples")}))}))}),[n.azureLogAnalyticsDatasource,null===(t=i.azureLogAnalytics)||void 0===t?void 0:t.resource]);const l=(0,o.useCallback)(((e,t)=>{var r,s;null===(r=u.current)||void 0===r||null===(s=r.resolve)||void 0===s||s.call(r,{editor:e,monaco:t})}),[]),p=(0,o.useCallback)((e=>{c(Fe(i,e))}),[c,i]);return(0,G.jsx)(a.CodeEditor,{value:null!==(r=null===(s=i.azureLogAnalytics)||void 0===s?void 0:s.query)&&void 0!==r?r:"",language:"kusto",height:200,width:"100%",showMiniMap:!1,onBlur:p,onSave:p,onEditorDidMount:l})};function Be(e,t,r){const[s,i]=(0,o.useState)();return(0,o.useEffect)((()=>{(async function(e,t,r){var s;if(void 0!==(null===(s=t.azureLogAnalytics)||void 0===s?void 0:s.workspace)&&!t.azureLogAnalytics.resource){let s;s=ge(t.azureLogAnalytics.workspace)?await e.resourcePickerData.getResourceURIFromWorkspace(t.azureLogAnalytics.workspace):t.azureLogAnalytics.workspace;const o=Object.assign({},t,{azureLogAnalytics:Object.assign({},t.azureLogAnalytics,{resource:s,workspace:void 0})});delete o.azureLogAnalytics.workspace,r(o)}})(e,t,r).catch((e=>i({title:"Unable to migrate workspace as a resource",message:e.message})))}),[e,t,r]),s}const He=e=>{var t;let{query:r,datasource:s,subscriptionId:o,variableOptionGroup:i,onChange:n,setError:c,hideFormatAs:u}=e;const l=Be(s,r,n);return(0,G.jsx)("span",{"data-testid":"azure-monitor-logs-query-editor-with-experimental-ui",children:(0,G.jsxs)(Q.EditorRows,{children:[(0,G.jsx)(Q.EditorRow,{children:(0,G.jsx)(Q.EditorFieldGroup,{children:(0,G.jsx)(Ee,{query:r,datasource:s,inlineField:!0,labelWidth:10,subscriptionId:o,variableOptionGroup:i,onQueryChange:n,setError:c,selectableEntryTypes:[ee.Subscription,ee.ResourceGroup,ee.Resource,ee.Variable],setResource:Ve,resourceUri:null===(t=r.azureLogAnalytics)||void 0===t?void 0:t.resource,queryType:"logs"})})}),(0,G.jsx)(Xe,{query:r,datasource:s,subscriptionId:o,variableOptionGroup:i,onQueryChange:n,setError:c}),(0,G.jsx)(Q.EditorRow,{children:(0,G.jsxs)(Q.EditorFieldGroup,{children:[!u&&(0,G.jsx)(Qe,{query:r,datasource:s,subscriptionId:o,variableOptionGroup:i,onQueryChange:n,setError:c}),l&&(0,G.jsx)(a.Alert,{title:l.title,children:l.message})]})})]})})};function _e(e,t){return Object.assign({},e,{azureMonitor:Object.assign({},e.azureMonitor,{resourceUri:t,metricNamespace:void 0,metricName:void 0,aggregation:void 0,metricDefinition:void 0,timeGrain:"",dimensionFilters:[]})})}function Ke(e,t){var r,s;if((null===(r=e.azureMonitor)||void 0===r?void 0:r.metricNamespace)===t)return e;let o=null===(s=e.azureMonitor)||void 0===s?void 0:s.resourceUri;if(o&&null!=t&&t.includes("Microsoft.Storage/storageAccounts")){const e=o.split("/"),r=e.findIndex((e=>"storageAccounts"===e))+1,s=e.slice(0,r+1).join("/");if("Microsoft.Storage/storageAccounts"===t)o=s;else{o=`${s}/${t.split("/")[2]}/default`}}return Object.assign({},e,{azureMonitor:Object.assign({},e.azureMonitor,{metricNamespace:t,metricName:void 0,aggregation:void 0,timeGrain:"",dimensionFilters:[],resourceUri:o})})}function Je(e,t){var r;return(null===(r=e.azureMonitor)||void 0===r?void 0:r.timeGrain)===t?e:Object.assign({},e,{azureMonitor:Object.assign({},e.azureMonitor,{timeGrain:t})})}function Ze(e,t){var r;return(null===(r=e.azureMonitor)||void 0===r?void 0:r.dimensionFilters)===t?e:Object.assign({},e,{azureMonitor:Object.assign({},e.azureMonitor,{dimensionFilters:t})})}const Ye=e=>{var t;let{query:r,variableOptionGroup:s,onQueryChange:i,aggregationOptions:n,isLoading:c}=e;const u=(0,o.useCallback)((e=>{if(!e.value)return;const t=function(e,t){var r;return(null===(r=e.azureMonitor)||void 0===r?void 0:r.aggregation)===t?e:Object.assign({},e,{azureMonitor:Object.assign({},e.azureMonitor,{aggregation:t})})}(r,e.value);i(t)}),[i,r]),l=(0,o.useMemo)((()=>[...n,s]),[n,s]);return(0,G.jsx)(U,{label:"Aggregation",children:(0,G.jsx)(a.Select,{inputId:"azure-monitor-metrics-aggregation-field",value:null===(t=r.azureMonitor)||void 0===t?void 0:t.aggregation,onChange:u,options:l,isLoading:c})})},et=e=>{var t;let{data:r,query:s,dimensionOptions:i,onQueryChange:n}=e;const c=(0,o.useMemo)((()=>{var e,t;return null!==(e=null===(t=s.azureMonitor)||void 0===t?void 0:t.dimensionFilters)&&void 0!==e?e:[]}),[null===(t=s.azureMonitor)||void 0===t?void 0:t.dimensionFilters]),u=((e,t)=>{const[r,s]=(0,o.useState)({});return(0,o.useEffect)((()=>{var r;let o={};if(null!=e&&null!==(r=e.series)&&void 0!==r&&r.length){const r=e.series.flat().filter((e=>e.refId===t.refId)).flatMap((e=>e.fields)).map((e=>e.labels)).flat().filter((e=>null!=e));for(const e of r)for(const[t,r]of Object.entries(e))o[t]?o[t].add(r):o[t]=new Set([r])}s((e=>{const t={},r=Object.keys(o);if(0===r.length)return e;for(const s of r)e[s]&&o[s].size<e[s].size?t[s]=e[s]:t[s]=o[s];return t}))}),[null==e?void 0:e.series,t.refId]),r})(r,s),l=[{label:"==",value:"eq"},{label:"!=",value:"ne"},{label:"starts with",value:"sw"}],p=(0,o.useMemo)((()=>{let e=i;return c.length&&(e=i.filter((e=>!c.some((t=>t.dimension===e.value))))),e}),[c,i]),m=(e,t,r,s)=>{t[e]=r,s(t)},d=(e,t)=>{var r;const s=Array.from(null!==(r=u[t.toLowerCase()])&&void 0!==r?r:[]);return s.find((t=>t===e))?s.map((e=>({value:e,label:e}))):[...s,...e&&"*"!==e?[e]:[]].map((e=>({value:e,label:e})))},f=(e,t)=>{const r=d(void 0,t);if(e)for(const t of e)r.find((e=>e.value===t))||r.push({value:t,label:t});return r};return(0,G.jsx)(U,{label:"Dimensions",children:(0,G.jsx)(Q.EditorList,{items:c,onChange:e=>{const t=e.map((e=>{var t,r,s;return{dimension:null!==(t=e.dimension)&&void 0!==t?t:"",operator:null!==(r=e.operator)&&void 0!==r?r:"eq",filters:null!==(s=e.filters)&&void 0!==s?s:[]}}));n(Ze(s,t))},renderItem:(e,t,r)=>{var s,o,n,c;return(0,G.jsxs)(a.HorizontalGroup,{spacing:"none",children:[(0,G.jsx)(a.Select,{menuShouldPortal:!0,placeholder:"Field",value:e.dimension,options:(c=e.dimension||"",p.concat(i.filter((e=>e.value===c)))),onChange:r=>{var s;return m("dimension",e,null!==(s=r.value)&&void 0!==s?s:"",t)}}),(0,G.jsx)(a.Select,{menuShouldPortal:!0,placeholder:"Operation",value:e.operator,options:(n=e.operator||"eq",l.find((e=>e.value===n))?l:[...l,...n?[{label:n,value:n}]:[]]),onChange:r=>{var s;return m("operator",e,null!==(s=r.value)&&void 0!==s?s:"",t)},allowCustomValue:!0}),"eq"===e.operator||"ne"===e.operator?(0,G.jsx)(a.MultiSelect,{menuShouldPortal:!0,placeholder:"Select value(s)",value:e.filters,options:f(e.filters,null!==(s=e.dimension)&&void 0!==s?s:""),onChange:r=>m("filters",e,r.map((e=>{var t;return null!==(t=e.value)&&void 0!==t?t:""})),t),"aria-label":"dimension-labels-select",allowCustomValue:!0}):(0,G.jsx)(a.Select,{menuShouldPortal:!0,placeholder:"Select value",value:e.filters?e.filters[0]:"",allowCustomValue:!0,options:d(e.filters?e.filters[0]:"",null!==(o=e.dimension)&&void 0!==o?o:""),onChange:r=>{var s;return m("filters",e,[null!==(s=null==r?void 0:r.value)&&void 0!==s?s:""],t)},isClearable:!0}),(0,G.jsx)(Q.AccessoryButton,{"aria-label":"Remove",icon:"times",variant:"secondary",onClick:r,type:"button"})]})}})})},tt=e=>{var t,r;let{onQueryChange:s,query:i}=e;const[n,c]=(0,o.useState)(null!==(t=null===(r=i.azureMonitor)||void 0===r?void 0:r.alias)&&void 0!==t?t:""),u=(0,o.useCallback)((e=>{e.target instanceof HTMLInputElement&&c(e.target.value)}),[]),l=(0,o.useCallback)((()=>{const e=function(e,t){var r;return(null===(r=e.azureMonitor)||void 0===r?void 0:r.alias)===t?e:Object.assign({},e,{azureMonitor:Object.assign({},e.azureMonitor,{alias:t})})}(i,n);s(e)}),[s,i,n]);return(0,G.jsx)(U,{label:"Legend format",children:(0,G.jsx)(a.Input,{id:"azure-monitor-metrics-legend-field",placeholder:"Alias patterns",value:n,onChange:u,onBlur:l,width:38})})},rt=e=>{var t,r;let{metricNames:s,query:i,variableOptionGroup:n,onQueryChange:c}=e;const u=(0,o.useCallback)((e=>{if(!e.value)return;const t=function(e,t){var r;return(null===(r=e.azureMonitor)||void 0===r?void 0:r.metricName)===t?e:Object.assign({},e,{azureMonitor:Object.assign({},e.azureMonitor,{metricName:t,aggregation:void 0,timeGrain:"",dimensionFilters:[]})})}(i,e.value);c(t)}),[c,i]),l=(0,o.useMemo)((()=>[...s,n]),[s,n]);return(0,G.jsx)(U,{label:"Metric",children:(0,G.jsx)(a.Select,{inputId:"azure-monitor-metrics-metric-field",value:null!==(t=null===(r=i.azureMonitor)||void 0===r?void 0:r.metricName)&&void 0!==t?t:null,onChange:u,options:l,allowCustomValue:!0})})},st=e=>{var t,r;let{metricNamespaces:s,query:i,variableOptionGroup:n,onQueryChange:c}=e;const u=(0,o.useCallback)((e=>{if(!e.value)return;const t=Ke(i,e.value);c(t)}),[c,i]),l=(0,o.useMemo)((()=>[...s,n]),[s,n]),p=s.map((e=>e.value.toLowerCase())).concat(n.options.map((e=>e.value))),m=null===(t=i.azureMonitor)||void 0===t?void 0:t.metricNamespace;return m&&!p.includes(m.toLowerCase())&&l.push({label:m,value:m}),(0,G.jsx)(U,{label:"Metric namespace",children:(0,G.jsx)(a.Select,{inputId:"azure-monitor-metrics-metric-namespace-field",value:null===(r=i.azureMonitor)||void 0===r?void 0:r.metricNamespace,onChange:u,options:l,allowCustomValue:!0})})},ot=e=>{var t;let{query:r,timeGrainOptions:s,variableOptionGroup:i,onQueryChange:n}=e;const c=(0,o.useCallback)((e=>{if(!e.value)return;const t=Je(r,e.value);n(t)}),[n,r]),l=(0,o.useMemo)((()=>{const e=u.findClosestTimeGrain("1m",s.map((e=>u.createKbnUnitFromISO8601Duration(e.value)))||["1m","5m","15m","30m","1h","6h","12h","1d"]);return[...s.map((t=>"auto"===t.value?Object.assign({},t,{description:e}):t)),i]}),[s,i]);return(0,G.jsx)(U,{label:"Time grain",children:(0,G.jsx)(a.Select,{inputId:"azure-monitor-metrics-time-grain-field",value:null===(t=r.azureMonitor)||void 0===t?void 0:t.timeGrain,onChange:c,options:l})})},it=e=>{var t,r;let{onQueryChange:s,query:i}=e;const[n,c]=(0,o.useState)(null!==(t=null===(r=i.azureMonitor)||void 0===r?void 0:r.top)&&void 0!==t?t:""),u=(0,o.useCallback)((e=>{e.target instanceof HTMLInputElement&&c(e.target.value)}),[]),l=(0,o.useCallback)((()=>{const e=function(e,t){var r;return(null===(r=e.azureMonitor)||void 0===r?void 0:r.top)===t?e:Object.assign({},e,{azureMonitor:Object.assign({},e.azureMonitor,{top:t})})}(i,n);s(e)}),[s,i,n]);return(0,G.jsx)(U,{label:"Top",children:(0,G.jsx)(a.Input,{id:"azure-monitor-metrics-top-field",value:n,onChange:u,onBlur:l,width:16})})};function at(e,t,r){const[s]=(0,o.useState)((()=>Math.random())),[i,a]=(0,o.useState)(),n=(0,o.useMemo)((()=>null!=i?i:[]),[i]);return(0,o.useEffect)((()=>{e().then((e=>{a(e),t(s,void 0)})).catch((e=>{t(s,e)}))}),r),n}const nt={aggOptions:[],timeGrains:[],dimensions:[],isLoading:!1,supportedAggTypes:[],primaryAggType:void 0};function ct(e,t){const r=e.map(m);return t&&!r.find((e=>e.value===t.toLowerCase()))&&r.push({label:t,value:t}),r}const ut=e=>{var t,r,i,a;let{data:n,query:c,datasource:l,variableOptionGroup:p,onChange:m,setError:d}=e;const f=((e,t,r)=>{var i;const[a,n]=(0,o.useState)(nt),{resourceUri:c,metricNamespace:l,metricName:p,aggregation:m,timeGrain:d}=null!==(i=e.azureMonitor)&&void 0!==i?i:{};return(0,o.useEffect)((()=>{c&&l&&p?t.azureMonitorDatasource.getMetricMetadata({resourceUri:c,metricNamespace:l,metricName:p}).then((e=>{var t;const r=(e.supportedAggTypes||[e.primaryAggType]).map((e=>({label:e,value:e})));n({aggOptions:r,timeGrains:e.supportedTimeGrains,dimensions:e.dimensions,isLoading:!1,supportedAggTypes:null!==(t=e.supportedAggTypes)&&void 0!==t?t:[],primaryAggType:e.primaryAggType})})):n(nt)}),[t,c,l,p]),(0,o.useEffect)((()=>{const t=m||a.primaryAggType,o=d||"auto";t===m&&o===d||r(Object.assign({},e,{azureMonitor:Object.assign({},e.azureMonitor,{aggregation:t,timeGrain:o,allowedTimeGrainsMs:a.timeGrains.filter((e=>"auto"!==e.value)).map((e=>s.rangeUtil.intervalToMs(u.createKbnUnitFromISO8601Duration(e.value))))})}))}),[r,a,m,d,e]),a})(c,l,m),g=((e,t,r,s)=>{var o;const{metricNamespace:i,resourceUri:a}=null!==(o=e.azureMonitor)&&void 0!==o?o:{};return at((async()=>{if(!a)return;const s=ct(await t.azureMonitorDatasource.getMetricNamespaces({resourceUri:a}),i);return!i&&s.length&&r(Ke(e,s[0].value)),s}),s,[a])})(c,l,m,d),h=((e,t,r,s)=>{var o;const{metricNamespace:i,metricName:a,resourceUri:n}=null!==(o=e.azureMonitor)&&void 0!==o?o:{};return at((async()=>{if(i&&n)return ct(await t.azureMonitorDatasource.getMetricNames({resourceUri:n,metricNamespace:i}),a)}),s,[n,i])})(c,l,0,d);return(0,G.jsx)("span",{"data-testid":"azure-monitor-metrics-query-editor-with-experimental-ui",children:(0,G.jsxs)(Q.EditorRows,{children:[(0,G.jsx)(Q.EditorRow,{children:(0,G.jsxs)(Q.EditorFieldGroup,{children:[(0,G.jsx)(Ee,{query:c,datasource:l,variableOptionGroup:p,onQueryChange:m,setError:d,selectableEntryTypes:[ee.Resource],setResource:_e,resourceUri:null===(t=c.azureMonitor)||void 0===t?void 0:t.resourceUri,queryType:"metrics"}),(0,G.jsx)(st,{metricNamespaces:g,query:c,datasource:l,variableOptionGroup:p,onQueryChange:m,setError:d}),(0,G.jsx)(rt,{metricNames:h,query:c,datasource:l,variableOptionGroup:p,onQueryChange:m,setError:d}),(0,G.jsx)(Ye,{query:c,datasource:l,variableOptionGroup:p,onQueryChange:m,setError:d,aggregationOptions:null!==(r=null==f?void 0:f.aggOptions)&&void 0!==r?r:[],isLoading:f.isLoading}),(0,G.jsx)(ot,{query:c,datasource:l,variableOptionGroup:p,onQueryChange:m,setError:d,timeGrainOptions:null!==(i=null==f?void 0:f.timeGrains)&&void 0!==i?i:[]})]})}),(0,G.jsx)(Q.EditorRow,{children:(0,G.jsx)(Q.EditorFieldGroup,{children:(0,G.jsx)(et,{data:n,query:c,datasource:l,variableOptionGroup:p,onQueryChange:m,setError:d,dimensionOptions:null!==(a=null==f?void 0:f.dimensions)&&void 0!==a?a:[]})})}),(0,G.jsx)(Q.EditorRow,{children:(0,G.jsxs)(Q.EditorFieldGroup,{children:[(0,G.jsx)(it,{query:c,datasource:l,variableOptionGroup:p,onQueryChange:m,setError:d}),(0,G.jsx)(tt,{query:c,datasource:l,variableOptionGroup:p,onQueryChange:m,setError:d})]})})]})})},lt=e=>{let{query:t,onQueryChange:r}=e;const s=[{value:v.AzureMonitor,label:"Metrics"},{value:v.LogAnalytics,label:"Logs"},{value:v.AzureResourceGraph,label:"Azure Resource Graph"}],i=(0,o.useCallback)((e=>{e.value&&r(Object.assign({},t,{queryType:e.value}))}),[r,t]);return(0,G.jsx)("span",{"data-testid":"azure-monitor-experimental-header",children:(0,G.jsx)(Q.EditorHeader,{children:(0,G.jsx)(Q.InlineSelect,{label:"Service",value:t.queryType,placeholder:"Service...",allowCustomValue:!0,options:s,onChange:i})})})};var pt=r(10322),mt=r.n(pt);class dt{static buildResourceUri(e,t,r,s,o){const i=o.replace(r),a=r.split("/"),n=o.replace(s),c=s.split("/"),u=["/subscriptions",e,"resourceGroups",t,"providers",a.shift()];if(i.startsWith("Microsoft.Storage/storageAccounts/")&&!n.endsWith("default")&&c.push("default"),c.length>a.length){const e=c.shift();u.push(e)}for(const e in a)u.push(a[e]),u.push(c[e]);return u.join("/")}static buildAzureMonitorGetMetricNamespacesUrl(e,t,r,s){let o;if("resourceUri"in r)o=r.resourceUri;else{const{subscription:e,resourceGroup:t,metricDefinition:i,resourceName:a}=r;o=dt.buildResourceUri(e,t,i,a,s)}return`${e}${o}/providers/microsoft.insights/metricNamespaces?api-version=${t}`}static buildAzureMonitorGetMetricNamesUrl(e,t,r,s){let o;const{metricNamespace:i}=r;if("resourceUri"in r)o=r.resourceUri;else{const{subscription:e,resourceGroup:t,metricDefinition:i,resourceName:a}=r;o=dt.buildResourceUri(e,t,i,a,s)}return`${e}${o}/providers/microsoft.insights/metricdefinitions?api-version=${t}&metricnamespace=${encodeURIComponent(i)}`}}const ft="select";function gt(e,t,r){let s=e;return s=function(e){var t;let r=e;if(null!==(t=r.azureMonitor)&&void 0!==t&&t.timeGrainUnit&&"auto"!==r.azureMonitor.timeGrain){var s,o;r=Je(r,u.createISO8601Duration(null!==(s=r.azureMonitor.timeGrain)&&void 0!==s?s:"auto",r.azureMonitor.timeGrainUnit)),null===(o=r.azureMonitor)||void 0===o||delete o.timeGrainUnit}return r}(s),s=function(e){var t,r,s,o;let i=e;null!==(t=i.azureLogAnalytics)&&void 0!==t&&null!==(r=t.query)&&void 0!==r&&r.match(/\$__from\s/gi)&&(i=Fe(i,i.azureLogAnalytics.query.replace(/\$__from\s/gi,"$__timeFrom() ")));null!==(s=i.azureLogAnalytics)&&void 0!==s&&null!==(o=s.query)&&void 0!==o&&o.match(/\$__to\s/gi)&&(i=Fe(i,i.azureLogAnalytics.query.replace(/\$__to\s/gi,"$__timeTo() ")));return i}(s),s=function(e){var t,r;if((!(null===(t=e.azureMonitor)||void 0===t?void 0:t.metricNamespace)||e.azureMonitor.metricNamespace===ft)&&null!==(r=e.azureMonitor)&&void 0!==r&&r.metricDefinition)return Object.assign({},e,{azureMonitor:Object.assign({},e.azureMonitor,{metricNamespace:e.azureMonitor.metricDefinition})});return e}(s),s=ht(s),s=vt(s,t,r),s=bt(s),s}function ht(e){var t;let r=e;const s=null===(t=r.azureMonitor)||void 0===t?void 0:t.dimension;var o;s&&"None"!==s&&(r=function(e){var t,r;let s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"eq",i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[];const a=null!==(t=null===(r=e.azureMonitor)||void 0===r?void 0:r.dimensionFilters)&&void 0!==t?t:[];return Ze(e,[...a,{dimension:s,operator:o,filters:i}])}(r,s,"eq",[(null===(o=r.azureMonitor)||void 0===o?void 0:o.dimensionFilter)||""]));return r}function vt(e,t,r){const s=e.azureMonitor;if(!s||s.resourceUri)return e;const{subscription:i}=e,{resourceGroup:a,metricDefinition:n,resourceName:c}=s;if(!(i&&a&&n&&c))return e;if(n.split("/").some((e=>t.replace(e).split("/").length>2)))return r&&r("Resource URI migration",o.createElement("div",null,"Failed to create resource URI. Validate the metric definition template variable against supported cases ",o.createElement("a",{href:"https://grafana.com/docs/grafana/latest/datasources/azuremonitor/template-variables/"},"here."))),e;if(c.split("/").some((e=>t.replace(e).split("/").length>1)))return r&&r("Resource URI migration",o.createElement("div",null,"Failed to create resource URI. Validate the resource name template variable against supported cases ",o.createElement("a",{href:"https://grafana.com/docs/grafana/latest/datasources/azuremonitor/template-variables/"},"here."))),e;const u=dt.buildResourceUri(i,a,n,c,t);return Object.assign({},e,{azureMonitor:Object.assign({},s,{resourceUri:u})})}function bt(e){const t=e.azureMonitor;if(!t)return e;const r=[],s=t.dimensionFilters;return s&&s.length>0&&(s.forEach((e=>{const t={dimension:e.dimension,operator:e.operator};if(!e.filters&&e.filter)r.push(Object.assign({},t,{filters:[e.filter]}));else{let s=!1;if(e.filters&&e.filter){for(const t of e.filters)if(e.filter===t){s=!0;break}s||"*"===e.filter||e.filters.push(e.filter),r.push(Object.assign({},t,{filters:e.filters}))}}})),r.length>0)?Object.assign({},e,{azureMonitor:Object.assign({},t,{dimensionFilters:r})}):e}function yt(e,t){let r=e;return r.queryType||(r=Object.assign({},r,{queryType:v.AzureMonitor})),r.queryType===v.AzureMonitor&&r.azureMonitor&&(r=ht(r),r=vt(r,t),r=bt(r)),r}const wt={queryType:v.AzureMonitor},St=(e,t,r)=>{const s=(0,o.useMemo)((()=>((e,t)=>{const r=gt((0,n.defaults)({},e,wt),(0,i.getTemplateSrv)(),t);return mt()(r,e)?e:r})(e,r)),[e,r]);return(0,o.useEffect)((()=>{s!==e&&t(s)}),[s,e,t]),s};var kt,Mt;const At=e=>{let{data:t,subscriptionId:r,query:s,datasource:o,variableOptionGroup:i,onChange:n,setError:c}=e;switch(s.queryType){case v.AzureMonitor:return(0,G.jsx)(ut,{data:t,query:s,datasource:o,onChange:n,variableOptionGroup:i,setError:c});case v.LogAnalytics:return(0,G.jsx)(He,{subscriptionId:r,query:s,datasource:o,onChange:n,variableOptionGroup:i,setError:c});case v.AzureResourceGraph:return(0,G.jsx)(_,{subscriptionId:r,query:s,datasource:o,onChange:n,variableOptionGroup:i,setError:c});default:const e=s.queryType;return(0,G.jsx)(a.Alert,{title:"Unknown query type",children:("Application Insights"===e||"Insights Analytics"===e)&&(0,G.jsxs)(G.Fragment,{children:[e," was deprecated in Grafana 9. See the"," ",Mt||(Mt=(0,G.jsx)("a",{href:"https://grafana.com/docs/grafana/latest/datasources/azuremonitor/deprecated-application-insights/",target:"_blank",rel:"noreferrer",children:"deprecation notice"}))," ","to get more information about how to migrate your queries. This is the current query definition:",(0,G.jsx)(a.CodeEditor,{height:"200px",readOnly:!0,language:"json",value:JSON.stringify(s,null,4)})]})})}},jt=e=>{let{query:t,datasource:r,onChange:s,onRunQuery:i,data:c}=e;const[u,l]=$(),p=(0,o.useMemo)((()=>(0,n.debounce)(i,500)),[i]),m=(0,o.useCallback)((e=>{s(e),p()}),[s,p]),d=St(t,m,l),f=d.subscription||r.azureMonitorDatasource.defaultSubscriptionId,g={label:"Template Variables",options:r.getVariables().map((e=>({label:e,value:e})))};return(0,G.jsxs)("div",{"data-testid":"azure-monitor-query-editor",children:[(0,G.jsx)(lt,{query:d,onQueryChange:m}),(0,G.jsx)(At,{data:c,subscriptionId:f,query:d,datasource:r,onChange:m,variableOptionGroup:g,setError:l}),u&&(0,G.jsxs)(G.Fragment,{children:[kt||(kt=(0,G.jsx)(Z,{v:2})),(0,G.jsx)(a.Alert,{severity:"error",title:"An error occurred while requesting metadata from Azure Monitor",children:u})]})]})};var zt=r(88399),xt=r(2937),Nt=r(10010),Ct=r(7166),It=r(80890),Dt=r(44998);class Gt{constructor(e,t,r){this.rawQueryString=e,this.options=t,this.defaultTimeField=r}generate(){let e=this.rawQueryString;const t=/\$__([_a-zA-Z0-9]+)\(([^()]*)\)/gi;e=e.replace(t,((e,t,r)=>"contains"===t?this.getMultiContains(r):e)),e=e.replace(/\$__escapeMulti\(('[^]*')\)/gi,((e,t)=>this.escape(t))),this.options&&(e=e.replace(t,((e,t,r)=>"timeFilter"===t?this.getTimeFilter(r,this.options):"timeFrom"===t?this.getFrom(this.options):"timeTo"===t?this.getUntil(this.options):e)),e=e.replace(/\$__interval/gi,this.options.interval));const r=e;e=encodeURIComponent(e);return{uriString:`query=${e}`,rawQuery:r}}getFrom(e){const t=e.range.from;return`datetime(${(0,s.dateTime)(t).startOf("minute").toISOString()})`}getUntil(e){var t;if("now"===(null===(t=e.rangeRaw)||void 0===t?void 0:t.to)){const e=Date.now();return`datetime(${(0,s.dateTime)(e).startOf("minute").toISOString()})`}{const t=e.range.to;return`datetime(${(0,s.dateTime)(t).startOf("minute").toISOString()})`}}getTimeFilter(e,t){var r;const s=e||this.defaultTimeField;return"now"===(null===(r=t.rangeRaw)||void 0===r?void 0:r.to)?`${s} >= ${this.getFrom(t)}`:`${s} >= ${this.getFrom(t)} and ${s} <= ${this.getUntil(t)}`}getMultiContains(e){const t=e.indexOf(","),r=e.substring(0,t),s=e.substring(e.indexOf(",")+1);return s&&"all"===s.toLowerCase().trim()?"1 == 1":`${r.trim()} in (${s.trim()})`}escape(e){return e.substring(1,e.length-1).split("','").map((e=>`@'${e}'`)).join(", ")}}class Tt{constructor(e){this.results=e}parseQueryResult(){let e=[],t=[];for(let r=0;r<this.results.length;r++){if(0===this.results[r].result.tables.length)continue;t=this.results[r].result.tables[0].columns;const s=this.results[r].result.tables[0].rows;e="time_series"===this.results[r].query.resultFormat?(0,n.concat)(e,this.parseTimeSeriesResult(this.results[r].query,t,s)):(0,n.concat)(e,this.parseTableResult(this.results[r].query,t,s))}return e}parseTimeSeriesResult(e,t,r){const s=[];let o=-1,i=-1,a=-1;for(let e=0;e<t.length;e++)-1===o&&"datetime"===t[e].type&&(o=e),-1===i&&"string"===t[e].type&&(i=e),-1===a&&["int","long","real","double"].indexOf(t[e].type)>-1&&(a=e);if(-1===o)throw new Error("No datetime column found in the result. The Time Series format requires a time column.");return(0,n.forEach)(r,(r=>{const n=Tt.dateTimeToEpoch(r[o]),c=i>-1?r[i]:t[a].name,u=Tt.findOrCreateBucket(s,c);u.datapoints.push([r[a],n]),u.refId=e.refId,u.meta={executedQueryString:e.query}})),s}parseTableResult(e,t,r){return{type:"table",columns:(0,n.map)(t,(e=>({text:e.name,type:e.type}))),rows:r,refId:e.refId,meta:{executedQueryString:e.query}}}parseToVariables(){const e=this.parseQueryResult(),t=[];return(0,n.forEach)(e,(e=>{(0,n.forEach)((0,n.flattenDeep)(e.rows),(e=>{t.push({text:e,value:e})}))})),t}transformToAnnotations(e){const t=this.parseQueryResult(),r=[];return(0,n.forEach)(t,(t=>{let s=-1,o=-1,i=-1;for(let e=0;e<t.columns.length;e++)-1===s&&"datetime"===t.columns[e].type&&(s=e),-1===o&&"text"===t.columns[e].text.toLowerCase()&&(o=e),-1===i&&"tags"===t.columns[e].text.toLowerCase()&&(i=e);(0,n.forEach)(t.rows,(t=>{r.push({annotation:e.annotation,time:Math.floor(Tt.dateTimeToEpoch(t[s])),text:t[o]?t[o].toString():"",tags:t[i]?t[i].trim().split(/\s*,\s*/):[]})}))})),r}static findOrCreateBucket(e,t){let r=(0,n.find)(e,["target",t]);return r||(r={target:t,datapoints:[],refId:"",query:""},e.push(r)),r}static dateTimeToEpoch(e){return(0,s.dateTime)(e).valueOf()}static parseSubscriptions(e){const t=[];if(!e)return t;const r="subscriptionId";for(let s=0;s<e.value.length;s++)(0,n.find)(t,["value",(0,n.get)(e.value[s],r)])||t.push({text:`${(0,n.get)(e.value[s],"displayName")}`,value:(0,n.get)(e.value[s],r)});return t}}const Lt=/([\w\W]+):([\w]+)(?:\s?=\s?([\w\W]+))?/;function Rt(e){return e.functions?e.functions.map((e=>{const t=e.parameters&&e.parameters.split(", ").map((e=>{const t=e.match(Lt);if(!t)return;const[,r,s,o]=t;return{name:r,type:s,defaultValue:o,cslDefaultValue:o}})).filter((e=>!!e));return{name:e.name,body:e.body,inputParameters:t||[]}})):[]}function Pt(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}class Ot extends i.DataSourceWithBackend{constructor(e){super(e),Pt(this,"resourcePath",void 0),Pt(this,"azurePortalUrl",void 0),Pt(this,"defaultSubscriptionId",void 0),Pt(this,"azureMonitorPath",void 0),Pt(this,"firstWorkspace",void 0),Pt(this,"cache",void 0),this.instanceSettings=e,this.cache=new Map,this.resourcePath=`${f}`,this.azureMonitorPath=`${d}/subscriptions`;const t=M(e);this.azurePortalUrl=k(t),this.defaultSubscriptionId=this.instanceSettings.jsonData.subscriptionId||""}isConfigured(){return!this.validateDatasource()}filterQuery(e){var t;return!(!0===e.hide||null===(t=e.azureLogAnalytics)||void 0===t||!t.query||!e.azureLogAnalytics.resource&&!e.azureLogAnalytics.workspace)}async getSubscriptions(){if(!this.isConfigured())return[];const e=`${this.azureMonitorPath}?api-version=2019-03-01`;return await this.getResource(e).then((e=>Tt.parseSubscriptions(e)))}async getWorkspaces(e){const t=await this.getWorkspaceList(e);return(0,n.map)(t.value,(e=>({text:e.name,value:e.id})))||[]}getWorkspaceList(e){const t=(0,i.getTemplateSrv)().replace(e||this.defaultSubscriptionId),r=this.azureMonitorPath+`/${t}/providers/Microsoft.OperationalInsights/workspaces?api-version=2017-04-26-preview`;return this.getResource(r)}async getMetadata(e){const t=`${this.resourcePath}/v1${e}/metadata`;return await this.getResource(t)}async getKustoSchema(e){const t=(0,i.getTemplateSrv)(),r=t.replace(e,{},h);return function(e,t,r){const s={name:t,tables:e.tables,functions:Rt(e),majorVersion:0,minorVersion:0};return s.functions.push({name:"$__timeFilter",body:"{ true }",inputParameters:[{name:"timeColumn",type:"System.String",defaultValue:'""',cslDefaultValue:'""'}]},{name:"$__timeFrom",body:"{ datetime(2018-06-05T18:09:58.907Z) }",inputParameters:[]},{name:"$__timeTo",body:"{ datetime(2018-06-05T20:09:58.907Z) }",inputParameters:[]},{name:"$__escapeMulti",body:"{ @'\\grafana-vmNetwork(eth0)Total', @'\\hello!'}",inputParameters:[{name:"$myVar",type:"System.String",defaultValue:"$myVar",cslDefaultValue:"$myVar"}]},{name:"$__contains",body:"{ colName in ('value1','value2') }",inputParameters:[{name:"colName",type:"System.String",defaultValue:"colName",cslDefaultValue:"colName"},{name:"$myVar",type:"System.String",defaultValue:"$myVar",cslDefaultValue:"$myVar"}]}),{clusterType:"Engine",cluster:{connectionString:t,databases:[s]},database:s,globalParameters:r.map((e=>({name:`$${e.name}`,type:"dynamic"})))}}(await this.getMetadata(r),r,t.getVariables())}applyTemplateVariables(e,t){const r=e.azureLogAnalytics;if(!r)return e;const s=(0,i.getTemplateSrv)(),o=s.replace(r.resource,t);let a=s.replace(r.workspace,t);a||o||!this.firstWorkspace||(a=this.firstWorkspace);const n=s.replace(r.query,t,h);return{refId:e.refId,queryType:v.LogAnalytics,azureLogAnalytics:{resultFormat:r.resultFormat,query:n,resource:o,workspace:a}}}query(e){return super.query(e).pipe((0,Dt.z)((e=>(0,It.D)(this.processResponse(e)))))}async processResponse(e){if(e.data)for(const s of e.data){var t,r;const e=null===(t=s.meta)||void 0===t||null===(r=t.custom)||void 0===r?void 0:r.encodedQuery;if(e&&e.length>0){const e=await this.buildDeepLink(s.meta.custom);if(null!=e&&e.length)for(const t of s.fields)t.config.links=[{url:e,title:"View in Azure Portal",targetBlank:!0}]}}return e}async buildDeepLink(e){const t=encodeURIComponent(e.encodedQuery),r=e.workspace,s=e.subscription,o=await this.getWorkspaceDetails(r);if(!o.workspace||!o.resourceGroup)return"";return`${this.azurePortalUrl}/#blade/Microsoft_OperationsManagementSuite_Workspace/AnalyticsBlade/initiator/AnalyticsShareLinkToQuery/isQueryEditorVisible/true/scope/%7B%22resources%22%3A%5B%7B%22resourceId%22%3A%22%2Fsubscriptions%2F${s}%2Fresourcegroups%2F${o.resourceGroup}%2Fproviders%2Fmicrosoft.operationalinsights%2Fworkspaces%2F${o.workspace}%22%7D%5D%7D/query/${t}/isQueryBase64Compressed/true/timespanInIsoFormat/P1D`}async getWorkspaceDetails(e){if(!this.defaultSubscriptionId)return{};const t=(await this.getWorkspaceList(this.defaultSubscriptionId)).value.find((t=>t.properties.customerId===e));if(!t)return{};const r=/.*resourcegroups\/(.*)\/providers.*/.exec(t.id);return!r||r.length<2?{}:{workspace:t.name,resourceGroup:r[1]}}getDeprecatedDefaultWorkSpace(){return this.instanceSettings.jsonData.logAnalyticsDefaultWorkspace}buildQuery(e,t,r){const s=new Gt((0,i.getTemplateSrv)().replace(e,{},h),t,"TimeGenerated").generate().uriString,o=ge(r)?`${this.resourcePath}/v1/workspaces/${r}/query?${s}`:`${this.resourcePath}/v1${r}/query?${s}`;return[{datasource:this.getRef(),path:o,resultFormat:"table"}]}async getDefaultOrFirstSubscription(){var e;if(this.defaultSubscriptionId)return this.defaultSubscriptionId;return null===(e=(await this.getSubscriptions())[0])||void 0===e?void 0:e.value}async getFirstWorkspace(){var e;if(this.firstWorkspace)return this.firstWorkspace;const t=await this.getDefaultOrFirstSubscription();if(!t)return;const r=null===(e=(await this.getWorkspaces(t))[0])||void 0===e?void 0:e.value;return r&&(this.firstWorkspace=r),r}annotationQuery(e){if(!e.annotation.rawQuery)return Promise.reject({message:"Query missing in annotation definition"});const t=this.buildQuery(e.annotation.rawQuery,e,e.annotation.workspace),r=this.doQueries(t);return Promise.all(r).then((t=>new Tt(t).transformToAnnotations(e)))}doQueries(e){return(0,n.map)(e,(e=>this.getResource(e.path).then((t=>({result:t,query:e}))).catch((t=>{throw{error:t,query:e}}))))}async testDatasource(){const e=this.validateDatasource();if(e)return e;let t;try{const e=await this.getFirstWorkspace();if(!e)return{status:"error",message:"Workspace not found."};t=e}catch(e){let t="Azure Log Analytics requires access to Azure Monitor but had the following error: ";return{status:"error",message:this.getErrorMessage(t,e)}}try{const e=ge(t)?`${this.resourcePath}/v1/workspaces/${t}/metadata`:`${this.resourcePath}/v1${t}/metadata`;return await this.getResource(e).then((e=>({status:"success",message:"Successfully queried the Azure Log Analytics service.",title:"Success"})))}catch(e){let t="Azure Log Analytics: ";return{status:"error",message:this.getErrorMessage(t,e)}}}getErrorMessage(e,t){return e+=t.statusText?t.statusText+": ":"",t.data&&t.data.error&&t.data.error.code?e+=t.data.error.code+". "+t.data.error.message:t.data&&t.data.error?e+=t.data.error:t.data?e+=t.data:e+="Cannot connect to Azure Log Analytics REST API.",e}validateDatasource(){if("clientsecret"===w(this.instanceSettings)){if(!this.isValidConfigField(this.instanceSettings.jsonData.tenantId))return{status:"error",message:"The Tenant Id field is required."};if(!this.isValidConfigField(this.instanceSettings.jsonData.clientId))return{status:"error",message:"The Client Id field is required."}}}isValidConfigField(e){return"string"==typeof e&&e.length>0}}var qt=r(75478);const Et=[{location:"eastus",displayName:"East US",supportsLogs:!0},{location:"eastus2",displayName:"East US 2",supportsLogs:!0},{location:"southcentralus",displayName:"South Central US",supportsLogs:!0},{location:"westus2",displayName:"West US 2",supportsLogs:!0},{location:"westus3",displayName:"West US 3",supportsLogs:!0},{location:"australiaeast",displayName:"Australia East",supportsLogs:!0},{location:"southeastasia",displayName:"Southeast Asia",supportsLogs:!0},{location:"northeurope",displayName:"North Europe",supportsLogs:!0},{location:"uksouth",displayName:"UK South",supportsLogs:!0},{location:"westeurope",displayName:"West Europe",supportsLogs:!0},{location:"centralus",displayName:"Central US",supportsLogs:!0},{location:"northcentralus",displayName:"North Central US",supportsLogs:!0},{location:"westus",displayName:"West US",supportsLogs:!0},{location:"southafricanorth",displayName:"South Africa North",supportsLogs:!0},{location:"centralindia",displayName:"Central India",supportsLogs:!0},{location:"eastasia",displayName:"East Asia",supportsLogs:!0},{location:"japaneast",displayName:"Japan East",supportsLogs:!0},{location:"jioindiawest",displayName:"Jio India West",supportsLogs:!0},{location:"koreacentral",displayName:"Korea Central",supportsLogs:!0},{location:"canadacentral",displayName:"Canada Central",supportsLogs:!0},{location:"francecentral",displayName:"France Central",supportsLogs:!0},{location:"germanywestcentral",displayName:"Germany West Central",supportsLogs:!0},{location:"norwayeast",displayName:"Norway East",supportsLogs:!0},{location:"switzerlandnorth",displayName:"Switzerland North",supportsLogs:!0},{location:"uaenorth",displayName:"UAE North",supportsLogs:!0},{location:"brazilsouth",displayName:"Brazil South",supportsLogs:!0},{location:"centralusstage",displayName:"Central US (Stage)",supportsLogs:!0},{location:"eastusstage",displayName:"East US (Stage)",supportsLogs:!0},{location:"eastus2stage",displayName:"East US 2 (Stage)",supportsLogs:!0},{location:"northcentralusstage",displayName:"North Central US (Stage)",supportsLogs:!0},{location:"southcentralusstage",displayName:"South Central US (Stage)",supportsLogs:!0},{location:"westusstage",displayName:"West US (Stage)",supportsLogs:!0},{location:"westus2stage",displayName:"West US 2 (Stage)",supportsLogs:!0},{location:"asia",displayName:"Asia",supportsLogs:!0},{location:"asiapacific",displayName:"Asia Pacific",supportsLogs:!0},{location:"australia",displayName:"Australia",supportsLogs:!0},{location:"brazil",displayName:"Brazil",supportsLogs:!0},{location:"canada",displayName:"Canada",supportsLogs:!0},{location:"europe",displayName:"Europe",supportsLogs:!0},{location:"global",displayName:"Global",supportsLogs:!0},{location:"india",displayName:"India",supportsLogs:!0},{location:"japan",displayName:"Japan",supportsLogs:!0},{location:"uk",displayName:"United Kingdom",supportsLogs:!0},{location:"unitedstates",displayName:"United States",supportsLogs:!0},{location:"eastasiastage",displayName:"East Asia (Stage)",supportsLogs:!0},{location:"southeastasiastage",displayName:"Southeast Asia (Stage)",supportsLogs:!0},{location:"westcentralus",displayName:"West Central US",supportsLogs:!0},{location:"southafricawest",displayName:"South Africa West",supportsLogs:!0},{location:"australiacentral",displayName:"Australia Central",supportsLogs:!0},{location:"australiacentral2",displayName:"Australia Central 2",supportsLogs:!0},{location:"australiasoutheast",displayName:"Australia Southeast",supportsLogs:!0},{location:"japanwest",displayName:"Japan West",supportsLogs:!0},{location:"koreasouth",displayName:"Korea South",supportsLogs:!0},{location:"southindia",displayName:"South India",supportsLogs:!0},{location:"westindia",displayName:"West India",supportsLogs:!0},{location:"canadaeast",displayName:"Canada East",supportsLogs:!0},{location:"francesouth",displayName:"France South",supportsLogs:!0},{location:"germanynorth",displayName:"Germany North",supportsLogs:!0},{location:"norwaywest",displayName:"Norway West",supportsLogs:!0},{location:"switzerlandwest",displayName:"Switzerland West",supportsLogs:!0},{location:"ukwest",displayName:"UK West",supportsLogs:!0},{location:"uaecentral",displayName:"UAE Central",supportsLogs:!0},{location:"brazilsoutheast",displayName:"Brazil Southeast",supportsLogs:!0},{location:"chinaeast",displayName:"China Eest",supportsLogs:!0},{location:"chinaeast2",displayName:"China Eest 2",supportsLogs:!0},{location:"chinanorth",displayName:"China North",supportsLogs:!0},{location:"chinanorth2",displayName:"China North 2",supportsLogs:!0},{location:"chinanorth3",displayName:"China North 3",supportsLogs:!0}],Ft=Et.filter((e=>e.supportsLogs)).map((e=>`"${e.location}"`)).join(","),Vt=Et.reduce(((e,t)=>Object.assign({},e,{[t.location]:t.displayName})),{}),$t={"microsoft.recoveryservices/vaults/backupfabrics/protectioncontainers/protecteditems":"Backup Items","microsoft.resources/subscriptions":"Subscriptions","microsoft.resources/subscriptions/resourcegroups":"Resource groups","citrix.services/xenappessentials":"Citrix Virtual Apps Essentials","citrix.services/xendesktopessentials":"Citrix Virtual Desktops Essentials","dynatrace.observability/monitors":"Dynatrace","github.enterprise/accounts":"GitHub AE","microsoft.aad/domainservices":"Azure AD Domain Services","microsoft.aadiam/privatelinkforazuread":"Private Link for Azure AD","microsoft.agfoodplatform/farmbeats":"Azure FarmBeats","microsoft.analysisservices/servers":"Analysis Services","microsoft.anybuild/clusters":"AnyBuild clusters","microsoft.apimanagement/service":"API Management services","microsoft.appconfiguration/configurationstores":"App Configuration","microsoft.appplatform/spring":"Azure Spring Cloud","microsoft.attestation/attestationproviders":"Attestation providers","microsoft.authorization/resourcemanagementprivatelinks":"Resource management private links","microsoft.automation/automationaccounts":"Automation Accounts","microsoft.automation/automationaccounts/runbooks":"Runbook","microsoft.autonomoussystems/workspaces":"Bonsai","microsoft.avs/privateclouds":"AVS Private clouds","microsoft.azureactivedirectory/b2cdirectories":"B2C Tenants","microsoft.azureactivedirectory/guestusages":"Guest Usages","microsoft.azurearcdata/datacontrollers":"Azure Arc data controllers","microsoft.azurearcdata/postgresinstances":"Azure Arc-enabled PostgreSQL Hyperscale server groups","microsoft.azurearcdata/sqlmanagedinstances":"SQL managed instances - Azure Arc","microsoft.azurearcdata/sqlserverinstances":"SQL Server - Azure Arc","microsoft.azuredata/sqlserverregistrations":"SQL Server registries","microsoft.azurepercept/accounts":"Azure Percept accounts","microsoft.azurestackhci/clusters":"Azure Stack HCI","microsoft.azurestackhci/virtualmachines":"Azure Stack HCI virtual machine - Azure Arc","microsoft.baremetal/crayservers":"Cray Servers","microsoft.baremetal/monitoringservers":"Monitoring Servers","microsoft.baremetalinfrastructure/baremetalinstances":"BareMetal Instances","microsoft.batch/batchaccounts":"Batch accounts","microsoft.bing/accounts":"Bing Resources","microsoft.botservice/botservices":"Bot Services","microsoft.cache/redis":"Azure Cache for Redis","microsoft.cache/redisenterprise":"Redis Enterprise","microsoft.cdn/cdnwebapplicationfirewallpolicies":"Content Delivery Network WAF policies","microsoft.cdn/profiles (front doors standard/premium":"Preview)","microsoft.cdn/profiles/afdendpoints":"Endpoints","microsoft.cdn/profiles/endpoints":"Endpoints","microsoft.certificateregistration/certificateorders":"App Service Certificates","microsoft.chaos/chaosexperiments":"Chaos Experiments (Classic)","microsoft.chaos/experiments":"Chaos Experiments","microsoft.classiccompute/domainnames":"Cloud services (classic)","microsoft.classiccompute/virtualmachines":"Virtual machines (classic)","microsoft.classicnetwork/networksecuritygroups":"Network security groups (classic)","microsoft.classicnetwork/reservedips":"Reserved IP addresses (classic)","microsoft.classicnetwork/virtualnetworks":"Virtual networks (classic)","microsoft.classicstorage/storageaccounts":"Storage accounts (classic)","microsoft.cloudtest/accounts":"CloudTest Accounts","microsoft.cloudtest/hostedpools":"1ES Hosted Pools","microsoft.cloudtest/images":"CloudTest Images","microsoft.cloudtest/pools":"CloudTest Pools","microsoft.clusterstor/nodes":"ClusterStors","microsoft.cognitiveservices/accounts":"Cognitive Services","microsoft.compute/availabilitysets":"Availability sets","microsoft.compute/capacityreservationgroups":"Capacity Reservation Groups","microsoft.compute/cloudservices":"Cloud services (extended support)","microsoft.compute/diskaccesses":"Disk Accesses","microsoft.compute/diskencryptionsets":"Disk Encryption Sets","microsoft.compute/disks":"Disks","microsoft.compute/galleries":"Azure compute galleries","microsoft.compute/galleries/applications":"VM application definitions","microsoft.compute/galleries/applications/versions":"VM application versions","microsoft.compute/galleries/images":"VM image definitions","microsoft.compute/galleries/images/versions":"VM image versions","microsoft.compute/hostgroups":"Host groups","microsoft.compute/hostgroups/hosts":"Hosts","microsoft.compute/images":"Images","microsoft.compute/proximityplacementgroups":"Proximity placement groups","microsoft.compute/restorepointcollections":"Restore Point Collections","microsoft.compute/snapshots":"Snapshots","microsoft.compute/sshpublickeys":"SSH keys","microsoft.compute/virtualmachines":"Virtual machines","microsoft.compute/virtualmachinescalesets":"Virtual machine scale sets","microsoft.confidentialledger/ledgers":"Confidential Ledgers","microsoft.confluent/organizations":"Confluent organizations","microsoft.connectedcache/cachenodes":"Connected Cache Resources","microsoft.connectedcache/enterprisecustomers":"Connected Cache Resources","microsoft.connectedvehicle/platformaccounts":"Connected Vehicle Platforms","microsoft.connectedvmwarevsphere/vcenters":"VMware vCenters","microsoft.connectedvmwarevsphere/virtualmachines":"VMware + AVS virtual machines","microsoft.containerinstance/containergroups":"Container instances","microsoft.containerregistry/registries":"Container registries","microsoft.containerregistry/registries/replications":"Container registry replications","microsoft.containerregistry/registries/webhooks":"Container registry webhooks","microsoft.containerservice/managedclusters":"Kubernetes services","microsoft.dashboard/grafana":"Grafana Workspaces","microsoft.databox/jobs":"Azure Data Box","microsoft.databoxedge/databoxedgedevices":"Azure Stack Edge / Data Box Gateway","microsoft.databricks/workspaces":"Azure Databricks Services","microsoft.datacatalog/catalogs":"Data Catalog","microsoft.datacollaboration/workspaces":"Project CI","microsoft.datadog/monitors":"Datadog","microsoft.datafactory/datafactories":"Data factories","microsoft.datafactory/factories":"Data factories (V2)","microsoft.datalakeanalytics/accounts":"Data Lake Analytics","microsoft.datalakestore/accounts":"Data Lake Storage Gen1","microsoft.datamigration/services":"Azure Database Migration Services","microsoft.datamigration/services/projects":"Azure Database Migration Projects","microsoft.datamigration/sqlmigrationservices":"Azure Database Migration Services","microsoft.dataprotection/backupvaults":"Backup vaults","microsoft.dataprotection/resourceguards":"Resource Guards (Preview)","microsoft.datareplication/replicationvaults":"Site Recovery Vaults","microsoft.datashare/accounts":"Data Shares","microsoft.dbformariadb/servers":"Azure Database for MariaDB servers","microsoft.dbformysql/flexibleservers":"Azure Database for MySQL flexible servers","microsoft.dbformysql/servers":"Azure Database for MySQL servers","microsoft.dbforpostgresql/flexibleservers":"Azure Database for PostgreSQL flexible servers","microsoft.dbforpostgresql/servergroups":"Azure Database for PostgreSQL server groups","microsoft.dbforpostgresql/servergroupsv2":"Azure Database for PostgreSQL server groups","microsoft.dbforpostgresql/servers":"Azure Database for PostgreSQL servers","microsoft.dbforpostgresql/serversv2":"Azure Database for PostgreSQL servers v2","microsoft.deploymentmanager/rollouts":"Rollouts","microsoft.desktopvirtualization/applicationgroups":"Application groups","microsoft.desktopvirtualization/hostpools":"Host pools","microsoft.desktopvirtualization/scalingplans":"Scaling plans","microsoft.desktopvirtualization/workspaces":"Workspaces","microsoft.devices/iothubs":"IoT Hub","microsoft.devices/provisioningservices":"Device Provisioning Services","microsoft.deviceupdate/accounts":"Device Update for IoT Hubs","microsoft.devops/pipelines":"DevOps Starter","microsoft.devtestlab/labs":"DevTest Labs","microsoft.devtestlab/labs/virtualmachines":"Virtual machines","microsoft.digitaltwins/digitaltwinsinstances":"Azure Digital Twins","microsoft.documentdb/cassandraclusters":"Azure Managed Instance for Apache Cassandra","microsoft.documentdb/databaseaccounts":"Azure Cosmos DB accounts","microsoft.domainregistration/domains":"App Service Domains","microsoft.edgeorder/addresses":"Azure Edge Hardware Center Address","microsoft.edgeorder/orderitems":"Azure Edge Hardware Center","microsoft.elastic/monitors":"Elasticsearch (Elastic Cloud)","microsoft.eventgrid/domains":"Event Grid Domains","microsoft.eventgrid/partnernamespaces":"Event Grid Partner Namespaces","microsoft.eventgrid/partnerregistrations":"Event Grid Partner Registrations","microsoft.eventgrid/partnertopics":"Event Grid Partner Topics","microsoft.eventgrid/systemtopics":"Event Grid System Topics","microsoft.eventgrid/topics":"Event Grid Topics","microsoft.eventhub/clusters":"Event Hubs Clusters","microsoft.eventhub/namespaces":"Event Hubs Namespaces","microsoft.experimentation/experimentworkspaces":"Experiment Workspaces","microsoft.extendedlocation/customlocations":"Custom locations","microsoft.fidalgo/devcenters":"Fidalgo DevCenters","microsoft.fidalgo/networksettings":"Network Configurations","microsoft.fidalgo/projects":"Fidalgo Projects","microsoft.fidalgo/projects/environments":"Fidalgo Environments","microsoft.fluidrelay/fluidrelayservers":"Fluid Relay","microsoft.genomics/accounts":"Genomics accounts","microsoft.hanaonazure/hanainstances":"SAP HANA on Azure","microsoft.hanaonazure/sapmonitors":"Azure Monitors for SAP Solutions","microsoft.hdinsight/clusterpools":"HDInsight cluster pools","microsoft.hdinsight/clusterpools/clusters":"HDInsight gen2 clusters","microsoft.hdinsight/clusterpools/clusters/sessionclusters":"HDInsight session clusters","microsoft.hdinsight/clusters":"HDInsight clusters","microsoft.healthbot/healthbots":"Azure Health Bot","microsoft.healthcareapis/services":"Azure API for FHIR","microsoft.healthcareapis/workspaces":"Healthcare APIs Workspaces","microsoft.healthcareapis/workspaces/dicomservices":"DICOM services","microsoft.healthcareapis/workspaces/fhirservices":"FHIR services","microsoft.healthcareapis/workspaces/iotconnectors":"IoT connectors","microsoft.hpcworkbench/instances":"HPC Workbenches (preview)","microsoft.hpcworkbench/instances/chambers":"Chambers (preview)","microsoft.hpcworkbench/instances/chambers/accessprofiles":"Chamber Profiles (preview)","microsoft.hpcworkbench/instances/chambers/workloads":"Chamber VMs (preview)","microsoft.hpcworkbench/instances/consortiums":"Consortiums (preview)","microsoft.hybridcompute/machines":"Servers - Azure Arc","microsoft.hybridcompute/privatelinkscopes":"Azure Arc Private Link Scopes","microsoft.hybriddata/datamanagers":"StorSimple Data Managers","microsoft.hybridnetwork/devices":"Azure Network Function Manager – Devices","microsoft.hybridnetwork/networkfunctions":"Azure Network Function Manager – Network Functions","microsoft.importexport/jobs":"Import/export jobs","microsoft.insights/components":"Application Insights","microsoft.insights/datacollectionendpoints":"Data collection endpoints","microsoft.insights/datacollectionrules":"Data collection rules","microsoft.insights/privatelinkscopes":"Azure Monitor Private Link Scopes","microsoft.insights/webtests":"Availability tests","microsoft.insights/workbooks":"Azure Workbooks","microsoft.insights/workbooktemplates":"Azure Workbook Templates","microsoft.iotcentral/iotapps":"IoT Central Applications","microsoft.keyvault/vaults":"Key vaults","microsoft.kubernetes/connectedclusters":"Kubernetes - Azure Arc","microsoft.kusto/clusters":"Azure Data Explorer Clusters","microsoft.kusto/clusters/databases":"Azure Data Explorer Databases","microsoft.labservices/labaccounts":"Lab accounts","microsoft.labservices/labplans":"Lab plans","microsoft.labservices/labs":"Labs","microsoft.loadtestservice/loadtests":"Azure Load Testing","microsoft.logic/integrationaccounts":"Integration accounts","microsoft.logic/integrationserviceenvironments":"Integration Service Environments","microsoft.logic/integrationserviceenvironments/managedapis":"Managed Connector","microsoft.logic/workflows":"Logic apps","microsoft.logz/monitors":"Logz main account","microsoft.logz/monitors/accounts":"Logz sub account","microsoft.logz/monitors/metricssource":"Logz metrics data source","microsoft.machinelearning/commitmentplans":"Machine Learning Studio (classic) web service plans","microsoft.machinelearning/webservices":"Machine Learning Studio (classic) web services","microsoft.machinelearning/workspaces":"Machine Learning Studio (classic) workspaces","microsoft.machinelearningservices/workspaces":"Machine learning","microsoft.machinelearningservices/workspaces/onlineendpoints":"Machine learning online endpoints","microsoft.machinelearningservices/workspaces/onlineendpoints/deployments":"Machine learning online deployments","microsoft.maintenance/maintenanceconfigurations":"Maintenance Configurations","microsoft.managedidentity/userassignedidentities":"Managed Identities","microsoft.maps/accounts":"Azure Maps Accounts","microsoft.maps/accounts/creators":"Azure Maps Creator Resources","microsoft.media/mediaservices":"Media Services","microsoft.media/mediaservices/liveevents":"Live events","microsoft.media/mediaservices/streamingendpoints":"Streaming Endpoints","microsoft.media/videoanalyzers":"Video Analyzers","microsoft.migrate/projects":"Migration projects","microsoft.mixedreality/objectanchorsaccounts":"Object Anchors Accounts","microsoft.mixedreality/objectunderstandingaccounts":"Object Understanding Accounts","microsoft.mixedreality/remoterenderingaccounts":"Remote Rendering Accounts","microsoft.mixedreality/spatialanchorsaccounts":"Spatial Anchors Accounts","microsoft.mobilenetwork/mobilenetworks":"Mobile Networks","microsoft.mobilenetwork/mobilenetworks/datanetworks":"Data Networks","microsoft.mobilenetwork/mobilenetworks/services":"Services","microsoft.mobilenetwork/mobilenetworks/simpolicies":"Sim Policies","microsoft.mobilenetwork/mobilenetworks/sites":"Mobile Network Sites","microsoft.mobilenetwork/mobilenetworks/slices":"Slices","microsoft.mobilenetwork/packetcorecontrolplanes":"Packet Core Control Planes","microsoft.mobilenetwork/packetcorecontrolplanes/packetcoredataplanes":"Packet Core Data Planes","microsoft.mobilenetwork/packetcorecontrolplanes/packetcoredataplanes/attacheddatanetworks":"Attached Data Networks","microsoft.mobilenetwork/sims":"Sims","microsoft.netapp/netappaccounts":"NetApp accounts","microsoft.netapp/netappaccounts/capacitypools":"Capacity pools","microsoft.netapp/netappaccounts/capacitypools/volumes":"Volumes","microsoft.netapp/netappaccounts/capacitypools/volumes/snapshots":"Snapshots","microsoft.netapp/netappaccounts/snapshotpolicies":"Snapshot policies","microsoft.network/applicationgateways":"Application gateways","microsoft.network/applicationgatewaywebapplicationfirewallpolicies":"Application Gateway WAF policies","microsoft.network/applicationsecuritygroups":"Application security groups","microsoft.network/azurefirewalls":"Firewalls","microsoft.network/bastionhosts":"Bastions","microsoft.network/connections":"Connections","microsoft.network/customipprefixes":"Custom IP Prefixes","microsoft.network/ddosprotectionplans":"DDoS protection plans","microsoft.network/dnsforwardingrulesets":"Dns Forwarding Rulesets","microsoft.network/dnsresolvers":"DNS Private Resolvers","microsoft.network/dnszones":"DNS zones","microsoft.network/expressroutecircuits":"ExpressRoute circuits","microsoft.network/expressrouteports":"ExpressRoute Direct","microsoft.network/firewallpolicies":"Firewall Policies","microsoft.network/frontdoors":"Front Doors","microsoft.network/frontdoorwebapplicationfirewallpolicies":"Web Application Firewall policies (WAF)","microsoft.network/ipgroups":"IP Groups","microsoft.network/loadbalancers":"Load balancers","microsoft.network/localnetworkgateways":"Local network gateways","microsoft.network/natgateways":"NAT gateways","microsoft.network/networkexperimentprofiles":"Internet Analyzer profiles","microsoft.network/networkinterfaces":"Network interfaces","microsoft.network/networkmanagers":"Network Managers","microsoft.network/networksecuritygroups":"Network security groups","microsoft.network/networkwatchers":"Network Watchers","microsoft.network/networkwatchers/flowlogs":"NSG Flow Logs","microsoft.network/privatednszones":"Private DNS zones","microsoft.network/privateendpoints":"Private endpoints","microsoft.network/privatelinkservices":"Private link services","microsoft.network/publicipaddresses":"Public IP addresses","microsoft.network/publicipprefixes":"Public IP Prefixes","microsoft.network/routefilters":"Route filters","microsoft.network/routetables":"Route tables","microsoft.network/serviceendpointpolicies":"Service endpoint policies","microsoft.network/trafficmanagerprofiles":"Traffic Manager profiles","microsoft.network/virtualnetworkgateways":"Virtual network gateways","microsoft.network/virtualnetworks":"Virtual networks","microsoft.network/virtualwans":"Virtual WANs","microsoft.notificationhubs/namespaces":"Notification Hub Namespaces","microsoft.notificationhubs/namespaces/notificationhubs":"Notification Hubs","microsoft.openenergyplatform/energyservices":"Project Oak Forest","microsoft.openlogisticsplatform/workspaces":"Open Supply Chain Platform","microsoft.operationalinsights/querypacks":"Log Analytics query packs","microsoft.operationalinsights/workspaces":"Log Analytics workspaces","microsoft.operationsmanagement/solutions":"Solutions","microsoft.orbital/contactprofiles":"Contact Profiles","microsoft.orbital/edgesites":"Edge Sites","microsoft.orbital/groundstations":"Ground Stations","microsoft.orbital/l2connections":"L2 Connections","microsoft.orbital/spacecrafts":"Spacecrafts","microsoft.peering/peerings":"Peerings","microsoft.peering/peeringservices":"Peering Services","microsoft.playfab/playeraccountpools":"PlayFab player account pools","microsoft.playfab/titles":"PlayFab titles","microsoft.portal/dashboards":"Shared dashboards","microsoft.powerbidedicated/capacities":"Power BI Embedded","microsoft.purview/accounts":"Microsoft Purview accounts","microsoft.quantum/workspaces":"Quantum Workspaces","microsoft.recommendationsservice/accounts":"Intelligent Recommendations Accounts","microsoft.recommendationsservice/accounts/modeling":"Modeling","microsoft.recommendationsservice/accounts/serviceendpoints":"Service Endpoints","microsoft.recoveryservices/vaults":"Recovery Services vaults","microsoft.redhatopenshift/openshiftclusters":"Azure Red Hat OpenShift","microsoft.relay/namespaces":"Relays","microsoft.resourceconnector/appliances":"Resource bridges","microsoft.resourcegraph/queries":"Resource Graph queries","microsoft.resources/deploymentscripts":"Deployment Scripts","microsoft.resources/templatespecs":"Template specs","microsoft.saas/applications":"Software as a Service (classic)","microsoft.saas/resources":"SaaS","microsoft.scom/managedinstances":"Aquila Instances","microsoft.scvmm/virtualmachines":"SCVMM virtual machine - Azure Arc","microsoft.scvmm/vmmservers":"SCVMM management servers","microsoft.search/searchservices":"Search services","microsoft.securitydetonation/chambers":"Security Detonation Chambers","microsoft.servicebus/namespaces":"Service Bus Namespaces","microsoft.servicefabric/clusters":"Service Fabric clusters","microsoft.servicefabric/managedclusters":"Service Fabric managed clusters","microsoft.serviceshub/connectors":"Services Hub Connectors","microsoft.signalrservice/signalr":"SignalR","microsoft.signalrservice/webpubsub":"Web PubSub Service","microsoft.solutions/applicationdefinitions":"Service catalog managed application definitions","microsoft.solutions/applications":"Managed applications","microsoft.sql/instancepools":"Instance pools","microsoft.sql/managedinstances":"SQL managed instances","microsoft.sql/managedinstances/databases":"Managed databases","microsoft.sql/servers":"SQL servers","microsoft.sql/servers/databases":"SQL databases","microsoft.sql/servers/elasticpools":"SQL elastic pools","microsoft.sql/servers/jobagents":"Elastic Job agents","microsoft.sql/virtualclusters":"Virtual clusters","microsoft.sqlvirtualmachine/sqlvirtualmachines":"SQL virtual machines","microsoft.storage/storageaccounts":"Storage accounts","microsoft.storagecache/amlfilesystems":"Lustre File Systems","microsoft.storagecache/caches":"HPC caches","microsoft.storagepool/diskpools":"Disk Pools","microsoft.storagesync/storagesyncservices":"Storage Sync Services","microsoft.storagesyncdev/storagesyncservices":"Storage Sync Services","microsoft.storagesyncint/storagesyncservices":"Storage Sync Services","microsoft.storsimple/managers":"StorSimple Device Managers","microsoft.streamanalytics/clusters":"Stream Analytics clusters","microsoft.streamanalytics/streamingjobs":"Stream Analytics jobs","microsoft.synapse/privatelinkhubs":"Azure Synapse Analytics (private link hubs)","microsoft.synapse/workspaces":"Azure Synapse Analytics","microsoft.synapse/workspaces/bigdatapools":"Apache Spark pools","microsoft.synapse/workspaces/kustopools":"Data Explorer pools (preview)","microsoft.synapse/workspaces/sqlpools":"Dedicated SQL pools","microsoft.testbase/testbaseaccounts":"Test Base Accounts","microsoft.testbase/testbaseaccounts/packages":"Test Base Packages","microsoft.timeseriesinsights/environments":"Time Series Insights environments","microsoft.timeseriesinsights/environments/eventsources":"Time Series Insights event sources","microsoft.timeseriesinsights/environments/referencedatasets":"Time Series Insights reference data sets","microsoft.videoindexer/accounts":"Video Analyzer for Media","microsoft.virtualmachineimages/imagetemplates":"Image Templates","microsoft.visualstudio/account":"Azure DevOps organizations","microsoft.visualstudio/account/project":"DevOps Starter","microsoft.vmwarecloudsimple/dedicatedcloudnodes":"CloudSimple Nodes","microsoft.vmwarecloudsimple/dedicatedcloudservices":"CloudSimple Services","microsoft.vmwarecloudsimple/virtualmachines":"CloudSimple Virtual Machines","microsoft.vsonline/plans":"Visual Studio Online Plans","microsoft.web/connectiongateways":"On-premises data gateways","microsoft.web/connections":"API Connections","microsoft.web/containerapps":"Container Apps","microsoft.web/customapis":"Logic Apps Custom Connector","microsoft.web/hostingenvironments":"App Service Environments","microsoft.web/kubeenvironments":"App Service Kubernetes Environments","microsoft.web/serverfarms":"App Service plans","microsoft.web/sites":"App Services","microsoft.web/sites/slots":"App Service (Slots)","microsoft.web/staticsites":"Static Web Apps","microsoft.windowsesu/multipleactivationkeys":"Windows Multiple Activation Keys","microsoft.windowsiot/deviceservices":"Windows 10 IoT Core Services","microsoft.workloads/monitors":"Azure Monitors for SAP Solutions (v2)","microsoft.workloads/phpworkloads":"Scalable WordPress on Linux","microsoft.workloads/sapvirtualinstances":"SAP Virtual Instances","microsoft.workloads/sapvirtualinstances/applicationinstances":"SAP app server instances","microsoft.workloads/sapvirtualinstances/centralinstances":"SAP central server instances","microsoft.workloads/sapvirtualinstances/databaseinstances":"SAP database server instances","nginx.nginxplus/nginxdeployments":"NGINX Deployment","providers.test/statefulibizaengines":"VLCentral Help","wandisco.fusion/fusiongroups":"LiveData Planes","wandisco.fusion/fusiongroups/azurezones":"Azure Zones","wandisco.fusion/fusiongroups/azurezones/plugins":"Plugins","wandisco.fusion/fusiongroups/hivereplicationrules":"Hive Replication Rules","wandisco.fusion/fusiongroups/managedonpremzones":"On-premises Zones","wandisco.fusion/fusiongroups/replicationrules":"Replication Rules","wandisco.fusion/migrators":"LiveData Migrators","wandisco.fusion/migrators/exclusiontemplates":"Exclusions","wandisco.fusion/migrators/livedatamigrations":"Migrations","wandisco.fusion/migrators/metadatamigrations":"Metadata Migrations","wandisco.fusion/migrators/metadatatargets":"Metadata Targets","wandisco.fusion/migrators/pathmappings":"Path Mappings","wandisco.fusion/migrators/targets":"Targets","microsoft.security/insights/classification":"Data Sensitivity Security Insights (Preview)","microsoft.security/locations/alerts":"Security Alerts"},Qt=["Microsoft.AAD/DomainServices","microsoft.aadiam/azureADMetrics","Microsoft.AnalysisServices/servers","Microsoft.ApiManagement/service","Microsoft.App/containerapps","Microsoft.AppConfiguration/configurationStores","Microsoft.AppPlatform/Spring","Microsoft.Automation/automationAccounts","microsoft.avs/privateClouds","Microsoft.Batch/batchAccounts","Microsoft.BatchAI/workspaces","microsoft.bing/accounts","Microsoft.Blockchain/blockchainMembers","microsoft.botservice/botservices","Microsoft.Cache/redis","Microsoft.Cache/redisEnterprise","Microsoft.Cdn/cdnwebapplicationfirewallpolicies","Microsoft.Cdn/profiles","Microsoft.ClassicCompute/domainNames/slots/roles","Microsoft.ClassicCompute/virtualMachines","Microsoft.ClassicStorage/storageAccounts","Microsoft.ClassicStorage/storageAccounts/blobServices","Microsoft.ClassicStorage/storageAccounts/fileServices","Microsoft.ClassicStorage/storageAccounts/queueServices","Microsoft.ClassicStorage/storageAccounts/tableServices","Microsoft.Cloudtest/hostedpools","Microsoft.Cloudtest/pools","Microsoft.ClusterStor/nodes","Microsoft.CognitiveServices/accounts","Microsoft.Communication/CommunicationServices","Microsoft.Compute/cloudServices","Microsoft.Compute/cloudServices/roles","microsoft.compute/disks","Microsoft.Compute/virtualMachines","Microsoft.Compute/virtualMachineScaleSets","Microsoft.Compute/virtualMachineScaleSets/virtualMachines","Microsoft.ConnectedCache/CacheNodes","Microsoft.ConnectedVehicle/platformAccounts","Microsoft.ContainerInstance/containerGroups","Microsoft.ContainerRegistry/registries","Microsoft.ContainerService/managedClusters","Microsoft.CustomProviders/resourceproviders","Microsoft.DataBoxEdge/dataBoxEdgeDevices","Microsoft.DataCollaboration/workspaces","Microsoft.DataFactory/datafactories","Microsoft.DataFactory/factories","Microsoft.DataLakeAnalytics/accounts","Microsoft.DataLakeStore/accounts","Microsoft.DataProtection/BackupVaults","Microsoft.DataShare/accounts","Microsoft.DBforMariaDB/servers","Microsoft.DBforMySQL/flexibleServers","Microsoft.DBforMySQL/servers","Microsoft.DBforPostgreSQL/flexibleServers","Microsoft.DBForPostgreSQL/serverGroupsv2","Microsoft.DBforPostgreSQL/servers","Microsoft.DBforPostgreSQL/serversv2","Microsoft.Devices/ElasticPools","Microsoft.Devices/ElasticPools/IotHubTenants","Microsoft.Devices/IotHubs","Microsoft.Devices/provisioningServices","Microsoft.DigitalTwins/digitalTwinsInstances","Microsoft.DocumentDB/cassandraClusters","Microsoft.DocumentDB/DatabaseAccounts","microsoft.edgezones/edgezones","Microsoft.EventGrid/domains","Microsoft.EventGrid/eventSubscriptions","Microsoft.EventGrid/extensionTopics","Microsoft.EventGrid/partnerNamespaces","Microsoft.EventGrid/partnerTopics","Microsoft.EventGrid/systemTopics","Microsoft.EventGrid/topics","Microsoft.EventHub/clusters","Microsoft.EventHub/Namespaces","Microsoft.HDInsight/clusters","Microsoft.HealthcareApis/services","Microsoft.HealthcareApis/workspaces/fhirservices","Microsoft.HealthcareApis/workspaces/iotconnectors","microsoft.hybridnetwork/networkfunctions","microsoft.hybridnetwork/virtualnetworkfunctions","microsoft.insights/autoscalesettings","Microsoft.Insights/Components","Microsoft.IoTCentral/IoTApps","microsoft.keyvault/managedhsms","Microsoft.KeyVault/vaults","microsoft.kubernetes/connectedClusters","Microsoft.Kusto/Clusters","Microsoft.Logic/integrationServiceEnvironments","Microsoft.Logic/Workflows","Microsoft.MachineLearningServices/workspaces","Microsoft.Maps/accounts","Microsoft.Media/mediaservices","Microsoft.Media/mediaservices/liveEvents","Microsoft.Media/mediaservices/streamingEndpoints","Microsoft.Media/videoanalyzers","Microsoft.MixedReality/remoteRenderingAccounts","Microsoft.MixedReality/spatialAnchorsAccounts","Microsoft.NetApp/netAppAccounts/capacityPools","Microsoft.NetApp/netAppAccounts/capacityPools/volumes","Microsoft.Network/applicationgateways","Microsoft.Network/azureFirewalls","microsoft.network/bastionHosts","Microsoft.Network/connections","Microsoft.Network/dnsForwardingRulesets","Microsoft.Network/dnsResolvers","Microsoft.Network/dnszones","Microsoft.Network/expressRouteCircuits","Microsoft.Network/expressRouteCircuits/peerings","Microsoft.Network/expressRouteGateways","Microsoft.Network/expressRoutePorts","Microsoft.Network/frontdoors","Microsoft.Network/loadBalancers","Microsoft.Network/natGateways","Microsoft.Network/networkInterfaces","Microsoft.Network/networkWatchers/connectionMonitors","microsoft.network/p2svpngateways","Microsoft.Network/privateDnsZones","Microsoft.Network/privateEndpoints","Microsoft.Network/privateLinkServices","Microsoft.Network/publicIPAddresses","Microsoft.Network/trafficManagerProfiles","Microsoft.Network/virtualHubs","microsoft.network/virtualnetworkgateways","Microsoft.Network/virtualNetworks","Microsoft.Network/virtualRouters","microsoft.network/vpngateways","Microsoft.NotificationHubs/Namespaces/NotificationHubs","Microsoft.OperationalInsights/workspaces","Microsoft.Peering/peerings","Microsoft.Peering/peeringServices","Microsoft.PowerBIDedicated/capacities","microsoft.purview/accounts","Microsoft.RecoveryServices/Vaults","Microsoft.Relay/namespaces","microsoft.resources/subscriptions","Microsoft.Search/searchServices","microsoft.securitydetonation/chambers","Microsoft.ServiceBus/Namespaces","Microsoft.SignalRService/SignalR","Microsoft.SignalRService/WebPubSub","Microsoft.Sql/managedInstances","Microsoft.Sql/servers/databases","Microsoft.Sql/servers/elasticPools","Microsoft.Storage/storageAccounts","Microsoft.Storage/storageAccounts/blobServices","Microsoft.Storage/storageAccounts/fileServices","Microsoft.Storage/storageAccounts/queueServices","Microsoft.Storage/storageAccounts/tableServices","Microsoft.StorageCache/caches","microsoft.storagesync/storageSyncServices","Microsoft.StreamAnalytics/streamingjobs","Microsoft.Synapse/workspaces","Microsoft.Synapse/workspaces/bigDataPools","Microsoft.Synapse/workspaces/kustoPools","Microsoft.Synapse/workspaces/sqlPools","Microsoft.TimeSeriesInsights/environments","Microsoft.TimeSeriesInsights/environments/eventsources","Microsoft.VMwareCloudSimple/virtualMachines","Microsoft.Web/connections","Microsoft.Web/containerapps","Microsoft.Web/hostingEnvironments","Microsoft.Web/hostingEnvironments/multiRolePools","Microsoft.Web/hostingEnvironments/workerPools","Microsoft.Web/serverfarms","Microsoft.Web/sites","Microsoft.Web/sites/slots","Microsoft.Web/staticSites","Wandisco.Fusion/migrators"];function Wt(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}const Ut="select";function Xt(e){return!(!e||e===Ut)}class Bt extends i.DataSourceWithBackend{constructor(e){super(e),Wt(this,"apiVersion","2018-01-01"),Wt(this,"apiPreviewVersion","2017-12-01-preview"),Wt(this,"listByResourceGroupApiVersion","2021-04-01"),Wt(this,"defaultSubscriptionId",void 0),Wt(this,"resourcePath",void 0),Wt(this,"azurePortalUrl",void 0),Wt(this,"timeSrv",void 0),Wt(this,"templateSrv",void 0),this.instanceSettings=e,this.timeSrv=(0,qt.$t)(),this.templateSrv=(0,i.getTemplateSrv)(),this.defaultSubscriptionId=e.jsonData.subscriptionId;const t=M(e);this.resourcePath=d,this.azurePortalUrl=k(t)}isConfigured(){return!this.validateDatasource()}filterQuery(e){var t,r,s,o,i,a;const n=!(null==e||null===(t=e.azureMonitor)||void 0===t||!t.resourceUri),c=Xt(null==e||null===(r=e.azureMonitor)||void 0===r?void 0:r.resourceGroup)&&Xt(null==e||null===(s=e.azureMonitor)||void 0===s?void 0:s.resourceName)&&Xt(null==e||null===(o=e.azureMonitor)||void 0===o?void 0:o.metricDefinition);return!(!0===e.hide||!n&&!c||!Xt(null==e||null===(i=e.azureMonitor)||void 0===i?void 0:i.metricName)||!Xt(null==e||null===(a=e.azureMonitor)||void 0===a?void 0:a.aggregation))}applyTemplateVariables(e,t){var r;const s=e.azureMonitor;if(!s)throw new Error("Query is not a valid Azure Monitor Metrics query");s.timeGrain&&s.timeGrainUnit&&"auto"!==s.timeGrain&&(s.timeGrain=u.createISO8601Duration(s.timeGrain,s.timeGrainUnit));const o=(0,i.getTemplateSrv)(),a=o.replace(s.resourceUri,t),n=o.replace(e.subscription||this.defaultSubscriptionId,t),c=o.replace(s.resourceGroup,t),l=o.replace(s.resourceName,t),p=o.replace(s.metricNamespace,t),m=o.replace(s.metricDefinition,t),d=o.replace((s.timeGrain||"").toString(),t),f=o.replace(s.aggregation,t),g=o.replace(s.top||"",t),h=(null!==(r=s.dimensionFilters)&&void 0!==r?r:[]).filter((e=>e.dimension&&"None"!==e.dimension)).map((e=>{var r;const s=null===(r=e.filters)||void 0===r?void 0:r.map((e=>o.replace(null!=e?e:"",t)));return{dimension:o.replace(e.dimension,t),operator:e.operator||"eq",filters:s||[]}}));return{refId:e.refId,subscription:n,queryType:v.AzureMonitor,azureMonitor:{resourceUri:a,resourceGroup:c,resourceName:l,metricDefinition:m,timeGrain:d,allowedTimeGrainsMs:s.allowedTimeGrainsMs,metricName:o.replace(s.metricName,t),metricNamespace:p&&p!==Ut?p:m,aggregation:f,dimensionFilters:h,top:g||"10",alias:s.alias}}}async getSubscriptions(){return this.isConfigured()?this.getResource(`${this.resourcePath}/subscriptions?api-version=2019-03-01`).then((e=>l.parseSubscriptions(e))):[]}getResourceGroups(e){return this.getResource(`${this.resourcePath}/subscriptions/${e}/resourceGroups?api-version=${this.listByResourceGroupApiVersion}`).then((e=>l.parseResponseValues(e,"name","name")))}getMetricDefinitions(e,t){return this.getResource(`${this.resourcePath}/subscriptions/${e}/resourceGroups/${t}/resources?api-version=${this.listByResourceGroupApiVersion}`).then((e=>l.parseResponseValues(e,"type","type"))).then((e=>e.filter((e=>{for(let t=0;t<Qt.length;t++)if(e.value.toLowerCase()===Qt[t].toLowerCase())return!0;return!1})))).then((e=>{let t=!1;for(let r=0;r<e.length;r++)if("Microsoft.Storage/storageAccounts"===e[r].value){t=!0;break}return t&&(e.push({text:"Microsoft.Storage/storageAccounts/blobServices",value:"Microsoft.Storage/storageAccounts/blobServices"}),e.push({text:"Microsoft.Storage/storageAccounts/fileServices",value:"Microsoft.Storage/storageAccounts/fileServices"}),e.push({text:"Microsoft.Storage/storageAccounts/tableServices",value:"Microsoft.Storage/storageAccounts/tableServices"}),e.push({text:"Microsoft.Storage/storageAccounts/queueServices",value:"Microsoft.Storage/storageAccounts/queueServices"})),e.map((e=>({value:e.value,text:$t[e.value.toLowerCase()]||e.value})))}))}getResourceNames(e,t,r,s){const o=(0,n.startsWith)(r,"Microsoft.Storage/storageAccounts/")?"Microsoft.Storage/storageAccounts":r;let i=`${this.resourcePath}/subscriptions/${e}/resourceGroups/${t}/resources?$filter=resourceType eq '${o}'&api-version=${this.listByResourceGroupApiVersion}`;return s&&(i+=`&$skiptoken=${s}`),this.getResource(i).then((async s=>{let o=[];if((0,n.startsWith)(r,"Microsoft.Storage/storageAccounts/")){o=l.parseResourceNames(s,"Microsoft.Storage/storageAccounts");for(let e=0;e<o.length;e++)o[e].text+="/default",o[e].value+="/default"}else o=l.parseResourceNames(s,r);if(s.nextLink){const i=new URL(s.nextLink).searchParams.get("$skiptoken");if(!i)throw Error("unable to request the next page of resources");const a=await this.getResourceNames(e,t,r,i);o=o.concat(a)}return o}))}getMetricNamespaces(e){const t=dt.buildAzureMonitorGetMetricNamespacesUrl(this.resourcePath,this.apiPreviewVersion,this.replaceTemplateVariables(e),this.templateSrv);return this.getResource(t).then((e=>l.parseResponseValues(e,"name","properties.metricNamespaceName"))).then((e=>{if(t.includes("Microsoft.Storage/storageAccounts")){const t=["Microsoft.Storage/storageAccounts","Microsoft.Storage/storageAccounts/blobServices","Microsoft.Storage/storageAccounts/fileServices","Microsoft.Storage/storageAccounts/tableServices","Microsoft.Storage/storageAccounts/queueServices"];for(const r of t)(0,n.find)(e,["value",r.toLowerCase()])||e.push({value:r,text:r})}return e}))}getMetricNames(e){const t=dt.buildAzureMonitorGetMetricNamesUrl(this.resourcePath,this.apiVersion,this.replaceTemplateVariables(e),this.templateSrv);return this.getResource(t).then((e=>l.parseResponseValues(e,"name.localizedValue","name.value")))}getMetricMetadata(e){const{metricName:t}=e,r=dt.buildAzureMonitorGetMetricNamesUrl(this.resourcePath,this.apiVersion,this.replaceTemplateVariables(e),this.templateSrv);return this.getResource(r).then((e=>l.parseMetadata(e,t)))}async testDatasource(){const e=this.validateDatasource();if(e)return Promise.resolve(e);try{const e=`${this.resourcePath}/subscriptions?api-version=2019-03-01`;return await this.getResource(e).then((e=>({status:"success",message:"Successfully queried the Azure Monitor service.",title:"Success"})))}catch(e){let t="Azure Monitor: ";return t+=e.statusText?e.statusText+": ":"",e.data&&e.data.error&&e.data.error.code?t+=e.data.error.code+". "+e.data.error.message:e.data&&e.data.error?t+=e.data.error:e.data?t+=e.data:t+="Cannot connect to Azure Monitor REST API.",{status:"error",message:t}}}validateDatasource(){if("clientsecret"===w(this.instanceSettings)){if(!this.isValidConfigField(this.instanceSettings.jsonData.tenantId))return{status:"error",message:"The Tenant Id field is required."};if(!this.isValidConfigField(this.instanceSettings.jsonData.clientId))return{status:"error",message:"The Client Id field is required."}}}isValidConfigField(e){return"string"==typeof e&&e.length>0}replaceTemplateVariables(e){const t=(0,i.getTemplateSrv)(),r=Object.assign({},e);return Object.keys(e).forEach((e=>{r[e]=t.replace(r[e])})),r}}class Ht extends i.DataSourceWithBackend{filterQuery(e){var t;return!(null===(t=e.azureResourceGraph)||void 0===t||!t.query)}applyTemplateVariables(e,t){const r=e.azureResourceGraph;if(!r)return e;const s=(0,i.getTemplateSrv)(),o=s.getVariables().map((e=>`$${e.name}`)),a=c().find(e.subscriptions,(e=>c().includes(o,e))),n=[...s.replace(a,t,(e=>e)).split(",").filter((e=>e.length>0)),...c().filter(e.subscriptions,(e=>!c().includes(o,e)))],u=s.replace(r.query,t,h);return{refId:e.refId,queryType:v.AzureResourceGraph,subscriptions:n,azureResourceGraph:{resultFormat:"table",query:u}}}}function _t(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}const Kt=["microsoft.aad/domainservices","microsoft.aadiam/azureadmetrics","microsoft.aadiam/tenants","microsoft.agfoodplatform/farmbeats","microsoft.analysisservices/servers","microsoft.apimanagement/service","microsoft.appconfiguration/configurationstores","microsoft.appplatform/spring","microsoft.attestation/attestationproviders","microsoft.automation/automationaccounts","microsoft.autonomousdevelopmentplatform/accounts","microsoft.autonomousdevelopmentplatform/datapools","microsoft.autonomousdevelopmentplatform/workspaces","microsoft.avs/privateclouds","microsoft.azurestackresourcemonitor/storageaccountmonitor","microsoft.batch/batchaccounts","microsoft.batchai/workspaces","microsoft.blockchain/blockchainmembers","microsoft.blockchain/cordamembers","microsoft.botservice/botservices","microsoft.cache/redis","microsoft.cache/redisenterprise","microsoft.cdn/cdnwebapplicationfirewallpolicies","microsoft.cdn/profiles","microsoft.cdn/profiles/endpoints","microsoft.classiccompute/domainnames","microsoft.classiccompute/virtualmachines","microsoft.classicnetwork/networksecuritygroups","microsoft.classicstorage/storageaccounts","microsoft.cognitiveservices/accounts","microsoft.communication/communicationservices","microsoft.compute/disks","microsoft.compute/virtualmachines","microsoft.compute/virtualmachinescalesets","microsoft.connectedcache/cachenodes","microsoft.connectedvehicle/platformaccounts","microsoft.containerinstance/containergroups","microsoft.containerregistry/registries","microsoft.containerservice/managedclusters","microsoft.customerinsights/hubs","microsoft.customproviders/resourceproviders","microsoft.d365customerinsights/instances","microsoft.dashboard/grafana","microsoft.databoxedge/databoxedgedevices","microsoft.databricks/workspaces","microsoft.datacollaboration/workspaces","microsoft.datafactory/datafactories","microsoft.datafactory/factories","microsoft.datalakeanalytics/accounts","microsoft.datalakestore/accounts","microsoft.datashare/accounts","microsoft.dbformariadb/servers","microsoft.dbformysql/flexibleservers","microsoft.dbformysql/servers","microsoft.dbforpostgresql/flexibleservers","microsoft.dbforpostgresql/servergroupsv2","microsoft.dbforpostgresql/servers","microsoft.dbforpostgresql/serversv2","microsoft.desktopvirtualization/applicationgroups","microsoft.desktopvirtualization/hostpools","microsoft.desktopvirtualization/scalingplans","microsoft.desktopvirtualization/workspaces","microsoft.devices/elasticpools/iothubtenants","microsoft.devices/iothubs","microsoft.devices/provisioningservices","microsoft.digitaltwins/digitaltwinsinstances","microsoft.documentdb/cassandraclusters","microsoft.documentdb/databaseaccounts","microsoft.eventgrid/domains","microsoft.eventgrid/partnernamespaces","microsoft.eventgrid/partnertopics","microsoft.eventgrid/systemtopics","microsoft.eventgrid/topics","microsoft.eventhub/clusters","microsoft.eventhub/namespaces","microsoft.experimentation/experimentworkspaces","microsoft.fabric.admin/fabriclocations","microsoft.hdinsight/clusters","microsoft.healthcareapis/services","microsoft.healthcareapis/workspaces/dicomservices","microsoft.healthcareapis/workspaces/fhirservices","microsoft.insights/autoscalesettings","microsoft.insights/components","microsoft.insights/qos","microsoft.iotcentral/iotapps","microsoft.keyvault/managedhsms","microsoft.keyvault/vaults","microsoft.kubernetes/connectedclusters","microsoft.kusto/clusters","microsoft.loadtestservice/loadtests","microsoft.logic/integrationaccounts","microsoft.logic/integrationserviceenvironments","microsoft.logic/workflows","microsoft.machinelearningservices/workspaces","microsoft.media/mediaservices","microsoft.media/mediaservices/liveevents","microsoft.media/mediaservices/streamingendpoints","microsoft.media/videoanalyzers","microsoft.netapp/netappaccounts/capacitypools","microsoft.netapp/netappaccounts/capacitypools/volumes","microsoft.network/applicationgateways","microsoft.network/azurefirewalls","microsoft.network/bastionhosts","microsoft.network/connections","microsoft.network/dnszones","microsoft.network/expressroutecircuits","microsoft.network/expressroutegateways","microsoft.network/expressrouteports","microsoft.network/frontdoors","microsoft.network/loadbalancers","microsoft.network/natgateways","microsoft.network/networkinterfaces","microsoft.network/networksecuritygroups","microsoft.network/networksecurityperimeters","microsoft.network/networkvirtualappliances","microsoft.network/networkwatchers","microsoft.network/networkwatchers/connectionmonitors","microsoft.network/p2svpngateways","microsoft.network/privateendpoints","microsoft.network/privatelinkservices","microsoft.network/publicipaddresses","microsoft.network/trafficmanagerprofiles","microsoft.network/virtualnetworkgateways","microsoft.network/virtualnetworks","microsoft.network/vpngateways","microsoft.networkfunction/azuretrafficcollectors","microsoft.notificationhubs/namespaces","microsoft.notificationhubs/namespaces/notificationhubs","microsoft.openlogisticsplatform/workspaces","microsoft.operationalinsights/workspaces","microsoft.operationsmanagement/solutions","microsoft.peering/peeringservices","microsoft.powerbi/tenants","microsoft.powerbi/tenants/workspaces","microsoft.powerbidedicated/capacities","microsoft.purview/accounts","microsoft.recoveryservices/vaults","microsoft.relay/namespaces","microsoft.resources/subscriptions","microsoft.resources/subscriptions/resourcegroups","microsoft.search/searchservices","microsoft.security/antimalwaresettings","microsoft.securityinsights/settings","microsoft.servicebus/namespaces","microsoft.signalrservice/signalr","microsoft.signalrservice/webpubsub","microsoft.singularity/accounts","microsoft.sql/managedinstances","microsoft.sql/managedinstances/databases","microsoft.sql/servers/databases","microsoft.sql/servers/elasticpools","microsoft.storage/storageaccounts","microsoft.storage/storageaccounts/blobservices","microsoft.storage/storageaccounts/fileservices","microsoft.storage/storageaccounts/queueservices","microsoft.storage/storageaccounts/tableservices","microsoft.storagecache/caches","microsoft.storagesync/storagesyncservices","microsoft.streamanalytics/streamingjobs","microsoft.synapse/workspaces","microsoft.synapse/workspaces/bigdatapools","microsoft.synapse/workspaces/kustopools","microsoft.synapse/workspaces/scopepools","microsoft.synapse/workspaces/sqlpools","microsoft.timeseriesinsights/environments","microsoft.timeseriesinsights/environments/eventsources","microsoft.videoindexer/accounts","microsoft.vmwarecloudsimple/virtualmachines","microsoft.web/hostingenvironments","microsoft.web/hostingenvironments/workerpools","microsoft.web/serverfarms","microsoft.web/sites","microsoft.web/sites/slots"].map((e=>`"${e}"`)).join(","),Jt=Qt.map((e=>`"${e.toLocaleLowerCase()}"`)).join(",");class Zt extends i.DataSourceWithBackend{constructor(e){super(e),_t(this,"resourcePath",void 0),_t(this,"resultLimit",200),_t(this,"search",(async(e,t)=>{let r="resources";"logs"===t&&(r+="\n | union resourcecontainers"),r+=`\n | where id contains "${e}"\n ${this.filterByType(t)}\n | order by tolower(name) asc\n | limit ${this.resultLimit}\n `;const{data:s}=await this.makeResourceGraphRequest(r);return s.map((e=>{const t=fe(e.id);if(!t||!(t.resource||t.resourceGroup||t.subscriptionID))throw new Error("unable to fetch resource details");let r=t.subscriptionID,s=ee.Subscription;return t.resource?(r=t.resource,s=ee.Resource):t.resourceGroup&&(r=t.resourceGroup,s=ee.ResourceGroup),{name:e.name,id:r,uri:e.id,resourceGroupName:e.resourceGroup,type:s,typeLabel:$t[e.type]||e.type,location:Vt[e.location]||e.location}}))})),_t(this,"filterByType",(e=>"logs"===e?`| where type in (${Kt})`:`| where type in (${Jt})`)),this.resourcePath=`${g}`}async fetchInitialRows(e,t){const r=await this.getSubscriptions();if(!t)return r;let s=r;const o=fe(t);if(o){const t=`/subscriptions/${o.subscriptionID}/resourceGroups/${o.resourceGroup}`;if(o.resourceGroup){const t=await this.getResourceGroupsBySubscriptionId(o.subscriptionID,e);s=ve(s,`/subscriptions/${o.subscriptionID}`,t)}if(o.resource){s=ve(s,t,await this.getResourcesForResourceGroup(t,e))}}return s}async fetchAndAppendNestedRow(e,t,r){const s=t.type===ee.Subscription?await this.getResourceGroupsBySubscriptionId(t.id,r):await this.getResourcesForResourceGroup(t.id,r);return ve(e,t.uri,s)}async getSubscriptions(){let e,t=[],r=!1;for(;!r;){let s={};e&&(s={$skipToken:e});const o=await this.makeResourceGraphRequest("\n resources\n | join kind=inner (\n ResourceContainers\n | where type == 'microsoft.resources/subscriptions'\n | project subscriptionName=name, subscriptionURI=id, subscriptionId\n ) on subscriptionId\n | summarize count() by subscriptionName, subscriptionURI, subscriptionId\n | order by subscriptionName desc\n ",1,s);if(!o.data.length)throw new Error("No subscriptions were found");t=t.concat(o.data),e=o.$skipToken,r=!e}return t.map((e=>({name:e.subscriptionName,id:e.subscriptionId,uri:`/subscriptions/${e.subscriptionId}`,typeLabel:"Subscription",type:ee.Subscription,children:[]})))}async getResourceGroupsBySubscriptionId(e,t){const r=`\n resources\n | join kind=inner (\n ResourceContainers\n | where type == 'microsoft.resources/subscriptions/resourcegroups'\n | project resourceGroupURI=id, resourceGroupName=name, resourceGroup, subscriptionId\n ) on resourceGroup, subscriptionId\n\n ${this.filterByType(t)}\n | where subscriptionId == '${e}'\n | summarize count() by resourceGroupName, resourceGroupURI\n | order by resourceGroupURI asc`;let s,o=[],i=!1;for(;!i;){let e={};s&&(e={$skipToken:s});const t=await this.makeResourceGraphRequest(r,1,e);o=o.concat(t.data),s=t.$skipToken,i=!s}return o.map((e=>{const t=fe(e.resourceGroupURI);if(!t||!t.resourceGroup)throw new Error("unable to fetch resource groups");return{name:e.resourceGroupName,uri:e.resourceGroupURI,id:t.resourceGroup,type:ee.ResourceGroup,typeLabel:"Resource Group",children:[]}}))}async getResourcesForResourceGroup(e,t){const{data:r}=await this.makeResourceGraphRequest(`\n resources\n | where id hasprefix "${e}"\n ${this.filterByType(t)} and location in (${Ft})\n `);return r.map((e=>{const t=fe(e.id);if(!t||!t.resource)throw new Error("unable to fetch resource details");return{name:e.name,id:t.resource,uri:e.id,resourceGroupName:e.resourceGroup,type:ee.Resource,typeLabel:$t[e.type]||e.type,location:Vt[e.location]||e.location}}))}async getResourceURIDisplayProperties(e){var t;const{subscriptionID:r,resourceGroup:s,resource:o}=null!==(t=fe(e))&&void 0!==t?t:{};if(!r)throw new Error("Invalid resource URI passed");const i=`/subscriptions/${r}`,a=`\n resourcecontainers\n | where type == "microsoft.resources/subscriptions"\n | where id =~ "${i}"\n | project subscriptionName=name, subscriptionId\n\n | join kind=leftouter (\n resourcecontainers \n | where type == "microsoft.resources/subscriptions/resourcegroups"\n | where id =~ "${`${i}/resourceGroups/${s}`}"\n | project resourceGroupName=name, resourceGroup, subscriptionId\n ) on subscriptionId\n\n | join kind=leftouter (\n resources\n | where id =~ "${e}"\n | project resourceName=name, subscriptionId\n ) on subscriptionId\n\n | project subscriptionName, resourceGroupName, resourceName\n `,{data:n}=await this.makeResourceGraphRequest(a);if(!n.length)throw new Error("unable to fetch resource details");const{subscriptionName:c,resourceGroupName:u,resourceName:l}=n[0];return{subscriptionName:c||r,resourceGroupName:u||s,resourceName:l||o}}async getResourceURIFromWorkspace(e){const{data:t}=await this.makeResourceGraphRequest(`\n resources\n | where properties['customerId'] == "${e}"\n | project id\n `);if(!t.length)throw new Error("unable to find resource for workspace "+e);return t[0].id}async makeResourceGraphRequest(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,r=arguments.length>2?arguments[2]:void 0;try{return await this.postResource(this.resourcePath+"/providers/Microsoft.ResourceGraph/resources?api-version=2021-03-01",{query:e,options:Object.assign({resultFormat:"objectArray"},r)})}catch(r){if(t>0)return this.makeResourceGraphRequest(e,t-1);throw r}}}function Yt(e){var t,r,s,o,i;const a="string"==typeof e.rawQuery?e.rawQuery:null,n="string"==typeof e.workspace?e.workspace:null;if(!a||!n||null!==(t=e.target)&&void 0!==t&&null!==(r=t.azureLogAnalytics)&&void 0!==r&&r.query)return e;const c=Object.assign({},null!==(s=e.target)&&void 0!==s?s:{},{refId:null!==(o=null===(i=e.target)||void 0===i?void 0:i.refId)&&void 0!==o?o:"Anno",queryType:v.LogAnalytics,azureLogAnalytics:{query:a,resource:n}});return Object.assign({},e,{rawQuery:void 0,workspace:void 0,subscription:void 0,queryType:void 0,target:c})}var er=r(58788);const tr=e=>({subscriptions:e.match(/^Subscriptions\(\)/i),resourceGroups:e.match(/^ResourceGroups\(\)/i),resourceGroupsWithSub:e.match(/^ResourceGroups\(([^\)]+?)(,\s?([^,]+?))?\)/i),metricDefinitions:e.match(/^Namespaces\(([^\)]+?)(,\s?([^,]+?))?\)/i),metricDefinitionsWithSub:e.match(/^Namespaces\(([^,]+?),\s?([^,]+?)\)/i),resourceNames:e.match(/^ResourceNames\(([^,]+?),\s?([^,]+?)\)/i),resourceNamesWithSub:e.match(/^ResourceNames\(([^,]+?),\s?([^,]+?),\s?(.+?)\)/i),metricNamespace:e.match(/^MetricNamespace\(([^,]+?),\s?([^,]+?),\s?([^,]+?)\)/i),metricNamespaceWithSub:e.match(/^metricnamespace\(([^,]+?),\s?([^,]+?),\s?([^,]+?),\s?([^,]+?)\)/i),metricNames:e.match(/^MetricNames\(([^,]+?),\s?([^,]+?),\s?([^,]+?),\s?([^,]+?)\)/i),metricNamesWithSub:e.match(/^MetricNames\(([^,]+?),\s?([^,]+?),\s?([^,]+?),\s?([^,]+?),\s?(.+?)\)/i),appInsightsMetricNameQuery:e.match(/^AppInsightsMetricNames\(\)/i),appInsightsGroupByQuery:e.match(/^AppInsightsGroupBys\(([^\)]+?)(,\s?([^,]+?))?\)/i),workspacesQuery:e.match(/^workspaces\(\)/i),workspacesQueryWithSub:e.match(/^workspaces\(["']?([^\)]+?)["']?\)/i)}),rr=async(e,t)=>"string"!=typeof e?e:(e=>{const t=tr(e);return Object.keys(t).some((e=>!!t[e]))})(e)?((e,t)=>{const r=tr(e),s=t.azureMonitorDatasource.defaultSubscriptionId;return{refId:"A",queryType:v.GrafanaTemplateVariableFn,grafanaTemplateVariableFn:r.appInsightsMetricNameQuery?{rawQuery:e,kind:"AppInsightsMetricNameQuery"}:r.appInsightsGroupByQuery?{kind:"AppInsightsGroupByQuery",rawQuery:e,metricName:r.appInsightsGroupByQuery[1]}:r.subscriptions?{kind:"SubscriptionsQuery",rawQuery:e}:r.resourceGroupsWithSub?{kind:"ResourceGroupsQuery",rawQuery:e,subscription:r.resourceGroupsWithSub[1]}:r.resourceGroups&&s?{kind:"ResourceGroupsQuery",rawQuery:e,subscription:s}:r.metricDefinitionsWithSub?{kind:"MetricDefinitionsQuery",rawQuery:e,subscription:r.metricDefinitionsWithSub[1],resourceGroup:r.metricDefinitionsWithSub[2]}:r.metricDefinitions&&s?{kind:"MetricDefinitionsQuery",rawQuery:e,subscription:s,resourceGroup:r.metricDefinitions[1]}:r.resourceNamesWithSub?{kind:"ResourceNamesQuery",rawQuery:e,subscription:r.resourceNamesWithSub[1],resourceGroup:r.resourceNamesWithSub[2],metricDefinition:r.resourceNamesWithSub[3]}:r.resourceNames&&s?{kind:"ResourceNamesQuery",rawQuery:e,subscription:s,resourceGroup:r.resourceNames[1],metricDefinition:r.resourceNames[2]}:r.metricNamespaceWithSub?{kind:"MetricNamespaceQuery",rawQuery:e,subscription:r.metricNamespaceWithSub[1],resourceGroup:r.metricNamespaceWithSub[2],metricDefinition:r.metricNamespaceWithSub[3],resourceName:r.metricNamespaceWithSub[4]}:r.metricNamespace&&s?{kind:"MetricNamespaceQuery",rawQuery:e,subscription:s,resourceGroup:r.metricNamespace[1],metricDefinition:r.metricNamespace[2],resourceName:r.metricNamespace[3]}:r.metricNames&&s&&-1===r.metricNames[3].indexOf(",")?{kind:"MetricNamesQuery",rawQuery:e,subscription:s,resourceGroup:r.metricNames[1],metricDefinition:r.metricNames[2],resourceName:r.metricNames[3],metricNamespace:r.metricNames[4]}:r.metricNamesWithSub?{kind:"MetricNamesQuery",rawQuery:e,subscription:r.metricNamesWithSub[1],resourceGroup:r.metricNamesWithSub[2],metricDefinition:r.metricNamesWithSub[3],resourceName:r.metricNamesWithSub[4],metricNamespace:r.metricNamesWithSub[5]}:r.workspacesQueryWithSub?{kind:"WorkspacesQuery",rawQuery:e,subscription:(r.workspacesQueryWithSub[1]||"").trim()}:r.workspacesQuery&&s?{kind:"WorkspacesQuery",rawQuery:e,subscription:s}:{kind:"SubscriptionsQuery",rawQuery:e},subscription:s}})(e,t.datasource):(async(e,t)=>{const r=t.azureMonitorDatasource.defaultSubscriptionId;let s="";if(e){const e=t.azureLogAnalyticsDatasource.getDeprecatedDefaultWorkSpace();s=e?ge(e)?await t.resourcePickerData.getResourceURIFromWorkspace(e):e:await t.azureLogAnalyticsDatasource.getFirstWorkspace()||""}return{refId:"A",queryType:v.LogAnalytics,azureLogAnalytics:{query:e,resource:s},subscription:r}})(e,t.datasource);var sr;const or=[{label:"Grafana Query Function",value:v.GrafanaTemplateVariableFn},{label:"Logs",value:v.LogAnalytics}],ir=e=>{var t;let{query:r,updateQuery:s,datasource:i}=e;const[n,c]=(0,o.useState)("");(0,o.useEffect)((()=>{var e;c((null===(e=r.grafanaTemplateVariableFn)||void 0===e?void 0:e.rawQuery)||"")}),[null===(t=r.grafanaTemplateVariableFn)||void 0===t?void 0:t.rawQuery]);const u=(0,o.useCallback)((e=>{rr(e,{datasource:i}).then((t=>{t.queryType===v.GrafanaTemplateVariableFn?s(t):s(Object.assign({},r,{grafanaTemplateVariableFn:{kind:"UnknownQuery",rawQuery:e}}))}))}),[i,r,s]);return(0,G.jsx)(a.InlineField,{label:"Grafana template variable function",children:(0,G.jsx)(a.Input,{placeholder:"type a grafana template variable function, ex: Subscriptions()",value:n,onChange:e=>{c(e.target.value)},onBlur:()=>u(n)})})},ar=e=>{const t={refId:"A",queryType:v.GrafanaTemplateVariableFn},[r,s]=(0,o.useState)(t);(0,o.useEffect)((()=>{rr(e.query,{datasource:e.datasource}).then((e=>{s(e)}))}),[e.query,e.datasource]);const[i,n]=$();return(0,G.jsxs)(G.Fragment,{children:[(0,G.jsx)(a.InlineField,{label:"Select query type",children:(0,G.jsx)(a.Select,{"aria-label":"select query type",onChange:e=>{e.value&&s(Object.assign({},r,{queryType:e.value}))},options:or,width:25,value:r.queryType})}),r.queryType===v.LogAnalytics&&(0,G.jsxs)(G.Fragment,{children:[(0,G.jsx)(He,{subscriptionId:r.subscription,query:r,datasource:e.datasource,onChange:t=>{var r;s(t),null!==(r=t.azureLogAnalytics)&&void 0!==r&&r.query&&e.onChange(t)},variableOptionGroup:{label:"Template Variables",options:[]},setError:n,hideFormatAs:!0}),i&&(0,G.jsxs)(G.Fragment,{children:[sr||(sr=(0,G.jsx)(Z,{v:2})),(0,G.jsx)(a.Alert,{severity:"error",title:"An error occurred while requesting metadata from Azure Monitor",children:i})]})]}),r.queryType===v.GrafanaTemplateVariableFn&&(0,G.jsx)(ir,{query:r,updateQuery:e.onChange,datasource:e.datasource})]})};class nr extends s.CustomVariableSupport{constructor(e){var t,r,s;super(),s=ar,(r="editor")in(t=this)?Object.defineProperty(t,r,{value:s,enumerable:!0,configurable:!0,writable:!0}):t[r]=s,this.datasource=e,this.datasource=e,this.query=this.query.bind(this)}query(e){return(0,It.D)((async()=>{const t=await rr(e.targets[0],{datasource:this.datasource});if(t.queryType===v.GrafanaTemplateVariableFn&&t.grafanaTemplateVariableFn)try{const e=await this.callGrafanaTemplateVariableFn(t.grafanaTemplateVariableFn);return{data:null!=e&&e.length?[(0,s.toDataFrame)(e)]:[]}}catch(e){return{data:[],error:{message:(0,V.Z)(e)}}}return e.targets[0]=t,(0,er.n)(this.datasource.query(e))})())}callGrafanaTemplateVariableFn(e){return"SubscriptionsQuery"===e.kind?this.datasource.getSubscriptions():"ResourceGroupsQuery"===e.kind?this.datasource.getResourceGroups(this.replaceVariable(e.subscription)):"MetricDefinitionsQuery"===e.kind?this.datasource.getMetricDefinitions(this.replaceVariable(e.subscription),this.replaceVariable(e.resourceGroup)):"ResourceNamesQuery"===e.kind?this.datasource.getResourceNames(this.replaceVariable(e.subscription),this.replaceVariable(e.resourceGroup),this.replaceVariable(e.metricDefinition)):"MetricNamespaceQuery"===e.kind?this.datasource.azureMonitorDatasource.getMetricNamespaces(e):"MetricNamesQuery"===e.kind?this.datasource.azureMonitorDatasource.getMetricNames(e):"WorkspacesQuery"===e.kind?this.datasource.azureLogAnalyticsDatasource.getWorkspaces(this.replaceVariable(e.subscription)):null}replaceVariable(e){return(0,i.getTemplateSrv)().replace((e||"").trim())}}function cr(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}class ur extends s.DataSourceApi{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:(0,Ct.J)();super(e),cr(this,"annotations",{prepareAnnotation:Yt}),cr(this,"azureMonitorDatasource",void 0),cr(this,"azureLogAnalyticsDatasource",void 0),cr(this,"resourcePickerData",void 0),cr(this,"azureResourceGraphDatasource",void 0),cr(this,"pseudoDatasource",{}),this.templateSrv=t,this.azureMonitorDatasource=new Bt(e),this.azureLogAnalyticsDatasource=new Ot(e),this.azureResourceGraphDatasource=new Ht(e),this.resourcePickerData=new Zt(e),this.pseudoDatasource={[v.AzureMonitor]:this.azureMonitorDatasource,[v.LogAnalytics]:this.azureLogAnalyticsDatasource,[v.AzureResourceGraph]:this.azureResourceGraphDatasource},this.variables=new nr(this)}filterQuery(e){var t,r;if(!e.queryType)return!0;const s=this.pseudoDatasource[e.queryType];return null===(t=null==s||null===(r=s.filterQuery)||void 0===r?void 0:r.call(s,e))||void 0===t||t}query(e){const t=new Map;for(const r of e.targets){const s=yt(r,this.templateSrv);if(!s.queryType||s.hide||!lr(s))continue;if(!t.has(s.queryType)){const r=(0,n.cloneDeep)(e);r.requestId=`${r.requestId}-${s.refId}`,r.targets=[],t.set(s.queryType,r)}const o=t.get(s.queryType);null==o||o.targets.push(s)}const r=Array.from(t.entries()).map((e=>{let[t,r]=e;const s=this.pseudoDatasource[t];if(!s)throw new Error("Data source not created for query type "+t);return s.query(r)}));return 1===r.length?r[0]:r.length>1?(0,zt.D)(r).pipe((0,Nt.U)((e=>{const t=[];for(const r of e)for(const e of r.data)t.push(e);return{state:s.LoadingState.Done,data:t}}))):(0,xt.of)({state:s.LoadingState.Done,data:[]})}targetContainsTemplate(e){if(e.subscription&&this.templateSrv.containsTemplate(e.subscription))return!0;let t;return e.queryType===v.AzureMonitor?t=JSON.stringify(e.azureMonitor):e.queryType===v.LogAnalytics?t=JSON.stringify(e.azureLogAnalytics):e.queryType===v.AzureResourceGraph&&(t=JSON.stringify([e.azureResourceGraph,e.subscriptions])),!!t&&this.templateSrv.containsTemplate(t)}async annotationQuery(e){return this.azureLogAnalyticsDatasource.annotationQuery(e)}async testDatasource(){const e=[];return e.push(this.azureMonitorDatasource.testDatasource()),e.push(this.azureLogAnalyticsDatasource.testDatasource()),await Promise.all(e).then((e=>{let t="success",r="";for(let s=0;s<e.length;s++)"success"!==e[s].status&&(t=e[s].status),r+=`${s+1}. ${e[s].message} `;return{status:t,message:r,title:(0,n.upperFirst)(t)}}))}getResourceGroups(e){return this.azureMonitorDatasource.getResourceGroups(this.replaceTemplateVariable(e))}getMetricDefinitions(e,t){return this.azureMonitorDatasource.getMetricDefinitions(this.replaceTemplateVariable(e),this.replaceTemplateVariable(t))}getResourceNames(e,t,r){return this.azureMonitorDatasource.getResourceNames(this.replaceTemplateVariable(e),this.replaceTemplateVariable(t),this.replaceTemplateVariable(r))}getAzureLogAnalyticsWorkspaces(e){return this.azureLogAnalyticsDatasource.getWorkspaces(e)}getSubscriptions(){return this.azureMonitorDatasource.getSubscriptions()}interpolateVariablesInQueries(e,t){return e.map((e=>{var r;if(!e.queryType)return e;const s=this.pseudoDatasource[e.queryType];return Object.assign({datasource:null==s?void 0:s.getRef()},null!==(r=null==s?void 0:s.applyTemplateVariables(e,t))&&void 0!==r?r:e)}))}replaceTemplateVariable(e){return this.templateSrv.replace(e)}getVariables(){return this.templateSrv.getVariables().map((e=>`$${e.name}`))}isTemplateVariable(e){return this.getVariables().includes(e)}}function lr(e){switch(e.queryType){case v.AzureMonitor:return!!e.azureMonitor;case v.LogAnalytics:return!!e.azureLogAnalytics;case v.AzureResourceGraph:return!!e.azureResourceGraph;case v.GrafanaTemplateVariableFn:return!!e.grafanaTemplateVariableFn;default:return!1}}const pr=new s.DataSourcePlugin(ur).setConfigEditor(F).setQueryEditor(jt)},75973:(e,t,r)=>{function s(e){for(var t=arguments.length,r=Array(t>1?t-1:0),s=1;s<t;s++)r[s-1]=arguments[s];throw Error("[Immer] minified error nr: "+e+(r.length?" "+r.map((function(e){return"'"+e+"'"})).join(","):"")+". Find the full error at: https://bit.ly/3cXEKWf")}function o(e){return!!e&&!!e[U]}function i(e){return!!e&&(function(e){if(!e||"object"!=typeof e)return!1;var t=Object.getPrototypeOf(e);if(null===t)return!0;var r=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return r===Object||"function"==typeof r&&Function.toString.call(r)===X}(e)||Array.isArray(e)||!!e[W]||!!e.constructor[W]||m(e)||d(e))}function a(e,t,r){void 0===r&&(r=!1),0===n(e)?(r?Object.keys:B)(e).forEach((function(s){r&&"symbol"==typeof s||t(s,e[s],e)})):e.forEach((function(r,s){return t(s,r,e)}))}function n(e){var t=e[U];return t?t.i>3?t.i-4:t.i:Array.isArray(e)?1:m(e)?2:d(e)?3:0}function c(e,t){return 2===n(e)?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function u(e,t){return 2===n(e)?e.get(t):e[t]}function l(e,t,r){var s=n(e);2===s?e.set(t,r):3===s?(e.delete(t),e.add(r)):e[t]=r}function p(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t}function m(e){return F&&e instanceof Map}function d(e){return V&&e instanceof Set}function f(e){return e.o||e.t}function g(e){if(Array.isArray(e))return Array.prototype.slice.call(e);var t=H(e);delete t[U];for(var r=B(t),s=0;s<r.length;s++){var o=r[s],i=t[o];!1===i.writable&&(i.writable=!0,i.configurable=!0),(i.get||i.set)&&(t[o]={configurable:!0,writable:!0,enumerable:i.enumerable,value:e[o]})}return Object.create(Object.getPrototypeOf(e),t)}function h(e,t){return void 0===t&&(t=!1),b(e)||o(e)||!i(e)||(n(e)>1&&(e.set=e.add=e.clear=e.delete=v),Object.freeze(e),t&&a(e,(function(e,t){return h(t,!0)}),!0)),e}function v(){s(2)}function b(e){return null==e||"object"!=typeof e||Object.isFrozen(e)}function y(e){var t=_[e];return t||s(18,e),t}function w(){return q}function S(e,t){t&&(y("Patches"),e.u=[],e.s=[],e.v=t)}function k(e){M(e),e.p.forEach(j),e.p=null}function M(e){e===q&&(q=e.l)}function A(e){return q={p:[],l:q,h:e,m:!0,_:0}}function j(e){var t=e[U];0===t.i||1===t.i?t.j():t.O=!0}function z(e,t){t._=t.p.length;var r=t.p[0],o=void 0!==e&&e!==r;return t.h.g||y("ES5").S(t,e,o),o?(r[U].P&&(k(t),s(4)),i(e)&&(e=x(t,e),t.l||C(t,e)),t.u&&y("Patches").M(r[U].t,e,t.u,t.s)):e=x(t,r,[]),k(t),t.u&&t.v(t.u,t.s),e!==Q?e:void 0}function x(e,t,r){if(b(t))return t;var s=t[U];if(!s)return a(t,(function(o,i){return N(e,s,t,o,i,r)}),!0),t;if(s.A!==e)return t;if(!s.P)return C(e,s.t,!0),s.t;if(!s.I){s.I=!0,s.A._--;var o=4===s.i||5===s.i?s.o=g(s.k):s.o;a(3===s.i?new Set(o):o,(function(t,i){return N(e,s,o,t,i,r)})),C(e,o,!1),r&&e.u&&y("Patches").R(s,r,e.u,e.s)}return s.o}function N(e,t,r,s,a,n){if(o(a)){var u=x(e,a,n&&t&&3!==t.i&&!c(t.D,s)?n.concat(s):void 0);if(l(r,s,u),!o(u))return;e.m=!1}if(i(a)&&!b(a)){if(!e.h.F&&e._<1)return;x(e,a),t&&t.A.l||C(e,a)}}function C(e,t,r){void 0===r&&(r=!1),e.h.F&&e.m&&h(t,r)}function I(e,t){var r=e[U];return(r?f(r):e)[t]}function D(e,t){if(t in e)for(var r=Object.getPrototypeOf(e);r;){var s=Object.getOwnPropertyDescriptor(r,t);if(s)return s;r=Object.getPrototypeOf(r)}}function G(e){e.P||(e.P=!0,e.l&&G(e.l))}function T(e){e.o||(e.o=g(e.t))}function L(e,t,r){var s=m(t)?y("MapSet").N(t,r):d(t)?y("MapSet").T(t,r):e.g?function(e,t){var r=Array.isArray(e),s={i:r?1:0,A:t?t.A:w(),P:!1,I:!1,D:{},l:t,t:e,k:null,o:null,j:null,C:!1},o=s,i=K;r&&(o=[s],i=J);var a=Proxy.revocable(o,i),n=a.revoke,c=a.proxy;return s.k=c,s.j=n,c}(t,r):y("ES5").J(t,r);return(r?r.A:w()).p.push(s),s}function R(e){return o(e)||s(22,e),function e(t){if(!i(t))return t;var r,s=t[U],o=n(t);if(s){if(!s.P&&(s.i<4||!y("ES5").K(s)))return s.t;s.I=!0,r=P(t,o),s.I=!1}else r=P(t,o);return a(r,(function(t,o){s&&u(s.t,t)===o||l(r,t,e(o))})),3===o?new Set(r):r}(e)}function P(e,t){switch(t){case 2:return new Map(e);case 3:return Array.from(e)}return g(e)}r.d(t,{ZP:()=>te});var O,q,E="undefined"!=typeof Symbol&&"symbol"==typeof Symbol("x"),F="undefined"!=typeof Map,V="undefined"!=typeof Set,$="undefined"!=typeof Proxy&&void 0!==Proxy.revocable&&"undefined"!=typeof Reflect,Q=E?Symbol.for("immer-nothing"):((O={})["immer-nothing"]=!0,O),W=E?Symbol.for("immer-draftable"):"__$immer_draftable",U=E?Symbol.for("immer-state"):"__$immer_state",X=("undefined"!=typeof Symbol&&Symbol.iterator,""+Object.prototype.constructor),B="undefined"!=typeof Reflect&&Reflect.ownKeys?Reflect.ownKeys:void 0!==Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Object.getOwnPropertyNames,H=Object.getOwnPropertyDescriptors||function(e){var t={};return B(e).forEach((function(r){t[r]=Object.getOwnPropertyDescriptor(e,r)})),t},_={},K={get:function(e,t){if(t===U)return e;var r=f(e);if(!c(r,t))return function(e,t,r){var s,o=D(t,r);return o?"value"in o?o.value:null===(s=o.get)||void 0===s?void 0:s.call(e.k):void 0}(e,r,t);var s=r[t];return e.I||!i(s)?s:s===I(e.t,t)?(T(e),e.o[t]=L(e.A.h,s,e)):s},has:function(e,t){return t in f(e)},ownKeys:function(e){return Reflect.ownKeys(f(e))},set:function(e,t,r){var s=D(f(e),t);if(null==s?void 0:s.set)return s.set.call(e.k,r),!0;if(!e.P){var o=I(f(e),t),i=null==o?void 0:o[U];if(i&&i.t===r)return e.o[t]=r,e.D[t]=!1,!0;if(p(r,o)&&(void 0!==r||c(e.t,t)))return!0;T(e),G(e)}return e.o[t]===r&&"number"!=typeof r&&(void 0!==r||t in e.o)||(e.o[t]=r,e.D[t]=!0,!0)},deleteProperty:function(e,t){return void 0!==I(e.t,t)||t in e.t?(e.D[t]=!1,T(e),G(e)):delete e.D[t],e.o&&delete e.o[t],!0},getOwnPropertyDescriptor:function(e,t){var r=f(e),s=Reflect.getOwnPropertyDescriptor(r,t);return s?{writable:!0,configurable:1!==e.i||"length"!==t,enumerable:s.enumerable,value:r[t]}:s},defineProperty:function(){s(11)},getPrototypeOf:function(e){return Object.getPrototypeOf(e.t)},setPrototypeOf:function(){s(12)}},J={};a(K,(function(e,t){J[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}})),J.deleteProperty=function(e,t){return J.set.call(this,e,t,void 0)},J.set=function(e,t,r){return K.set.call(this,e[0],t,r,e[0])};var Z=function(){function e(e){var t=this;this.g=$,this.F=!0,this.produce=function(e,r,o){if("function"==typeof e&&"function"!=typeof r){var a=r;r=e;var n=t;return function(e){var t=this;void 0===e&&(e=a);for(var s=arguments.length,o=Array(s>1?s-1:0),i=1;i<s;i++)o[i-1]=arguments[i];return n.produce(e,(function(e){var s;return(s=r).call.apply(s,[t,e].concat(o))}))}}var c;if("function"!=typeof r&&s(6),void 0!==o&&"function"!=typeof o&&s(7),i(e)){var u=A(t),l=L(t,e,void 0),p=!0;try{c=r(l),p=!1}finally{p?k(u):M(u)}return"undefined"!=typeof Promise&&c instanceof Promise?c.then((function(e){return S(u,o),z(e,u)}),(function(e){throw k(u),e})):(S(u,o),z(c,u))}if(!e||"object"!=typeof e){if(void 0===(c=r(e))&&(c=e),c===Q&&(c=void 0),t.F&&h(c,!0),o){var m=[],d=[];y("Patches").M(e,c,m,d),o(m,d)}return c}s(21,e)},this.produceWithPatches=function(e,r){if("function"==typeof e)return function(r){for(var s=arguments.length,o=Array(s>1?s-1:0),i=1;i<s;i++)o[i-1]=arguments[i];return t.produceWithPatches(r,(function(t){return e.apply(void 0,[t].concat(o))}))};var s,o,i=t.produce(e,r,(function(e,t){s=e,o=t}));return"undefined"!=typeof Promise&&i instanceof Promise?i.then((function(e){return[e,s,o]})):[i,s,o]},"boolean"==typeof(null==e?void 0:e.useProxies)&&this.setUseProxies(e.useProxies),"boolean"==typeof(null==e?void 0:e.autoFreeze)&&this.setAutoFreeze(e.autoFreeze)}var t=e.prototype;return t.createDraft=function(e){i(e)||s(8),o(e)&&(e=R(e));var t=A(this),r=L(this,e,void 0);return r[U].C=!0,M(t),r},t.finishDraft=function(e,t){var r=(e&&e[U]).A;return S(r,t),z(void 0,r)},t.setAutoFreeze=function(e){this.F=e},t.setUseProxies=function(e){e&&!$&&s(20),this.g=e},t.applyPatches=function(e,t){var r;for(r=t.length-1;r>=0;r--){var s=t[r];if(0===s.path.length&&"replace"===s.op){e=s.value;break}}r>-1&&(t=t.slice(r+1));var i=y("Patches").$;return o(e)?i(e,t):this.produce(e,(function(e){return i(e,t)}))},e}(),Y=new Z,ee=Y.produce;Y.produceWithPatches.bind(Y),Y.setAutoFreeze.bind(Y),Y.setUseProxies.bind(Y),Y.applyPatches.bind(Y),Y.createDraft.bind(Y),Y.finishDraft.bind(Y);const te=ee}}]);
  2. //# sourceMappingURL=azureMonitorPlugin.dcdd38e4ee204b628148.js.map