(self.webpackChunkgrafana=self.webpackChunkgrafana||[]).push([[8366],{362:(Te,ne,s)=>{"use strict";s.d(ne,{ZP:()=>m});var b=s(9892),U=s(57706),a=s(66111),re=s(83881),D=s(41818),ae=s(13193),B=s(67660),ee=s(39904),Z=s(31403),J=s(72648),G=s(59796);function F(i){return typeof i=="object"&&i!==null&&"isCanceled"in i}const E=i=>{let l=!1;return{promise:new Promise((o,c)=>{const g={isCanceled:!0};i.then(p=>l?c(g):o(p)),i.catch(p=>c(l?g:p))}),cancel(){l=!0}}};var Q=s(51649),C=s(32436),W=s(7804),M=s(61744),$=s(52081),k=s(64353),w=s(46967),P=s(85951);const O="{}",L="__name__",j=25;function X(i){let l="";const u=[];for(const o of i)if((o.name===L||o.selected)&&o.values&&o.values.length>0){const c=o.values.filter(g=>g.selected).map(g=>g.name);c.length>1?u.push(`${o.name}=~"${c.map(Q.tU).join("|")}"`):c.length===1&&(o.name===L?l=c[0]:u.push(`${o.name}="${(0,Q.U9)(c[0])}"`))}return[l,"{",u.join(","),"}"].join("")}function de(i,l,u){return i.map(o=>{const c=l[o.name];if(c){let g;if(o.name===u&&o.values)g=o.values;else{const p=new Set(o.values?.filter(v=>v.selected).map(v=>v.name)||[]);g=c.map(v=>({name:v,selected:p.has(v)}))}return{...o,loading:!1,values:g,hidden:!c,facets:g.length}}return{...o,loading:!1,hidden:!c,values:void 0,facets:0}})}const le=(0,W.B)(i=>({wrapper:b.css`
    background-color: ${i.colors.background.secondary};
    padding: ${i.spacing(1)};
    width: 100%;
  `,list:b.css`
    margin-top: ${i.spacing(1)};
    display: flex;
    flex-wrap: wrap;
    max-height: 200px;
    overflow: auto;
    align-content: flex-start;
  `,section:b.css`
    & + & {
      margin: ${i.spacing(2)} 0;
    }
    position: relative;
  `,selector:b.css`
    font-family: ${i.typography.fontFamilyMonospace};
    margin-bottom: ${i.spacing(1)};
  `,status:b.css`
    padding: ${i.spacing(.5)};
    color: ${i.colors.text.secondary};
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    /* using absolute positioning because flex interferes with ellipsis */
    position: absolute;
    width: 50%;
    right: 0;
    text-align: right;
    transition: opacity 100ms linear;
    opacity: 0;
  `,statusShowing:b.css`
    opacity: 1;
  `,error:b.css`
    color: ${i.colors.error.main};
  `,valueList:b.css`
    margin-right: ${i.spacing(1)};
    resize: horizontal;
  `,valueListWrapper:b.css`
    border-left: 1px solid ${i.colors.border.medium};
    margin: ${i.spacing(1)} 0;
    padding: ${i.spacing(1)} 0 ${i.spacing(1)} ${i.spacing(1)};
  `,valueListArea:b.css`
    display: flex;
    flex-wrap: wrap;
    margin-top: ${i.spacing(1)};
  `,valueTitle:b.css`
    margin-left: -${i.spacing(.5)};
    margin-bottom: ${i.spacing(1)};
  `,validationStatus:b.css`
    padding: ${i.spacing(.5)};
    margin-bottom: ${i.spacing(1)};
    color: ${i.colors.text.maxContrast};
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  `}));class Se extends a.Component{constructor(){super(...arguments),this.valueListsRef=a.createRef(),this.state={labels:[],labelSearchTerm:"",metricSearchTerm:"",status:"Ready",error:"",validationStatus:"",valueSearchTerm:""},this.onChangeLabelSearch=l=>{this.setState({labelSearchTerm:l.target.value})},this.onChangeMetricSearch=l=>{this.setState({metricSearchTerm:l.target.value})},this.onChangeValueSearch=l=>{this.setState({valueSearchTerm:l.target.value})},this.onClickRunQuery=()=>{const l=X(this.state.labels);this.props.onChange(l)},this.onClickRunRateQuery=()=>{const u=`rate(${X(this.state.labels)}[$__rate_interval])`;this.props.onChange(u)},this.onClickClear=()=>{this.setState(l=>({labels:l.labels.map(o=>({...o,values:void 0,selected:!1,loading:!1,hidden:!1,facets:void 0})),labelSearchTerm:"",metricSearchTerm:"",status:"",error:"",validationStatus:"",valueSearchTerm:""})),this.props.deleteLastUsedLabels(),this.fetchValues(L,O)},this.onClickLabel=(l,u,o)=>{const c=this.state.labels.find(v=>v.name===l);if(!c)return;const g=!c.selected;let p={selected:g};if(c.values&&!g){const v=c.values.map(x=>({...x,selected:!1}));p={...p,facets:0,values:v}}this.setState({labelSearchTerm:""}),this.updateLabelState(l,p,"",()=>this.doFacettingForLabel(l))},this.onClickValue=(l,u,o)=>{const c=this.state.labels.find(p=>p.name===l);if(!c||!c.values)return;this.setState({labelSearchTerm:""});const g=c.values.map(p=>({...p,selected:p.name===u?!p.selected:p.selected}));this.updateLabelState(l,{values:g},"",()=>this.doFacetting(l))},this.onClickMetric=(l,u,o)=>{const c=this.state.labels.find(v=>v.name===l);if(!c||!c.values)return;this.setState({metricSearchTerm:""});const g=c.values.map(v=>({...v,selected:v.name===u||v.selected?!v.selected:v.selected})),p=g.some(v=>v.selected);this.updateLabelState(l,{selected:p,values:g},"",()=>this.doFacetting(l))},this.onClickValidate=()=>{const l=X(this.state.labels);this.validateSelector(l)},this.doFacetting=l=>{const u=X(this.state.labels);if(u===O){const o=this.state.labels.map(c=>({...c,facets:0,values:void 0,hidden:!1}));this.setState({labels:o},()=>{this.state.labels.forEach(c=>(c.selected||c.name===L)&&this.fetchValues(c.name,u))})}else this.fetchSeries(u,l)}}updateLabelState(l,u,o="",c){this.setState(g=>{const p=g.labels.map(x=>x.name===l?{...x,...u}:x),v=o?"":g.error;return{labels:p,status:o,error:v,validationStatus:""}},c)}componentDidMount(){const{languageProvider:l,lastUsedLabels:u}=this.props;if(l){const o=u;l.start().then(()=>{let c=l.getLabelKeys();this.fetchValues(L,O);const g=c.map((p,v,x)=>({name:p,selected:o.includes(p),loading:!1}));this.setState({labels:g},()=>{this.state.labels.forEach(p=>{p.selected&&this.fetchValues(p.name,O)})})})}}doFacettingForLabel(l){const u=this.state.labels.find(c=>c.name===l);if(!u)return;const o=this.state.labels.filter(c=>c.selected).map(c=>c.name);this.props.storeLastUsedLabels(o),u.selected?u.values||this.fetchValues(l,X(this.state.labels)):this.doFacetting()}async fetchValues(l,u){const{languageProvider:o}=this.props;this.updateLabelState(l,{loading:!0},`Fetching values for ${l}`);try{let c=await o.getLabelValues(l);if(u!==X(this.state.labels)){this.updateLabelState(l,{loading:!1});return}const g=[],{metricsMetadata:p}=o;for(const v of c){const x={name:v};if(l===L&&p){const S=p[v];S&&(x.details=`(${S.type}) ${S.help}`)}g.push(x)}this.updateLabelState(l,{values:g,loading:!1})}catch(c){console.error(c)}}async fetchSeries(l,u){const{languageProvider:o}=this.props;u&&this.updateLabelState(u,{loading:!0},`Facetting labels for ${l}`);try{const c=await o.fetchSeriesLabels(l,!0);if(l!==X(this.state.labels)){u&&this.updateLabelState(u,{loading:!1});return}if(Object.keys(c).length===0){this.setState({error:`Empty results, no matching label for ${l}`});return}const g=de(this.state.labels,c,u);this.setState({labels:g,error:""}),u&&this.updateLabelState(u,{loading:!1})}catch(c){console.error(c)}}async validateSelector(l){const{languageProvider:u}=this.props;this.setState({validationStatus:`Validating selector ${l}`,error:""});const o=await u.fetchSeries(l);this.setState({validationStatus:`Selector is valid (${o.length} series found)`})}render(){const{theme:l}=this.props,{labels:u,labelSearchTerm:o,metricSearchTerm:c,status:g,error:p,validationStatus:v,valueSearchTerm:x}=this.state,S=le(l);if(u.length===0)return a.createElement("div",{className:S.wrapper},a.createElement(M.u,{text:"Loading labels..."}));let T=u.find(I=>I.name===L);T&&c&&(T={...T,values:T.values?.filter(I=>I.selected||I.name.includes(c))});let _=u.filter(I=>!I.hidden&&I.name!==L);o&&(_=_.filter(I=>I.selected||I.name.includes(o)));let te=_.filter(I=>I.selected&&I.values);x&&(te=te.map(I=>({...I,values:I.values?.filter(z=>z.selected||z.name.includes(x))})));const ce=X(this.state.labels),ge=ce===O,V=T?.values?.length||0;return a.createElement("div",{className:S.wrapper},a.createElement($.Lh,{align:"flex-start",spacing:"lg"},a.createElement("div",null,a.createElement("div",{className:S.section},a.createElement(k._,{description:"Once a metric is selected only possible labels are shown."},"1. Select a metric"),a.createElement("div",null,a.createElement(w.I,{onChange:this.onChangeMetricSearch,"aria-label":"Filter expression for metric",value:c})),a.createElement("div",{role:"list",className:S.valueListWrapper},a.createElement(C.t7,{height:Math.min(450,V*j),itemCount:V,itemSize:j,itemKey:I=>T.values[I].name,width:300,className:S.valueList},({index:I,style:z})=>{const se=T?.values?.[I];return se?a.createElement("div",{style:z},a.createElement(P._,{name:T.name,value:se?.name,title:se.details,active:se?.selected,onClick:this.onClickMetric,searchTerm:c})):null})))),a.createElement("div",null,a.createElement("div",{className:S.section},a.createElement(k._,{description:"Once label values are selected, only possible label combinations are shown."},"2. Select labels to search in"),a.createElement("div",null,a.createElement(w.I,{onChange:this.onChangeLabelSearch,"aria-label":"Filter expression for label",value:o})),a.createElement("div",{className:S.list,style:{height:120}},_.map(I=>a.createElement(P._,{key:I.name,name:I.name,loading:I.loading,active:I.selected,hidden:I.hidden,facets:I.facets,onClick:this.onClickLabel,searchTerm:o})))),a.createElement("div",{className:S.section},a.createElement(k._,{description:"Use the search field to find values across selected labels."},"3. Select (multiple) values for your labels"),a.createElement("div",null,a.createElement(w.I,{onChange:this.onChangeValueSearch,"aria-label":"Filter expression for label values",value:x})),a.createElement("div",{className:S.valueListArea,ref:this.valueListsRef},te.map(I=>a.createElement("div",{role:"list",key:I.name,"aria-label":`Values for ${I.name}`,className:S.valueListWrapper},a.createElement("div",{className:S.valueTitle},a.createElement(P._,{name:I.name,loading:I.loading,active:I.selected,hidden:I.hidden,facets:I.facets||I.values?.length,onClick:this.onClickLabel})),a.createElement(C.t7,{height:Math.min(200,j*(I.values?.length||0)),itemCount:I.values?.length||0,itemSize:28,itemKey:z=>I.values[z].name,width:200,className:S.valueList},({index:z,style:se})=>{const Ee=I.values?.[z];return Ee?a.createElement("div",{style:se},a.createElement(P._,{name:I.name,value:Ee?.name,active:Ee?.selected,onClick:this.onClickValue,searchTerm:x})):null}))))))),a.createElement("div",{className:S.section},a.createElement(k._,null,"4. Resulting selector"),a.createElement("div",{"aria-label":"selector",className:S.selector},ce),v&&a.createElement("div",{className:S.validationStatus},v),a.createElement($.Lh,null,a.createElement(Z.zx,{"aria-label":"Use selector for query button",disabled:ge,onClick:this.onClickRunQuery},"Use query"),a.createElement(Z.zx,{"aria-label":"Use selector as metrics button",variant:"secondary",disabled:ge,onClick:this.onClickRunRateQuery},"Use as rate query"),a.createElement(Z.zx,{"aria-label":"Validate submit button",variant:"secondary",disabled:ge,onClick:this.onClickValidate},"Validate selector"),a.createElement(Z.zx,{"aria-label":"Selector clear button",variant:"secondary",onClick:this.onClickClear},"Clear"),a.createElement("div",{className:(0,b.cx)(S.status,(g||p)&&S.statusShowing)},a.createElement("span",{className:p?S.error:""},p||g)))))}}const K=(0,J.HE)(Se),ie=a.lazy(()=>s.e(6031).then(s.bind(s,75695))),ve=i=>a.createElement(a.Suspense,{fallback:null},a.createElement(ie,{...i})),pe=i=>{const l=(0,a.useRef)(null),{onRunQuery:u,onChange:o,...c}=i,g=x=>{l.current=x,o(x),u()},p=x=>{o(x)},v=x=>{o(x)};return a.createElement(ve,{onChange:v,onRunQuery:g,onBlur:p,...c})},Ce="__recording_rules__",ye="grafana.datasources.prometheus.browser.labels";function Me(i,l,u){return i?"(Disabled)":l?u?"Metrics browser":"(No metrics found)":"Loading metrics..."}function Re(i,{typeaheadContext:l,typeaheadText:u}){switch(l){case"context-labels":{const o=DOMUtil.getNextCharacter();(!o||o==="}"||o===",")&&(i+="=");break}case"context-label-values":{u.match(/^(!?=~?"|")/)||(i=`"${i}`),DOMUtil.getNextCharacter()!=='"'&&(i=`${i}"`);break}default:}return i}class fe extends a.PureComponent{constructor(l,u){super(l,u),this.refreshHint=()=>{const{datasource:o,query:c,data:g}=this.props,p=o.getInitHints(),v=p.length>0?p[0]:null;if(!g||g.series.length===0){this.setState({hint:v});return}const x=(0,re.aY)(g.series[0])?g.series.map(re.Zr):g.series,S=o.getQueryHints(c,x);let T=S.length>0?S[0]:null;this.setState({hint:T??v})},this.refreshMetrics=async()=>{const{datasource:{languageProvider:o}}=this.props;this.languageProviderInitializationPromise=E(o.start());try{const c=await this.languageProviderInitializationPromise.promise;await Promise.all(c),this.onUpdateLanguage()}catch(c){if(!(F(c)&&c.isCanceled))throw c}},this.onChangeLabelBrowser=o=>{this.onChangeQuery(o,!0),this.setState({labelBrowserVisible:!1})},this.onChangeQuery=(o,c)=>{const{query:g,onChange:p,onRunQuery:v}=this.props;if(p){const x={...g,expr:o};p(x),c&&v&&v()}},this.onClickChooserButton=()=>{this.setState(o=>({labelBrowserVisible:!o.labelBrowserVisible})),(0,D.ff)("user_grafana_prometheus_metrics_browser_clicked",{editorMode:this.state.labelBrowserVisible?"metricViewClosed":"metricViewOpen",app:this.props?.app??""})},this.onClickHintFix=()=>{const{datasource:o,query:c,onChange:g,onRunQuery:p}=this.props,{hint:v}=this.state;v?.fix?.action&&g(o.modifyQuery(c,v.fix.action)),p()},this.onUpdateLanguage=()=>{const{datasource:{languageProvider:o}}=this.props,{metrics:c}=o;c&&this.setState({syntaxLoaded:!0})},this.onTypeahead=async o=>{const{datasource:{languageProvider:c}}=this.props;if(!c)return{suggestions:[]};const{history:g}=this.props,{prefix:p,text:v,value:x,wrapperClasses:S,labelKey:T}=o;return await c.provideCompletionItems({text:v,value:x,prefix:p,wrapperClasses:S,labelKey:T},{history:g})},this.plugins=[(0,ae.h)(),(0,B.Z)({onlyIn:o=>o.type==="code_block",getSyntax:o=>"promql"},{...U.languages,promql:this.props.datasource.languageProvider.syntax})],this.state={labelBrowserVisible:!1,syntaxLoaded:!1,hint:null}}componentDidMount(){this.props.datasource.languageProvider&&this.refreshMetrics(),this.refreshHint()}componentWillUnmount(){this.languageProviderInitializationPromise&&this.languageProviderInitializationPromise.cancel()}componentDidUpdate(l){const{data:u,datasource:{languageProvider:o},range:c}=this.props;o!==l.datasource.languageProvider&&this.setState({syntaxLoaded:!1});const g=this.rangeChangedToRefresh(c,l.range);(o!==l.datasource.languageProvider||g)&&this.refreshMetrics(),u&&l.data&&l.data.series!==u.series&&this.refreshHint()}rangeChangedToRefresh(l,u){if(l&&u){const o=(0,Q.o8)(l.from.valueOf())===(0,Q.o8)(u.from.valueOf()),c=(0,Q.o8)(l.to.valueOf())===(0,Q.o8)(u.to.valueOf());return!(o&&c)}return!1}render(){const{datasource:l,datasource:{languageProvider:u},query:o,ExtraFieldElement:c,history:g=[],theme:p}=this.props,{labelBrowserVisible:v,syntaxLoaded:x,hint:S}=this.state,T=u.metrics.length>0,_=Me(l.lookupsDisabled,x,T),te=!(x&&T);return a.createElement(G.G,{storageKey:ye,defaultValue:[]},(ce,ge,V)=>a.createElement(a.Fragment,null,a.createElement("div",{className:"gf-form-inline gf-form-inline--xs-view-flex-column flex-grow-1","data-testid":this.props["data-testid"]},a.createElement("button",{className:"gf-form-label query-keyword pointer",onClick:this.onClickChooserButton,disabled:te,type:"button"},_,a.createElement(ee.J,{name:v?"angle-down":"angle-right"})),a.createElement("div",{className:"gf-form gf-form--grow flex-shrink-1 min-width-15"},a.createElement(pe,{languageProvider:u,history:g,onChange:this.onChangeQuery,onRunQuery:this.props.onRunQuery,initialValue:o.expr??"",placeholder:"Enter a PromQL query\u2026"}))),v&&a.createElement("div",{className:"gf-form"},a.createElement(K,{languageProvider:u,onChange:this.onChangeLabelBrowser,lastUsedLabels:ce||[],storeLastUsedLabels:ge,deleteLastUsedLabels:V})),c,S?a.createElement("div",{className:"query-row-break"},a.createElement("div",{className:"prom-query-field-info text-warning"},S.label," ",S.fix?a.createElement("button",{type:"button",className:(0,b.cx)((0,Z.gN)(p),"text-link","muted"),onClick:this.onClickHintFix},S.fix.label):null)):null))}}const m=(0,J.HE)(fe)},8366:(Te,ne,s)=>{"use strict";s.d(ne,{QG:()=>je,vQ:()=>Je});var b=s(82897),U=s(52998),a=s(66111),re=s(85850),D=s(65583),ae=s(59980),B=s(40003),ee=s(12877),Z=s(53208),J=s(9471),G=s(71735),F=s(90801),E=s(59724),Q=s(72097),C=s.n(Q),W=s(206),M=s(47891),$=s(52666),k=s(67483),w=s(22069),P=s(32689),O=s(54899),L=s(19985),j=s(61860),X=s(55935),de=s(44737),le=s(19349),Se=s(28674),K=s(46063),ie=s(47694),ve=s(41564),pe=s(26418),Ce=s(68668),ye=s(46967),Me=s(79969);function Re(y){const e=y.annotation,t=y.onAnnotationChange,r={expr:e.expr,refId:e.name,interval:e.step};return a.createElement(a.Fragment,null,a.createElement(pe.EditorRows,null,a.createElement(Me.j,{...y,query:r,showExplain:!1,onChange:d=>{t({...e,expr:d.expr})}}),a.createElement(pe.EditorRow,null,a.createElement(pe.EditorField,{label:"Min step",tooltip:a.createElement(a.Fragment,null,"An additional lower limit for the step parameter of the Prometheus query and for the"," ",a.createElement("code",null,"$__interval")," and ",a.createElement("code",null,"$__rate_interval")," variables.")},a.createElement(Ce.H,{type:"text","aria-label":"Set lower limit for the step parameter",placeholder:"auto",minWidth:10,onCommitChange:d=>{t({...e,step:d.currentTarget.value})},defaultValue:r.interval})))),a.createElement(pe.Space,{v:.5}),a.createElement(pe.EditorRow,null,a.createElement(pe.EditorField,{label:"Title",tooltip:"Use either the name or a pattern. For example, {{instance}} is replaced with label value for the label instance."},a.createElement(ye.I,{type:"text",placeholder:"{{alertname}}",value:e.titleFormat,onChange:d=>{t({...e,titleFormat:d.currentTarget.value})}})),a.createElement(pe.EditorField,{label:"Tags"},a.createElement(ye.I,{type:"text",placeholder:"label1,label2",value:e.tagKeys,onChange:d=>{t({...e,tagKeys:d.currentTarget.value})}})),a.createElement(pe.EditorField,{label:"Text",tooltip:"Use either the name or a pattern. For example, {{instance}} is replaced with label value for the label instance."},a.createElement(ye.I,{type:"text",placeholder:"{{instance}}",value:e.textFormat,onChange:d=>{t({...e,textFormat:d.currentTarget.value})}})),a.createElement(pe.EditorField,{label:"Series value as timestamp",tooltip:"The unit of timestamp is milliseconds. If the unit of the series value is seconds, multiply its range vector by 1000."},a.createElement(pe.EditorSwitch,{value:e.useValueForTime,onChange:d=>{t({...e,useValueForTime:d.currentTarget.value})}}))))}var fe=s(36784),m=s(51649),i=s(44332);class l{constructor(e,t){this.datasource=e,this.query=t,this.datasource=e,this.query=t,this.range=(0,le.$t)().timeRange()}process(){const e=/^label_names\(\)\s*$/,t=/^label_values\((?:(.+),\s*)?([a-zA-Z_][a-zA-Z0-9_]*)\)\s*$/,r=/^metrics\((.+)\)\s*$/,d=/^query_result\((.+)\)\s*$/;if(this.query.match(e))return this.datasource.getTagKeys();const h=this.query.match(t);if(h)return h[1]?this.labelValuesQuery(h[2],h[1]):this.labelValuesQuery(h[2]);const f=this.query.match(r);if(f)return this.metricNameQuery(f[1]);const R=this.query.match(d);return R?(0,D.n)(this.queryResultQuery(R[1])):["label_values()","metrics()","query_result()"].includes(this.query)?Promise.resolve([]):this.metricNameAndLabelsQuery(this.query)}labelValuesQuery(e,t){const r=(0,m.jj)(this.range.from,!1),d=(0,m.jj)(this.range.to,!0),n={...t&&{"match[]":t},start:r.toString(),end:d.toString()};if(!t||this.datasource.hasLabelsMatchAPISupport()){const h=`/api/v1/label/${e}/values`;return this.datasource.metadataRequest(h,n).then(f=>(0,b.map)(f.data.data,R=>({text:R})))}else{const h="/api/v1/series";return this.datasource.metadataRequest(h,n).then(f=>{const R=(0,b.map)(f.data.data,N=>N[e]||"").filter(N=>N!=="");return(0,b.uniq)(R).map(N=>({text:N,expandable:!0}))})}}metricNameQuery(e){const t=(0,m.jj)(this.range.from,!1),r=(0,m.jj)(this.range.to,!0),d={start:t.toString(),end:r.toString()},n="/api/v1/label/__name__/values";return this.datasource.metadataRequest(n,d).then(h=>(0,b.chain)(h.data.data).filter(f=>new RegExp(e).test(f)).map(f=>({text:f,expandable:!0})).value())}queryResultQuery(e){const t=(0,m.jj)(this.range.to,!0),r={expr:e};return this.datasource.performInstantQuery(r,t).pipe((0,J.U)(d=>{switch(d.data.data.resultType){case"scalar":case"string":return[{text:d.data.data.result[1]||"",expandable:!1}];case"vector":return(0,b.map)(d.data.data.result,n=>{let h=n.metric.__name__||"";return delete n.metric.__name__,h+="{"+(0,b.map)(n.metric,(f,R)=>R+'="'+f+'"').join(",")+"}",h+=" "+n.value[1]+" "+n.value[0]*1e3,{text:h,expandable:!0}});default:throw Error(`Unknown/Unhandled result type: [${d.data.data.resultType}]`)}}))}metricNameAndLabelsQuery(e){const t=(0,m.jj)(this.range.from,!1),r=(0,m.jj)(this.range.to,!0),d={"match[]":e,start:t.toString(),end:r.toString()},n="/api/v1/series",h=this;return this.datasource.metadataRequest(n,d).then(f=>(0,b.map)(f.data.data,R=>({text:h.datasource.getOriginalMetricName(R),expandable:!0})))}}const u=20;function o(y,e,t){const r=[];if(y.trim().match(/^\w+_bucket$|^\w+_bucket{.*}$/)){const n="Selected metric has buckets.";r.push({type:"HISTOGRAM_QUANTILE",label:n,fix:{label:"Consider calculating aggregated quantile by adding histogram_quantile().",action:{type:"ADD_HISTOGRAM_QUANTILE",query:y}}})}if(y.indexOf("rate(")===-1&&y.indexOf("increase(")===-1){const n=y.match(/\b(\w+_(total|sum|count))\b/);let h=n?n[1]:"";const f=t?.languageProvider?.metricsMetadata;let R=!1;if(f&&(h=Array.from(y.matchAll(/\$?[a-zA-Z_:][a-zA-Z0-9_:]*/g)).map(([Y])=>Y).filter(Y=>!Y.startsWith("$")).flatMap(Y=>Y.split(":")).find(Y=>{const A=f[Y];return A&&A.type.toLowerCase()==="counter"?(R=!0,!0):!1})??""),h){const N=y.trim().match(/^\w+$|^\w+{.*}$/);let A=`Selected metric ${R?"is":"looks like"} a counter.`,oe;N?oe={label:"Consider calculating rate of counter by adding rate().",action:{type:"ADD_RATE",query:y}}:A=`${A} Consider calculating rate of counter by adding rate().`,r.push({type:"APPLY_RATE",label:A,fix:oe})}}if(t&&t.ruleMappings){const n=t.ruleMappings,h=Object.keys(n).reduce((f,R)=>y.search(R)>-1?{...f,[R]:n[R]}:f,{});if((0,b.size)(h)>0){const f="Query contains recording rules.";r.push({type:"EXPAND_RULES",label:f,fix:{label:"Expand rules",action:{type:"EXPAND_RULES",query:y,options:h}}})}}return e&&e.length>=u&&y.trim().match(/^\w+$/)&&r.push({type:"ADD_SUM",label:"Many time series results returned.",fix:{label:"Consider aggregating with sum().",action:{type:"ADD_SUM",query:y,preventSubmit:!0}}}),r}function c(y){const e=[];return y.directUrl.includes("/loki")&&!y.languageProvider.metrics.length&&e.push({label:"Using Loki as a Prometheus data source is no longer supported. You must use the Loki data source for your Loki instance.",type:"INFO"}),y.lookupsDisabled&&e.push({label:"Labels and metrics lookup was disabled in data source settings.",type:"INFO"}),e}var g=s(24509),p=s(30749),v=s(41818),x=s(35645);function S(y,e,t){const{app:r,targets:d}=e;if(!(r===W.zj.Dashboard||r===W.zj.PanelViewer))for(const n of d)(0,v.ff)("grafana_prometheus_query_executed",{app:r,grafana_version:x.v.buildInfo.version,has_data:y.data.some(h=>h.length>0),has_error:y.error!==void 0,expr:n.expr,format:n.format,instant:n.instant,range:n.range,exemplar:n.exemplar,hinting:n.hinting,interval:n.interval,intervalFactor:n.intervalFactor,utcOffsetSec:n.utcOffsetSec,legend:n.legendFormat,valueWithRefId:n.valueWithRefId,requestId:e.requestId,showingGraph:n.showingGraph,showingTable:n.showingTable,editor_mode:n.editorMode,simultaneously_sent_query_count:d.length,time_range_from:e?.range?.from?.toISOString(),time_range_to:e?.range?.to?.toISOString(),time_taken:Date.now()-t.getTime()})}var T=s(37462),_=s(49372),te=s(48976),ce=s(20308),ge=s(11543),V=s(81764),I=s(8581),z=s(97379);const se=/^label_names\(\)\s*$/,Ee=/^label_values\((?:(.+),\s*)?([a-zA-Z_][a-zA-Z0-9_]*)\)\s*$/,Le=/^metrics\((.+)\)\s*$/,Oe=/^query_result\((.+)\)\s*$/;function Ue(y){if(typeof y!="string")return y;const e={refId:"PrometheusDatasource-VariableQuery",qryType:T.jo.LabelNames},t=y.match(se);if(t)return{...e,qryType:T.jo.LabelNames};const r=y.match(Ee);if(r){const h=r[2],f=r[1];return f?{...e,qryType:T.jo.LabelValues,label:h,metric:f}:{...e,qryType:T.jo.LabelValues,label:h}}const d=y.match(Le);if(d)return{...e,qryType:T.jo.MetricNames,metric:d[1]};const n=y.match(Oe);return n?{...e,qryType:T.jo.VarQueryResult,varQuery:n[1]}:!t&&!r&&!d&&!n?{...e,qryType:T.jo.SeriesQuery,seriesQuery:y}:e}function we(y){switch(y.qryType){case T.jo.LabelNames:return"label_names()";case T.jo.LabelValues:return y.metric?`label_values(${y.metric},${y.label})`:`label_values(${y.label})`;case T.jo.MetricNames:return`metrics(${y.metric})`;case T.jo.VarQueryResult:return`query_result(${Ke(y.varQuery)})`;case T.jo.SeriesQuery:return""+y.seriesQuery}return""}function Ke(y){return y?y.replace(/[\r\n]+/gm,""):""}const _e=[{label:"Label names",value:T.jo.LabelNames},{label:"Label values",value:T.jo.LabelValues},{label:"Metrics",value:T.jo.MetricNames},{label:"Query result",value:T.jo.VarQueryResult},{label:"Series query",value:T.jo.SeriesQuery}],ze="PrometheusVariableQueryEditor-VariableQuery",He=({onChange:y,query:e,datasource:t})=>{const[r,d]=(0,a.useState)(void 0),[n,h]=(0,a.useState)(""),[f,R]=(0,a.useState)(""),[N,Y]=(0,a.useState)(""),[A,oe]=(0,a.useState)(""),[H,me]=(0,a.useState)([]);(0,a.useEffect)(()=>{if(!e)return;const q=Ge(e);d(q.qryType),h(q.label??""),R(q.metric??""),Y(q.varQuery??""),oe(q.seriesQuery??""),q.label&&me([{label:q.label,value:q.label}])},[e]),(0,a.useEffect)(()=>{r===T.jo.LabelValues&&t.getTagKeys().then(q=>{me(q.map(({text:Pe})=>({label:Pe,value:Pe})))})},[t,r]);const ue=q=>{const be=we({qryType:q,label:n,metric:f,varQuery:N,seriesQuery:A,refId:"PrometheusVariableQueryEditor-VariableQuery"});y({query:be,refId:ze})},Ae=q=>{d(q.value),q.value===T.jo.LabelNames&&ue(q.value)},De=q=>{h(q.value??"")},Ie=q=>{R(q.currentTarget.value)},Fe=q=>{Y(q.currentTarget.value)},Qe=q=>{oe(q.currentTarget.value)},xe=()=>{(r===T.jo.LabelNames||r===T.jo.LabelValues&&n||r===T.jo.MetricNames&&f||r===T.jo.VarQueryResult&&N||r===T.jo.SeriesQuery&&A)&&ue(r)};return a.createElement(ge.Z,null,a.createElement(V._,{label:"Query Type",labelWidth:20,tooltip:a.createElement("div",null,"The Prometheus data source plugin provides the following query types for template variables.")},a.createElement(I.Ph,{placeholder:"Select query type","aria-label":"Query type",onChange:Ae,onBlur:xe,value:r,options:_e,width:25})),r===T.jo.LabelValues&&a.createElement(a.Fragment,null,a.createElement(V._,{label:"Label",labelWidth:20,required:!0,tooltip:a.createElement("div",null,"Returns a list of label values for the label name in all metrics unless the metric is specified.")},a.createElement(I.Ph,{"aria-label":"label-select",onChange:De,onBlur:xe,value:n,options:H,width:25,allowCustomValue:!0})),a.createElement(V._,{label:"Metric",labelWidth:20,tooltip:a.createElement("div",null,"Optional: returns a list of label values for the label name in the specified metric.")},a.createElement(ye.I,{type:"text","aria-label":"Metric selector",placeholder:"Optional metric selector",value:f,onChange:Ie,onBlur:xe,width:25}))),r===T.jo.MetricNames&&a.createElement(a.Fragment,null,a.createElement(V._,{label:"Metric Regex",labelWidth:20,tooltip:a.createElement("div",null,"Returns a list of metrics matching the specified metric regex.")},a.createElement(ye.I,{type:"text","aria-label":"Metric selector",placeholder:"Metric Regex",value:f,onChange:Ie,onBlur:xe,width:25}))),r===T.jo.VarQueryResult&&a.createElement(a.Fragment,null,a.createElement(V._,{label:"Query",labelWidth:20,tooltip:a.createElement("div",null,"Returns a list of Prometheus query results for the query. This can include Prometheus functions, i.e. sum(go_goroutines).")},a.createElement(z.K,{type:"text","aria-label":"Prometheus Query",placeholder:"Prometheus Query",value:N,onChange:Fe,onBlur:xe,cols:100}))),r===T.jo.SeriesQuery&&a.createElement(a.Fragment,null,a.createElement(V._,{label:"Series Query",labelWidth:20,tooltip:a.createElement("div",null,'Enter enter a metric with labels, only a metric or only labels, i.e. go_goroutines{instance="localhost:9090"}, go_goroutines, or {instance="localhost:9090"}. Returns a list of time series associated with the entered data.')},a.createElement(ye.I,{type:"text","aria-label":"Series Query",placeholder:"Series Query",value:A,onChange:Qe,onBlur:xe,width:100}))))};function Ge(y){return typeof y=="string"?Ue(y):y.query?Ue(y.query):y}class ke extends te.Mg{constructor(e,t=(0,ce.J)(),r=(0,le.$t)()){super(),this.datasource=e,this.templateSrv=t,this.timeSrv=r,this.editor=He,this.query=this.query.bind(this)}query(e){let t;if(typeof e.targets[0]=="string"?t=e.targets[0]:t=e.targets[0].query,!t)return(0,ae.of)({data:[]});const r={...e.scopedVars,__interval:{text:this.datasource.interval,value:this.datasource.interval},__interval_ms:{text:M.intervalToMs(this.datasource.interval),value:M.intervalToMs(this.datasource.interval)},...this.datasource.getRangeScopedVars(this.timeSrv.timeRange())},d=this.templateSrv.replace(t,r,this.datasource.interpolateQueryExpr),n=new l(this.datasource,d);return(0,_.D)(n.process()).pipe((0,J.U)(f=>({data:f})))}}const $e="60s",Ze=["api/v1/query","api/v1/query_range","api/v1/series","api/v1/labels"],je="-Instant";class Je extends w.CK{constructor(e,t=(0,Se.J)(),r=(0,le.$t)(),d){super(e),this.templateSrv=t,this.timeSrv=r,this.metricsNameCache=new U.Z({max:10}),this.init=async()=>{this.loadRules(),this.exemplarsAvailable=await this.areExemplarsAvailable()},this.prepareTargets=(n,h,f)=>{const R=[],N=[],Y=(0,b.cloneDeep)(n.targets);for(const A of Y){if(!A.expr||A.hide)continue;const oe=this.languageProvider.histogramMetrics.find(H=>A.expr.includes(H));if(n.app===W.zj.Explore&&A.range===A.instant){const H=(0,b.cloneDeep)(A);H.format="table",H.instant=!0,H.range=!1,H.valueWithRefId=!0,delete H.maxDataPoints;const me=(0,b.cloneDeep)(A);if(me.format="time_series",me.instant=!1,H.range=!0,A.exemplar){if(!oe||oe&&!N.some(ue=>ue.expr.includes(oe))){const ue=(0,b.cloneDeep)(A);ue.instant=!1,R.push(this.createQuery(ue,n,h,f)),N.push(ue)}H.exemplar=!1,me.exemplar=!1}N.push(H,me),R.push(this.createQuery(H,n,h,f),this.createQuery(me,n,h,f))}else if(A.instant&&n.app===W.zj.Explore){const H=(0,b.cloneDeep)(A);H.format="table",R.push(this.createQuery(H,n,h,f)),N.push(H)}else{if(A.exemplar&&!A.instant){if(!oe||oe&&!N.some(H=>H.expr.includes(oe))){const H=(0,b.cloneDeep)(A);R.push(this.createQuery(H,n,h,f)),N.push(H)}A.exemplar=!1}R.push(this.createQuery(A,n,h,f)),N.push(A)}}return{queries:R,activeTargets:N}},this.handleErrors=(n,h)=>{const f={message:n&&n.statusText||"Unknown error during query transaction. Please check JS console logs.",refId:h.refId};return n.data?typeof n.data=="string"?f.message=n.data:n.data.error&&(f.message=(0,X.Xh)(n.data.error)):n.message?f.message=n.message:typeof n=="string"&&(f.message=n),f.status=n.status,f.statusText=n.statusText,f},this.processAnnotationResponse=(n,h)=>{const f=(0,P.z1)({data:h}).data;if(!f||!f.length)return[];const R=n.annotation,{tagKeys:N="",titleFormat:Y="",textFormat:A=""}=R,oe=M.intervalToSeconds(R.step||$e)*1e3,H=N.split(","),me=[];for(const ue of f){if(ue.fields.length===0)continue;const Ae=ue.fields[0],De=ue.fields[1],Ie=De?.labels||{},Fe=Object.keys(Ie).filter(he=>H.includes(he)).map(he=>Ie[he]),Qe=[];let xe=0;De.values.forEach(he=>{let Ve,Ne;const qe=Ae.values[xe];n.annotation.useValueForTime?(Ve=Math.floor(parseFloat(he)),Ne=1):(Ve=Math.floor(parseFloat(qe)),Ne=parseFloat(he)),xe++,Qe.push([Ve,Ne])});const Pe=Qe.filter(he=>he[1]>0).map(he=>he[0]);let be=null;for(const he of Pe){if(be&&(be.timeEnd??0)+oe>=he){be.timeEnd=he;continue}be&&me.push(be),be={time:he,timeEnd:he,annotation:R,title:(0,i.W)(Y,Ie),tags:Fe,text:(0,i.W)(A,Ie)}}be&&(be.timeEnd=Pe[Pe.length-1],me.push(be))}return me},this.type="prometheus",this.subType=K.T8.Prometheus,this.rulerEnabled=!1,this.id=e.id,this.url=e.url,this.access=e.access,this.basicAuth=e.basicAuth,this.withCredentials=e.withCredentials,this.interval=e.jsonData.timeInterval||"15s",this.queryTimeout=e.jsonData.queryTimeout,this.httpMethod=e.jsonData.httpMethod||"GET",this.directUrl=e.jsonData.directUrl??this.url,this.exemplarTraceIdDestinations=e.jsonData.exemplarTraceIdDestinations,this.hasIncrementalQuery=e.jsonData.incrementalQuerying??!1,this.ruleMappings={},this.languageProvider=d??new fe.ZP(this),this.lookupsDisabled=e.jsonData.disableMetricsLookup??!1,this.customQueryParameters=new URLSearchParams(e.jsonData.customQueryParameters),this.datasourceConfigurationPrometheusFlavor=e.jsonData.prometheusType,this.datasourceConfigurationPrometheusVersion=e.jsonData.prometheusVersion,this.defaultEditor=e.jsonData.defaultEditor,this.variables=new ke(this,this.templateSrv,this.timeSrv),this.exemplarsAvailable=!0,this.cacheLevel=e.jsonData.cacheLevel??T.x3.Low,this.cache=new g.tQ(e.jsonData.incrementalQueryOverlapWindow??g.Ji),this.annotations={QueryEditor:Re}}getQueryDisplayText(e){return e.expr}hasLabelsMatchAPISupport(){return this._isDatasourceVersionGreaterOrEqualTo("2.24.0",K.T8.Prometheus)||this._isDatasourceVersionGreaterOrEqualTo("2.0.0",K.T8.Mimir)||this._isDatasourceVersionGreaterOrEqualTo("1.11.0",K.T8.Cortex)||this._isDatasourceVersionGreaterOrEqualTo("0.18.0",K.T8.Thanos)}_isDatasourceVersionGreaterOrEqualTo(e,t){return!this.datasourceConfigurationPrometheusVersion||!this.datasourceConfigurationPrometheusFlavor||t!==this.datasourceConfigurationPrometheusFlavor?!1:C().gte(this.datasourceConfigurationPrometheusVersion,e)}_addTracingHeaders(e,t){e.headers={},this.access==="proxy"&&(e.headers["X-Dashboard-UID"]=t.dashboardUID,e.headers["X-Panel-Id"]=t.panelId)}_request(e,t,r={}){if(this.access==="direct"){const h=new Error("Browser access mode in the Prometheus datasource is no longer available. Switch to server access mode.");return(0,re._)(()=>h)}t=t||{};for(const[h,f]of this.customQueryParameters)t[h]==null&&(t[h]=f);let d=this.url+e;e.startsWith(`/api/datasources/uid/${this.uid}`)&&(d=e);const n=(0,b.defaults)(r,{url:d,method:this.httpMethod,headers:{}});return n.method==="GET"?t&&Object.keys(t).length&&(n.url=n.url+(n.url.search(/\?/)>=0?"&":"?")+Object.entries(t).map(([h,f])=>`${encodeURIComponent(h)}=${encodeURIComponent(f)}`).join("&")):(n.headers["Content-Type"]="application/x-www-form-urlencoded",n.data=t),(this.basicAuth||this.withCredentials)&&(n.withCredentials=!0),this.basicAuth&&(n.headers.Authorization=this.basicAuth),(0,O.i)().fetch(n)}async importFromAbstractQueries(e){return e.map(t=>this.languageProvider.importFromAbstractQuery(t))}async exportToAbstractQueries(e){return e.map(t=>this.languageProvider.exportToAbstractQuery(t))}async metadataRequest(e,t={},r){if(Ze.some(d=>e.includes(d)))try{return await(0,D.n)(this._request(`/api/datasources/uid/${this.uid}/resources${e}`,t,{method:this.httpMethod,hideFromInspector:!0,showErrorAlert:!1,...r}))}catch(d){if(this.httpMethod==="POST"&&(0,O.kW)(d)&&(d.status===405||d.status===400))console.warn("Couldn't use configured POST HTTP method for this request. Trying to use GET method instead.");else throw d}return await(0,D.n)(this._request(`/api/datasources/uid/${this.uid}/resources${e}`,t,{method:"GET",hideFromInspector:!0,...r}))}interpolateQueryExpr(e=[],t){if(!t.multi&&!t.includeAll)return Be(e);if(typeof e=="string")return We(e);const r=e.map(d=>We(d));return r.length===1?r[0]:"("+r.join("|")+")"}targetContainsTemplate(e){return this.templateSrv.containsTemplate(e.expr)}shouldRunExemplarQuery(e,t){if(e.exemplar){const r=this.languageProvider.histogramMetrics.find(h=>e.expr.includes(h)),d=t.targets.findIndex(h=>h.refId===e.refId),n=t.targets.slice(0,d).filter(h=>!h.hide);return!!(!r||r&&!n.some(h=>h.expr.includes(r)))}return!1}processTargetV2(e,t){const r=[],d={...e,exemplar:this.shouldRunExemplarQuery(e,t),requestId:t.panelId+e.refId,utcOffsetSec:this.timeSrv.timeRange().to.utcOffset()*60};return e.instant&&e.range?r.push({...d,refId:d.refId,instant:!1},{...d,refId:d.refId+je,range:!1}):r.push(d),r}query(e){if(this.access==="proxy"){let t,r;this.hasIncrementalQuery?(r=this.cache.requestInfo(e,this.interpolateString.bind(this)),t=r.requests[0]):t=e;const d=t.targets.map(h=>this.processTargetV2(h,t)),n=new Date;return super.query({...t,targets:d.flat()}).pipe((0,J.U)(h=>{const f={...h,data:this.cache.procFrames(e,r,h.data)};return(0,p.n)(f,e,{exemplarTraceIdDestinations:this.exemplarTraceIdDestinations})}),(0,G.b)(h=>{S(h,e,n)}))}else{const t=(0,m.jj)(e.range.from,!1),r=(0,m.jj)(e.range.to,!0),{queries:d,activeTargets:n}=this.prepareTargets(e,t,r);return!d||!d.length?(0,ae.of)({data:[],state:$.Gu.Done}):e.app===W.zj.Explore?this.exploreQuery(d,n,r):this.panelsQuery(d,n,r,e.requestId,e.scopedVars)}}exploreQuery(e,t,r){let d=e.length;const n=e.map((h,f)=>{const R=t[f],N=(0,B.z)((0,G.b)(()=>d--),(0,F.h)(Y=>!Y.cancelled),(0,J.U)(Y=>({data:(0,p.vs)(Y,{query:h,target:R,responseListLength:e.length,exemplarTraceIdDestinations:this.exemplarTraceIdDestinations}),key:h.requestId,state:d===0?$.Gu.Done:$.Gu.Loading})));return this.runQuery(h,r,N)});return(0,ee.T)(...n)}panelsQuery(e,t,r,d,n){const h=e.map((f,R)=>{const N=t[R],Y=(0,B.z)((0,F.h)(A=>!A.cancelled),(0,J.U)(A=>(0,p.vs)(A,{query:f,target:N,responseListLength:e.length,scopedVars:n,exemplarTraceIdDestinations:this.exemplarTraceIdDestinations})));return this.runQuery(f,r,Y)});return(0,Z.D)(h).pipe((0,J.U)(f=>({data:f.reduce((N,Y)=>[...N,...Y],[]),key:d,state:$.Gu.Done})))}runQuery(e,t,r){return e.instant?this.performInstantQuery(e,t).pipe(r):e.exemplar?this.getExemplars(e).pipe((0,E.K)(()=>(0,ae.of)({data:[],state:$.Gu.Done})),r):this.performTimeSeriesQuery(e,e.start,e.end).pipe(r)}createQuery(e,t,r,d){const n={hinting:e.hinting,instant:e.instant,exemplar:e.exemplar,step:0,expr:"",refId:e.refId,start:0,end:0},h=Math.ceil(d-r);let f=M.intervalToSeconds(t.interval);const R=M.intervalToSeconds(this.templateSrv.replace(e.interval||t.interval,t.scopedVars)),N=e.interval?M.intervalToSeconds(this.templateSrv.replace(e.interval,t.scopedVars)):M.intervalToSeconds(this.interval),Y=e.intervalFactor||1,A=this.adjustInterval(f,R,h,Y);let oe={...t.scopedVars,...this.getRangeScopedVars(t.range),...this.getRateIntervalScopedVariable(A,N)};f!==A&&(f=A,oe=Object.assign({},t.scopedVars,{__interval:{text:f+"s",value:f+"s"},__interval_ms:{text:f*1e3,value:f*1e3},...this.getRateIntervalScopedVariable(f,N),...this.getRangeScopedVars(t.range)})),n.step=f;let H=e.expr;H=this.enhanceExprWithAdHocFilters(H),n.expr=this.templateSrv.replace(H,oe,this.interpolateQueryExpr);const me=Xe(r,d,n.step,this.timeSrv.timeRange().to.utcOffset()*60);return n.start=me.start,n.end=me.end,this._addTracingHeaders(n,t),n}getRateIntervalScopedVariable(e,t){t===0&&(t=15);const r=Math.max(e+t,4*t);return{__rate_interval:{text:r+"s",value:r+"s"}}}adjustInterval(e,t,r,d){let n=r/11e3;return n>1&&(n=Math.ceil(n)),Math.max(e*d,t,n)}performTimeSeriesQuery(e,t,r){if(t>r)throw{message:"Invalid time range"};const d="/api/v1/query_range",n={query:e.expr,start:t,end:r,step:e.step};return this.queryTimeout&&(n.timeout=this.queryTimeout),this._request(d,n,{requestId:e.requestId,headers:e.headers}).pipe((0,E.K)(h=>h.cancelled?(0,ae.of)(h):(0,re._)(this.handleErrors(h,e))))}performInstantQuery(e,t){const r="/api/v1/query",d={query:e.expr,time:t};return this.queryTimeout&&(d.timeout=this.queryTimeout),this._request(`/api/datasources/uid/${this.uid}/resources${r}`,d,{requestId:e.requestId,headers:e.headers}).pipe((0,E.K)(n=>n.cancelled?(0,ae.of)(n):(0,re._)(this.handleErrors(n,e))))}metricFindQuery(e){if(!e)return Promise.resolve([]);const t={__interval:{text:this.interval,value:this.interval},__interval_ms:{text:M.intervalToMs(this.interval),value:M.intervalToMs(this.interval)},...this.getRangeScopedVars(this.timeSrv.timeRange())},r=this.templateSrv.replace(e,t,this.interpolateQueryExpr);return new l(this,r).process()}getRangeScopedVars(e=this.timeSrv.timeRange()){const t=e.to.diff(e.from),r=Math.round(t/1e3);return{__range_ms:{text:t,value:t},__range_s:{text:r,value:r},__range:{text:r+"s",value:r+"s"}}}async annotationQuery(e){if(this.access==="direct"){const h=new Error("Browser access mode in the Prometheus datasource is no longer available. Switch to server access mode.");return Promise.reject(h)}const t=e.annotation,{expr:r=""}=t;if(!r)return Promise.resolve([]);const d=e.annotation.step||$e,n={expr:r,range:!0,instant:!1,exemplar:!1,interval:d,refId:"X",datasource:this.getRef()};return await(0,D.n)((0,O.i)().fetch({url:"/api/ds/query",method:"POST",headers:this.getRequestHeaders(),data:{from:((0,m.jj)(e.range.from,!1)*1e3).toString(),to:((0,m.jj)(e.range.to,!0)*1e3).toString(),queries:[this.applyTemplateVariables(n,{})]},requestId:`prom-query-${t.name}`}).pipe((0,J.U)(h=>this.processAnnotationResponse(e,h.data))))}getExemplars(e){const t="/api/v1/query_exemplars";return this._request(t,{query:e.expr,start:e.start.toString(),end:e.end.toString()},{requestId:e.requestId,headers:e.headers})}async getTagKeys(e){if(e?.series){const t=await Promise.all(e.series.map(n=>this.languageProvider.fetchSeriesLabels(n)));let r=[];return t.map(n=>r=r.concat(Object.keys(n))),[...new Set(r)].map(n=>({text:n}))}else{const t=this.getTimeRangeParams();return(await this.metadataRequest("/api/v1/labels",t))?.data?.data?.map(d=>({text:d}))??[]}}async getTagValues(e={}){const t=this.getTimeRangeParams();return(await this.metadataRequest(`/api/v1/label/${e.key}/values`,t))?.data?.data?.map(d=>({text:d}))??[]}async getBuildInfo(){try{return await(0,de.WG)({url:this.url,name:this.name,type:"prometheus"})}catch{return}}getBuildInfoMessage(e){const t=a.createElement(L.C,{color:"green",icon:"check",text:"Ruler API enabled"}),r=a.createElement(L.C,{color:"orange",icon:"exclamation-triangle",text:"Ruler API not enabled"}),d=a.createElement(j.u,{placement:"top",content:"Prometheus does not allow editing rules, connect to either a Mimir or Cortex datasource to manage alerts via Grafana."},a.createElement("div",null,a.createElement(L.C,{color:"red",icon:"exclamation-triangle",text:"Ruler API not supported"}))),n={[K.T8.Cortex]:"/public/app/plugins/datasource/prometheus/img/cortex_logo.svg",[K.T8.Mimir]:"/public/app/plugins/datasource/prometheus/img/mimir_logo.svg",[K.T8.Prometheus]:"/public/app/plugins/datasource/prometheus/img/prometheus_logo.svg",[K.T8.Thanos]:"/public/app/plugins/datasource/prometheus/img/thanos_logo.svg"},h={[K.T8.Cortex]:"blue",[K.T8.Mimir]:"orange",[K.T8.Prometheus]:"red",[K.T8.Thanos]:"purple"},f={[K.T8.Cortex]:"Cortex",[K.T8.Mimir]:"Mimir",[K.T8.Prometheus]:"Prometheus",[K.T8.Thanos]:"Thanos"},R=this.datasourceConfigurationPrometheusFlavor??e.application,N=a.createElement(L.C,{text:a.createElement("span",null,a.createElement("img",{style:{width:14,height:14,verticalAlign:"text-bottom"},src:n[R??K.T8.Prometheus],alt:""})," ",R?f[R]:"Unknown"),color:h[R??K.T8.Prometheus]});return a.createElement("div",{style:{display:"grid",gridTemplateColumns:"max-content max-content",rowGap:"0.5rem",columnGap:"2rem",marginTop:"1rem"}},a.createElement("div",null,"Type"),a.createElement("div",null,N),a.createElement(a.Fragment,null,a.createElement("div",null,"Ruler API"),e.application===K.T8.Prometheus&&a.createElement("div",null,d),e.application!==K.T8.Prometheus&&a.createElement("div",null,e.features.rulerApiEnabled?t:r)))}interpolateVariablesInQueries(e,t){let r=e;return e&&e.length&&(r=e.map(d=>({...d,datasource:this.getRef(),expr:this.enhanceExprWithAdHocFilters(this.templateSrv.replace(d.expr,t,this.interpolateQueryExpr)),interval:this.templateSrv.replace(d.interval,t)}))),r}getQueryHints(e,t){return o(e.expr??"",t,this)}getInitHints(){return c(this)}async loadRules(){try{const t=(await this.metadataRequest("/api/v1/rules",{},{showErrorAlert:!1})).data?.data?.groups;t&&(this.ruleMappings=Ye(t))}catch(e){console.log("Rules API is experimental. Ignore next error."),console.error(e)}}async areExemplarsAvailable(){try{return(await this.metadataRequest("/api/v1/query_exemplars",{query:"test",start:(0,k.CQ)().subtract(30,"minutes").valueOf().toString(),end:(0,k.CQ)().valueOf().toString()},{showErrorAlert:!1})).data.status==="success"}catch{return!1}}modifyQuery(e,t){let r=e.expr??"";switch(t.type){case"ADD_FILTER":{const{key:d,value:n}=t.options??{};d&&n&&(r=(0,ve.F)(r,d,n));break}case"ADD_FILTER_OUT":{const{key:d,value:n}=t.options??{};d&&n&&(r=(0,ve.F)(r,d,n,"!="));break}case"ADD_HISTOGRAM_QUANTILE":{r=`histogram_quantile(0.95, sum(rate(${r}[$__rate_interval])) by (le))`;break}case"ADD_RATE":{r=`rate(${r}[$__rate_interval])`;break}case"ADD_SUM":{r=`sum(${r.trim()}) by ($1)`;break}case"EXPAND_RULES":{t.options&&(r=(0,m.ll)(r,t.options));break}default:break}return{...e,expr:r}}getAdjustedInterval(){if(!ie.ZP.featureToggles.prometheusResourceBrowserCache)return this.getTimeRangeParams();const e=this.timeSrv.timeRange();return(0,m.wY)(this.cacheLevel,e)}getTimeRangeParams(){const e=this.timeSrv.timeRange();return{start:(0,m.jj)(e.from,!1).toString(),end:(0,m.jj)(e.to,!0).toString()}}getOriginalMetricName(e){return(0,p.nM)(e)}enhanceExprWithAdHocFilters(e){return this.templateSrv.getAdhocFilters(this.name).reduce((d,n)=>{const{key:h,operator:f}=n;let{value:R}=n;return(f==="=~"||f==="!~")&&(R=Be(R)),(0,ve.F)(d,h,R,f)},e)}filterQuery(e){return!(e.hide||!e.expr)}applyTemplateVariables(e,t){const r=(0,b.cloneDeep)(t);delete r.__interval,delete r.__interval_ms;const d=this.enhanceExprWithAdHocFilters(e.expr);return{...e,legendFormat:this.templateSrv.replace(e.legendFormat,r),expr:this.templateSrv.replace(d,r,this.interpolateQueryExpr),interval:this.templateSrv.replace(e.interval,r)}}getVariables(){return this.templateSrv.getVariables().map(e=>`$${e.name}`)}interpolateString(e){return this.templateSrv.replace(e,void 0,this.interpolateQueryExpr)}getDebounceTimeInMilliseconds(){switch(this.cacheLevel){case T.x3.Medium:return 600;case T.x3.High:return 1200;default:return 350}}getDaysToCacheMetadata(){switch(this.cacheLevel){case T.x3.Medium:return 7;case T.x3.High:return 30;default:return 1}}getCacheDurationInMinutes(){return(0,m.l3)(this.cacheLevel)}getDefaultQuery(e){const t={refId:"A",expr:"",range:!0,instant:!1};return e===W.zj.UnifiedAlerting?{...t,instant:!0,range:!1}:e===W.zj.Explore?{...t,instant:!0,range:!0}:t}}function Xe(y,e,t,r){const d=Math.floor((e+r)/t)*t-r,n=Math.floor((y+r)/t)*t-r;return{end:d,start:n}}function Ye(y){return y.reduce((e,t)=>t.rules.filter(r=>r.type==="recording").reduce((r,d)=>({...r,[d.name]:d.query}),e),{})}function Be(y){return typeof y=="string"?y.replace(/\\/g,"\\\\").replace(/'/g,"\\\\'"):y}function We(y){return typeof y=="string"?y.replace(/\\/g,"\\\\\\\\").replace(/[$^*{}\[\]\'+?.()|]/g,"\\\\$&"):y}},37285:(Te,ne,s)=>{"use strict";s.d(ne,{A:()=>Z,n:()=>J});var b=s(66111),U=s(26418),a=s(21899),re=s(4252),D=s(80522),ae=s(58439),B=s(19023),ee=s(45204);const Z="Fetch all series matching metric name and label filters.",J=b.memo(({query:G})=>{const F=(0,D._)(G||"").query,E={grammar:a.ZP,name:"promql"};return b.createElement(U.Stack,{gap:.5,direction:"column"},b.createElement(ae.B,{stepNumber:1,title:b.createElement(ee.U,{query:`${F.metric} ${re.Z.renderLabels(F.labels)}`,lang:E})},Z),b.createElement(B.V,{stepNumber:2,queryModeller:re.Z,query:F,lang:E}))});J.displayName="PromQueryBuilderExplained"},79969:(Te,ne,s)=>{"use strict";s.d(ne,{j:()=>ae});var b=s(9892),U=s(66111),a=s(72648),re=s(362),D=s(37285);function ae(ee){const{query:Z,datasource:J,range:G,onRunQuery:F,onChange:E,data:Q,app:C,showExplain:W}=ee,M=(0,a.wW)(B);return U.createElement("div",{className:M.wrapper},U.createElement(re.ZP,{datasource:J,query:Z,range:G,onRunQuery:F,onChange:E,history:[],data:Q,app:C}),W&&U.createElement(D.n,{query:Z.expr}))}const B=ee=>({wrapper:b.css`
      .gf-form {
        margin-bottom: 0;
      }
    `})},58439:(Te,ne,s)=>{"use strict";s.d(ne,{B:()=>D});var b=s(9892),U=s(66111),a=s(2631),re=s(72648);function D({title:B,stepNumber:ee,markdown:Z,children:J}){const G=(0,re.wW)(ae);return U.createElement("div",{className:G.box},ee!==void 0&&U.createElement("div",{className:G.stepNumber},ee),U.createElement("div",{className:G.boxInner},B&&U.createElement("div",{className:G.header},U.createElement("span",null,B)),U.createElement("div",{className:G.body},Z&&U.createElement("div",{dangerouslySetInnerHTML:{__html:(0,a.a)(Z)}}),J)))}const ae=B=>({box:(0,b.css)({background:B.colors.background.secondary,padding:B.spacing(1),borderRadius:B.shape.borderRadius(),position:"relative"}),boxInner:(0,b.css)({marginLeft:B.spacing(4)}),stepNumber:(0,b.css)({fontWeight:B.typography.fontWeightMedium,background:B.colors.secondary.main,width:"20px",height:"20px",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",position:"absolute",top:"10px",left:"11px",fontSize:B.typography.bodySmall.fontSize}),header:(0,b.css)({paddingBottom:B.spacing(.5),display:"flex",alignItems:"center",fontFamily:B.typography.fontFamilyMonospace}),body:(0,b.css)({color:B.colors.text.secondary,"p:last-child":{margin:0},a:{color:B.colors.text.link,textDecoration:"underline"}})})},19023:(Te,ne,s)=>{"use strict";s.d(ne,{V:()=>re});var b=s(66111),U=s(58439),a=s(45204);function re({query:D,queryModeller:ae,stepNumber:B,lang:ee,onMouseEnter:Z,onMouseLeave:J}){return b.createElement(b.Fragment,null,D.operations.map((G,F)=>{const E=ae.getOperationDef(G.id);if(!E)return`Operation ${G.id} not found`;const Q=E.renderer(G,E,"<expr>"),C=E.explainHandler?E.explainHandler(G,E):E.documentation??"no docs";return b.createElement("div",{key:F,onMouseEnter:()=>Z?.(G,F),onMouseLeave:()=>J?.(G,F)},b.createElement(U.B,{stepNumber:F+B,title:b.createElement(a.U,{query:Q,lang:ee}),markdown:C}))}))}},45204:(Te,ne,s)=>{"use strict";s.d(ne,{U:()=>ae});var b=s(9892),U=s(57706),a=s.n(U),re=s(66111),D=s(72648);function ae({query:ee,lang:Z,className:J}){const G=(0,D.l4)(),F=B(G),E=a().highlight(ee,Z.grammar,Z.name);return re.createElement("div",{className:(0,b.cx)(F.editorField,"prism-syntax-highlight",J),"aria-label":"selector",dangerouslySetInnerHTML:{__html:E}})}const B=ee=>({editorField:(0,b.css)({fontFamily:ee.typography.fontFamilyMonospace,fontSize:ee.typography.bodySmall.fontSize})})},24509:(Te,ne,s)=>{"use strict";s.d(ne,{tQ:()=>G,Ji:()=>ee});var b=s(76282),U=s(67483),a=s(53843),re=s(35645),D=s(28625);function ae(F,E){let[Q]=F,[C]=E,W=Q.length,M=Q[0],$=Q[W-1],k=C.length,w=C[0],P=C[k-1],O;if(W)if(k){if(w>$)O=F.map((L,j)=>F[j].concat(E[j]));else if(P<M)O=E.map((L,j)=>E[j].concat(F[j]));else if(w<=M&&P>=$)O=E;else if(!(w>M&&P<$)){if(w>=M){let L=(0,D.Ko)(w,Q);L=Q[L]<w?L-1:L,O=F.map((j,X)=>F[X].slice(0,L).concat(E[X]))}else if(P>=M){let L=(0,D.Ko)(P,Q);L=Q[L]<P?L:L+1,O=E.map((j,X)=>E[X].concat(F[X].slice(L)))}}}else O=F;else k?O=E:O=[[]];return O}function B(F,E,Q){let[C,...W]=F,M,$;return C[0]<E&&(M=(0,D.Ko)(E,C),C[M]<E&&M++),C[C.length-1]>Q&&($=(0,D.Ko)(Q,C),C[$]>Q&&$--),(M!=null||$!=null)&&(C=C.slice(M??0,$),W=W.map(k=>k.slice(M??0,$))),[C,...W]}const ee="10m",Z=F=>`${F.type}|${F.name}|${JSON.stringify(F.labels??"")}`;function J(F,E,Q){return`${F}|${Q.interval??E.interval}|${JSON.stringify(E.rangeRaw??"")}|${Q.exemplar}`}class G{constructor(E){this.sendEventsInterval=6e4*5,this.pendingRequestIdsToTargSigs=new Map,this.pendingAccumulatedEvents=new Map,this.cache=new Map,this.sendPendingTrackingEvents=()=>{const C=this.pendingAccumulatedEvents.entries();for(let[W,M]of C)M.sent||(this.pendingAccumulatedEvents.set(W,{...M,sent:!0}),a.s.api.pushMeasurement({type:"custom",values:{thing:0,thing2:1}}),a.s.api.pushEvent("prometheus incremental query response size",{requestCount:M.requestCount.toString(),savedBytesTotal:M.savedBytesTotal.toString(),initialRequestSize:M.initialRequestSize.toString(),lastRequestSize:M.lastRequestSize.toString(),panelId:M.panelId.toString(),dashId:M.dashId.toString(),expr:M.expr.toString(),interval:M.interval.toString()},"no-interaction",{skipDedupe:!0}))};const Q=E??ee;if((0,b.jO)(Q)){const C=(0,b.RA)(Q);this.overlapWindowMs=(0,b.iX)(C)}else{const C=(0,b.RA)(ee);this.overlapWindowMs=(0,b.iX)(C)}re.v.grafanaJavascriptAgent.enabled?(this.profile(),this.shouldProfile=!0):this.shouldProfile=!1}profile(){typeof PerformanceObserver=="function"&&(this.perfObeserver=new PerformanceObserver(E=>{E.getEntries().forEach(Q=>{const C=Q,W=typeof C?.transferSize=="number";if(C?.initiatorType==="fetch"&&W){let M=C.name;if(M.includes("/api/ds/query")){let $=M.match(/requestId=([a-z\d]+)/i);if($){let k=$[1];const w=Math.round(C.transferSize),P=this.pendingRequestIdsToTargSigs.get(k);if(P){const O=this.pendingRequestIdsToTargSigs.entries();for(let[,L]of O)if(L.identity===P.identity&&L.bytes!==null){const j=this.pendingAccumulatedEvents.get(L.identity),X=L.bytes-w;this.pendingAccumulatedEvents.set(L.identity,{requestCount:(j?.requestCount??0)+1,savedBytesTotal:(j?.savedBytesTotal??0)+X,initialRequestSize:L.bytes,lastRequestSize:w,panelId:P.panelId?.toString()??"",dashId:P.dashboardUID??"",expr:P.expr??"",interval:P.interval??"",sent:!1}),this.pendingRequestIdsToTargSigs.delete(k);return}this.pendingRequestIdsToTargSigs.set(k,{...P,bytes:w})}}}}})}),this.perfObeserver.observe({type:"resource",buffered:!1}),setInterval(this.sendPendingTrackingEvents,this.sendEventsInterval),window.addEventListener("beforeunload",this.sendPendingTrackingEvents))}requestInfo(E,Q){const C=E.range.from.valueOf(),W=E.range.to.valueOf(),M=E.rangeRaw?.to?.toString()==="now"&&!E.targets.some(P=>P.instant);let $=M,k;const w=new Map;E.targets.forEach(P=>{let O=`${E.dashboardUID}|${E.panelId}|${P.refId}`,L=Q(P.expr),j=J(L,E,P);this.shouldProfile&&this.pendingRequestIdsToTargSigs.set(E.requestId,{identity:O+"|"+j,dashboardUID:E.dashboardUID??"",interval:P.interval??E.interval,panelId:E.panelId,expr:L,bytes:null}),w.set(O,j)});for(const[P,O]of w){let L=this.cache.get(P);if(L?.sig!==O?$=!1:(k=L?.prevTo??1/0,$=W>k&&C<=k),!$)break}if($){let P=Math.max(k-this.overlapWindowMs,C);E={...E,range:{...E.range,from:(0,U.CQ)(P),to:(0,U.CQ)(W)}}}else w.forEach((P,O)=>{this.cache.delete(O)});return{requests:[E],targSigs:w,shouldCache:M}}procFrames(E,Q,C){if(Q?.shouldCache){const W=E.range.from.valueOf(),M=E.range.to.valueOf(),$=new Map;C.forEach(w=>{let P=`${E.dashboardUID}|${E.panelId}|${w.refId}`,O=$.get(P);O||(O=[],$.set(P,O)),O.push(w)});let k=[];$.forEach((w,P)=>{let O=(P?this.cache.get(P)?.frames:null)??[];w.forEach(j=>{if(j.length===0||j.fields.length===0)return;let X=Z(j.fields[1]),de=O.find(le=>Z(le.fields[1])===X);if(!de)O.push(j);else{let le=de.fields.map(ie=>ie.values),Se=j.fields.map(ie=>ie.values),K=ae(le,Se);if(K){for(let ie=0;ie<K.length;ie++)de.fields[ie].values=K[ie];de.length=de.fields[0].values.length}}});let L=[];O.forEach(j=>{let X=j.fields.map(le=>le.values),de=B(X,W,M);if(de[0].length>0){for(let le=0;le<de.length;le++)j.fields[le].values=de[le];L.push(j)}}),this.cache.set(P,{sig:Q.targSigs.get(P),frames:L,prevTo:M}),k.push(...L)}),C=k.map(w=>({...w,fields:w.fields.map(P=>({...P,config:{...P.config},values:P.values.slice()}))}))}return C}}},30749:(Te,ne,s)=>{"use strict";s.d(ne,{Ky:()=>fe,n:()=>w,nM:()=>Ce,nf:()=>Re,vs:()=>j});var b=s(47700),U=s(82897),a=s.n(U),re=s(206),D=s(99098),ae=s(89749),B=s(86029),ee=s(6194),Z=s(7569),J=s(39393),G=s(30471),F=s(35645),E=s(86647),Q=s(20308),C=s(44332),W=s(37462);const M=/^[+-]?inf(?:inity)?$/i,$=(m,i)=>i.app===re.zj.Explore&&(m.meta?.custom?.resultType==="vector"||m.meta?.custom?.resultType==="scalar")?!0:i.targets.find(u=>u.refId===m.refId)?.format==="table",k=(m,i)=>i.targets.find(u=>u.refId===m.refId)?.format==="heatmap";function w(m,i,l){F.v.featureToggles.prometheusDataplane&&m.data.forEach(V=>{const I=i.targets.find(z=>z.refId===V.refId);I&&I.legendFormat==="__auto"&&V.fields.forEach(z=>{if(z.labels?.__name__&&z.labels?.__name__===z.name){const se={...z,name:D.M5};z.config.displayNameFromDS=(0,G.$w)(se,V,m.data)}})});const[u,o]=(0,U.partition)(m.data,V=>$(V,i)),c=O(u),[g,p]=(0,U.partition)(o,V=>V.meta?.custom?.resultType==="exemplar"),{exemplarTraceIdDestinations:v}=l,x=g.map(V=>{if(v?.length)for(const I of v){const z=V.fields.find(se=>se.name===I.name);if(z){const se=X(I);z.config.links=z.config.links?.length?[...z.config.links,...se]:se}}return{...V,meta:{...V.meta,dataTopic:ae.w5.Annotations}}}),[S,T]=(0,U.partition)(p,V=>k(V,i));S.forEach(V=>{if(V.name==null){let I=V.fields.find(z=>z.name==="Value");if(I){let z=I.labels?.le;z&&(V.name=z,I.config.displayNameFromDS=z)}}});const _=(0,U.groupBy)(S,V=>V.refId);let te=[];for(const V in _){const I=_[V],z=(0,U.groupBy)(I,se=>{const Ee=se.fields.find(Le=>Le.name===D.M5);if(Ee?.labels&&P in Ee.labels){const{le:Le,...Oe}=Ee?.labels;return Object.values(Oe).join()}return Object.values(Ee?.labels??[]).join()});(0,U.forOwn)(z,(se,Ee)=>{const Le=se.sort(Re);te.push(ye(Me(Le)))})}const ce=T.map(V=>({...V,meta:{...V.meta,preferredVisualisationType:"graph"}})),ge=(0,U.flatten)(te);return{...m,data:[...ce,...c,...ge,...x]}}const P="le";function O(m){if(m.length===0||m.length===1&&m[0].length===0)return m;const i=(0,U.groupBy)(m,"refId"),l=Object.keys(i);return l.map(o=>{const c=L(l.length,o),g=ve({data:[],valueName:c}),p=ie([]),v=[];i[o].forEach(S=>{const _=S.fields[1]?.labels??{};Object.keys(_).sort().forEach(te=>{if(!v.some(ce=>ce.name===te)){const ce=te===P;v.push({name:te,config:{filterable:!0},type:ce?D.fS.number:D.fS.string,values:[]})}})}),i[o].forEach(S=>{const T=S.fields[0]?.values??[],_=S.fields[1]?.values??[];T.forEach(te=>p.values.push(te)),_.forEach(te=>{g.values.push(fe(te));const ce=S.fields[1].labels??{};v.forEach(ge=>ge.values.push(K(ce,ge.name)))})});const x=[p,...v,g];return{refId:o,fields:x,meta:{...m[0].meta,preferredVisualisationType:"rawPrometheus"},length:p.values.length}})}function L(m,i=""){return m>1?`Value #${i}`:"Value"}function j(m,i){const l={format:i.target.format,step:i.query.step,legendFormat:i.target.legendFormat,start:i.query.start,end:i.query.end,query:i.query.expr,responseListLength:i.responseListLength,scopedVars:i.scopedVars,refId:i.target.refId,valueWithRefId:i.target.valueWithRefId,meta:{preferredVisualisationType:i.query.instant?"rawPrometheus":"graph"}},u=m.data.data;if((0,W.WS)(u)){const c=[];u.forEach(v=>{const x=v.exemplars.map(S=>({[D.Ls]:S.timestamp*1e3,[D.M5]:S.value,...S.labels,...v.seriesLabels}));c.push(...x)});const g=de(c,l),p=new B.i(g);if(p.meta={dataTopic:ae.w5.Annotations},i.exemplarTraceIdDestinations?.length)for(const v of i.exemplarTraceIdDestinations){const x=p.fields.find(S=>S.name===v.name);if(x){const S=X(v);x.config.links=x.config.links?.length?[...x.config.links,...S]:S}}return[p]}if(!u?.result)return[];if(u.resultType==="scalar")return[{meta:l.meta,refId:l.refId,length:1,fields:[ie([u.result]),ve({data:[u.result]})]}];if(l.format==="table")return[Se(u.result,l)];const o=[];return u.result.forEach(c=>o.push(le(c,l))),l.format==="heatmap"?ye(Me(o.sort(Re))):o}function X(m){const i=[];if(m.datasourceUid){const u=(0,E.F)().getInstanceSettings(m.datasourceUid);u&&i.push({title:m.urlDisplayLabel||`Query with ${u?.name}`,url:"",internal:{query:{query:"${__value.raw}",queryType:"traceql"},datasourceUid:m.datasourceUid,datasourceName:u?.name??"Data source not found"}})}return m.url&&i.push({title:m.urlDisplayLabel||`Go to ${m.url}`,url:m.url,targetBlank:!0}),i}function de(m,i){const l=i.step||15,u={},o=[];for(const v of m){const x=String(Math.floor(v[D.Ls]/1e3/l)*l*1e3);u[x]||(u[x]=[]),u[x].push(v),o.push(v[D.M5])}const c=(0,b.deviation)(o),g=Object.keys(u).sort(),p=[];for(const v of g){const x=u[v];if(x.length===1)p.push(x[0]);else{const T=x.map(_=>_[D.M5]).sort(b.descending).reduce((_,te)=>{if(_.length===0)_.push(te);else{const ce=_[_.length-1];c&&ce-te>=2*c&&_.push(te)}return _},[]);p.push(...T.map(_=>x.find(te=>te[D.M5]===_)))}}return p}function le(m,i){const{name:l,labels:u}=pe(m.metric,i),o=[];if((0,W.el)(m)){const c=i.step?i.step*1e3:NaN;let g=i.start*1e3;const p=[];for(const x of m.values){let S=fe(x[1]);isNaN(S)&&(S=null);const T=x[0]*1e3;for(let _=g;_<T;_+=c)p.push([_,null]);g=T+c,p.push([T,S])}const v=i.end*1e3;for(let x=g;x<=v;x+=c)p.push([x,null]);o.push(ie(p,!0)),o.push(ve({data:p,parseValue:!1,labels:u,displayNameFromDS:l}))}else o.push(ie([m.value])),o.push(ve({data:[m.value],labels:u,displayNameFromDS:l}));return{meta:i.meta,refId:i.refId,length:o[0].values.length,fields:o,name:l}}function Se(m,i){if(!m||m.length===0)return{meta:i.meta,refId:i.refId,length:0,fields:[]};const l=i.responseListLength>1||i.valueWithRefId?`Value #${i.refId}`:"Value",u=ie([]),o=Object.keys(m.reduce((g,p)=>({...g,...p.metric}),{})).sort().map(g=>({name:g,config:{filterable:!0},type:g===P?D.fS.number:D.fS.string,values:[]})),c=ve({data:[],valueName:l});return m.forEach(g=>{(0,W.el)(g)?g.values.forEach(p=>{u.values.push(p[0]*1e3),o.forEach(v=>v.values.push(K(g.metric,v.name))),c.values.push(fe(p[1]))}):(u.values.push(g.value[0]*1e3),o.forEach(p=>p.values.push(K(g.metric,p.name))),c.values.push(fe(g.value[1])))}),{meta:i.meta,refId:i.refId,length:u.values.length,fields:[u,...o,c]}}function K(m,i){return m.hasOwnProperty(i)?i===P?fe(m[i]):m[i]:""}function ie(m,i=!1){return{name:D.Ls,type:D.fS.time,config:{},values:m.map(l=>i?l[0]:l[0]*1e3)}}function ve({data:m,valueName:i=D.M5,parseValue:l=!0,labels:u,displayNameFromDS:o}){return{name:i,type:D.fS.number,display:(0,ee.U_)(),config:{displayNameFromDS:o},labels:u,values:m.map(c=>l?fe(c[1]):c[1])}}function pe(m,i){if(i?.legendFormat)return{name:(0,C.W)((0,Q.J)().replace(i.legendFormat,i?.scopedVars),m),labels:m};const{__name__:l,...u}=m,o=(0,Z.aA)(u);let c=`${l??""}${o}`;return c||(c=i.query),{name:c,labels:u}}function Ce(m){const i=m.__name__||"";delete m.__name__;const l=Object.entries(m).map(u=>`${u[0]}="${u[1]}"`).join(",");return`${i}{${l}}`}function ye(m){if(m.length===0)return[];const i=m[0].fields.find(u=>u.type===D.fS.time),l=m.map(u=>{let o=u.fields.find(c=>c.type===D.fS.number);return{...o,name:o.config.displayNameFromDS}});return[{...m[0],meta:{...m[0].meta,type:J.P.HeatmapRows},fields:[i,...l]}]}function Me(m){for(let i=m.length-1;i>0;i--){const l=m[i].fields.find(o=>o.name===D.M5),u=m[i-1].fields.find(o=>o.name===D.M5);if(!l||!u)throw new Error("Prometheus heatmap transform error: data should be a time series");for(let o=0;o<l.values.length;o++){const c=u.values[o]||[0];l.values[o]-=c}}return m}function Re(m,i){let l,u;try{l=fe(m.name??m.fields[1].name),u=fe(i.name??i.fields[1].name)}catch(o){return console.error(o),0}return l>u?1:l<u?-1:0}function fe(m){return M.test(m)?m[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY:parseFloat(m)}},72097:(Te,ne,s)=>{Te.exports=s(5048)}}]);

//# sourceMappingURL=8366.c2486504d3ae1732be24.js.map