"use strict";(self.webpackChunkgrafana=self.webpackChunkgrafana||[]).push([[4254],{6191:(Ae,q,i)=>{i.d(q,{X:()=>X});var U=i(32196),t=i(96540),K=i(40845);const X=({children:L})=>{const O=(0,K.of)(le);return t.createElement("div",{className:O.root},L)},le=L=>({root:(0,U.css)({display:"flex",flexWrap:"wrap",alignItems:"center",gap:L.spacing(3),minHeight:L.spacing(4)})})},31347:(Ae,q,i)=>{i.d(q,{Z:()=>t});var U=i(96540);const t=({grow:K,shrink:X})=>U.createElement("div",{style:{display:"block",flexGrow:K,flexShrink:X}})},94254:(Ae,q,i)=>{i.r(q),i.d(q,{plugin:()=>Sn});var U=i(40187),t=i(96540);const K=[{title:"Request Rate",expression:"rate(http_request_total[5m])",label:"Given an HTTP request counter, this query calculates the per-second average request rate over the last 5 minutes."},{title:"95th Percentile of Request Latencies",expression:"histogram_quantile(0.95, sum(rate(prometheus_http_request_duration_seconds_bucket[5m])) by (le))",label:"Calculates the 95th percentile of HTTP request rate over 5 minute windows."},{title:"Alerts Firing",expression:'sort_desc(sum(sum_over_time(ALERTS{alertstate="firing"}[24h])) by (alertname))',label:"Sums up the alerts that have been firing over the last 24 hours."},{title:"Step",label:"Defines the graph resolution using a duration format (15s, 1m, 3h, ...). Small steps create high-resolution graphs but can be slow over larger time ranges. Using a longer step lowers the resolution and smooths the graph by producing fewer datapoints. If no step is given the resolution is calculated automatically."}],le=e=>t.createElement("div",null,t.createElement("h2",null,"PromQL Cheat Sheet"),K.map((a,n)=>t.createElement("div",{className:"cheat-sheet-item",key:n},t.createElement("div",{className:"cheat-sheet-item__title"},a.title),a.expression?t.createElement("button",{type:"button",className:"cheat-sheet-item__example",onClick:s=>e.onClickExample({refId:"A",expr:a.expression})},t.createElement("code",null,a.expression)):null,t.createElement("div",{className:"cheat-sheet-item__label"},a.label))));var L=i(41987),O=i(2543),Fe=i(39070),A=i(13544),ft=i(6191),_=i(31347),Be=i(71087),k=i(14110),ht=i(96374),C=i(55852),yt=i(68402),o=i(32196),$=i(40845),vt=i(37390),Oe=i(82762),Et=i(21969),F=i(47891),ce=i(10860),me=i(44339),ue=i(69470);const bt=e=>{const{pattern:a,onPatternSelect:n,hasNewQueryOption:s,hasPreviousQuery:r,selectedPatternName:m,setSelectedPatternName:u}=e,l=(0,$.of)(xt),c={grammar:ue.Ay,name:"promql"};return t.createElement(ce.Z,{className:l.card},t.createElement(ce.Z.Heading,null,a.name),t.createElement("div",{className:l.rawQueryContainer},t.createElement(me.Z,{"aria-label":`${a.name} raw query`,query:F.z.renderQuery({labels:[],operations:a.operations,binaryQueries:a.binaryQueries}),lang:c,className:l.rawQuery})),t.createElement(ce.Z.Actions,null,m!==a.name?t.createElement(C.$n,{size:"sm","aria-label":"use this query button",onClick:()=>{r?u(a.name):n(a)}},"Use this query"):t.createElement(t.Fragment,null,t.createElement("div",{className:l.spacing},`If you would like to use this query, ${s?"you can either apply this query pattern or create a new query":"this query pattern will be applied to your current query"}.`),t.createElement(C.$n,{size:"sm","aria-label":"back button",fill:"outline",onClick:()=>u(null)},"Back"),t.createElement(C.$n,{size:"sm","aria-label":"apply query starter button",onClick:()=>{n(a)}},"Apply query"),s&&t.createElement(C.$n,{size:"sm","aria-label":"create new query button",onClick:()=>{n(a,!0)}},"Create new query"))))},xt=e=>({card:(0,o.css)`
      width: 49.5%;
      display: flex;
      flex-direction: column;
    `,rawQueryContainer:(0,o.css)`
      flex-grow: 1;
    `,rawQuery:(0,o.css)`
      background-color: ${e.colors.background.primary};
      padding: ${e.spacing(1)};
      margin-top: ${e.spacing(1)};
    `,spacing:(0,o.css)`
      margin-bottom: ${e.spacing(1)};
    `});var R=i(65405),St=i(65820);const Ct=e=>{const{isOpen:a,onClose:n,onChange:s,onAddQuery:r,query:m,queries:u,app:l}=e,[c,f]=(0,t.useState)([]),[h,p]=(0,t.useState)(null),x=(0,$.of)(Pt),E=!!r,g=(0,t.useMemo)(()=>{const d=(0,R.u)(m.expr??""),b=d.query.operations.length>0,v=d.query.metric,P=d.query.labels.length>0,Q=d.query.binaryQueries?d.query.binaryQueries.length>0:!1;return b||v||P||Q},[m.expr]),y=(d,b=!1)=>{const v=(0,R.u)(b?"":m.expr);(0,k.rR)("grafana_prom_kickstart_your_query_selected",{app:l??"",editorMode:m.editorMode,selectedPattern:d.name,preSelectedOperationsCount:v.query.operations.length,preSelectedLabelsCount:v.query.labels.length,createNewQuery:E&&b}),v.query.operations=d.operations,v.query.binaryQueries=d.binaryQueries,E&&b?r({...m,refId:(0,Et.W3)(u??[m]),expr:F.z.renderQuery(v.query)}):s({...m,expr:F.z.renderQuery(v.query)}),p(null),n()};return t.createElement(vt.a,{"aria-label":"Kick start your query modal",isOpen:a,title:"Kick start your query",onDismiss:n},t.createElement("div",{className:x.spacing},"Kick start your query by selecting one of these queries. You can then continue to complete your query."),Object.values(St.n5).map(d=>t.createElement(Oe.S,{"aria-label":`open and close ${d} query starter card`,key:d,label:`${(0,O.capitalize)(d)} query starters`,isOpen:c.includes(d),collapsible:!0,onToggle:()=>f(b=>b.includes(d)?b.filter(v=>v!==d):[...b,d])},t.createElement("div",{className:x.cardsContainer},F.z.getQueryPatterns().filter(b=>b.type===d).map(b=>t.createElement(bt,{key:b.name,pattern:b,hasNewQueryOption:E,hasPreviousQuery:g,onPatternSelect:y,selectedPatternName:h,setSelectedPatternName:p}))))),t.createElement(C.$n,{"aria-label":"close kick start your query modal",variant:"secondary",onClick:n},"Close"))},Pt=e=>({cardsContainer:(0,o.css)`
      display: flex;
      flex-direction: row;
      flex-wrap: wrap;
      justify-content: space-between;
    `,spacing:(0,o.css)`
      margin-bottom: ${e.spacing(1)};
    `});var z=i(33390);const Tt="PrometheusQueryEditorExplainDefault";function Nt(e,a=!1){const n=z.A.get(e);return n===void 0?a:!!parseInt(n,10)}function Qt(e,a){z.A.set(e,a?"1":"0")}function wt(e,a=!1){const[n,s]=(0,t.useState)(Nt(e,a)),r=(0,t.useCallback)(m=>{Qt(e,m),s(m)},[e]);return{flag:n,setFlag:r}}var de=i(94354),B=i(35146);const $t=[{label:"Builder",value:B.f.Builder},{label:"Code",value:B.f.Code}];function It({mode:e,onChange:a}){return t.createElement("div",{"data-testid":"QueryEditorModeToggle"},t.createElement(de.z,{options:$t,size:"sm",value:e,onChange:a}))}var D=i(67061),Mt=i(15292);function Lt({label:e,...a}){const n=e.replace(" ","-"),s=(0,t.useRef)((0,O.uniqueId)(`switch-${n}`)),r=(0,$.of)(kt);return t.createElement(D.B,{gap:1},t.createElement("label",{htmlFor:s.current,className:r.switchLabel},e),t.createElement(Mt.d,{...a,id:s.current}))}const kt=e=>({switchLabel:(0,o.css)({color:e.colors.text.secondary,cursor:"pointer",fontSize:e.typography.bodySmall.fontSize,"&:hover":{color:e.colors.text.primary}})});var I=i(69120);const Re="PrometheusQueryEditorModeDefault";function ze(e,a,n){e.expr===""&&z.A.set(Re,a),n({...e,editorMode:a})}function At(e,a=B.f.Builder){if(e!=null&&e!=="")return B.f.Code;const n=z.A.get(Re);switch(n){case B.f.Builder:case B.f.Code:return n;default:return a}}function Ft(e,a,n){let s=e;e.editorMode||(s={...e,editorMode:At(e.expr,n)}),e.expr||(s={...s,expr:"",legendFormat:I.m_.Auto}),e.range==null&&e.instant==null&&(s={...s,range:!0},a===L.Jk.Explore&&(s.instant=!0));const r=e.instant&&e.range;return a===L.Jk.UnifiedAlerting&&r&&(s={...s,instant:!1,range:!0}),s}var De=i(30038),pe=i(32264),ge=i(9e4),Bt=i(87978),Ot=i(30683),fe=i(75494),Rt=i(1604),he=i(84596),zt=i(3988),G=i(56034),We=i(14578),Dt=i(14186),Wt=i(11216),Ht=i(54623),ee=i(56823),W=i(88323),qt=i(95361),ye=i(18491),te=i(36376),Gt=i(36663),Vt=i(17464);const He=t.memo(({def:e,operation:a})=>{const n=(0,$.of)(Ut),[s,r]=(0,t.useState)(!1),m=[(0,qt.cY)(16),(0,ye.UU)({fallbackAxisSideDirection:"end",crossAxis:!1,boundary:document.body}),(0,ye.BN)()],{context:u,refs:l,floatingStyles:c}=(0,te.we)({open:s,placement:"top",onOpenChange:r,middleware:m,whileElementsMounted:ye.ll}),f=(0,te.kp)(u),h=(0,te.s9)(u),{getReferenceProps:p,getFloatingProps:x}=(0,te.bv)([h,f]);return t.createElement(t.Fragment,null,t.createElement(C.$n,{title:"Click to show description",ref:l.setReference,icon:"info-circle",size:"sm",variant:"secondary",fill:"text",...p()}),s&&t.createElement(Vt.ZL,null,t.createElement("div",{ref:l.setFloating,style:c,...x(),className:n.docBox},t.createElement("div",{className:n.docBoxHeader},t.createElement("span",null,e.renderer(a,e,"<expr>")),t.createElement(_.Z,{grow:1}),t.createElement(C.$n,{icon:"times",onClick:()=>r(!1),fill:"text",variant:"secondary",title:"Remove operation"})),t.createElement("div",{className:n.docBoxBody,dangerouslySetInnerHTML:{__html:Kt(e,a)}}))))});He.displayName="OperationDocs";const Ut=e=>({docBox:(0,o.css)({overflow:"hidden",background:e.colors.background.primary,border:`1px solid ${e.colors.border.strong}`,boxShadow:e.shadows.z3,maxWidth:"600px",padding:e.spacing(1),borderRadius:e.shape.radius.default,zIndex:e.zIndex.tooltip}),docBoxHeader:(0,o.css)({fontSize:e.typography.h5.fontSize,fontFamily:e.typography.fontFamilyMonospace,paddingBottom:e.spacing(1),display:"flex",alignItems:"center"}),docBoxBody:(0,o.css)({marginBottom:e.spacing(-1),color:e.colors.text.secondary})});function Kt(e,a){return(0,Gt.G)(e.explainHandler?e.explainHandler(a,e):e.documentation??"no docs")}const qe=t.memo(({operation:e,def:a,index:n,onChange:s,onRemove:r,queryModeller:m,dragHandleProps:u})=>{const l=(0,$.of)(jt),[c,f]=(0,t.useState)({}),h=()=>{if(c.isOpen)f({...c,isOpen:!1});else{const p=m.getAlternativeOperations(a.alternativesKey).map(x=>({label:x.name,value:x}));f({isOpen:!0,alternatives:p})}};return t.createElement("div",{className:l.header},!c.isOpen&&t.createElement(t.Fragment,null,t.createElement("div",{...u},a.name??a.id),t.createElement(_.Z,{grow:1}),t.createElement("div",{className:`${l.operationHeaderButtons} operation-header-show-on-hover`},t.createElement(C.$n,{icon:"angle-down",size:"sm",onClick:h,fill:"text",variant:"secondary",title:"Click to view alternative operations"}),t.createElement(He,{def:a,operation:e}),t.createElement(C.$n,{icon:"times",size:"sm",onClick:()=>r(n),fill:"text",variant:"secondary",title:"Remove operation"}))),c.isOpen&&t.createElement("div",{className:l.selectWrapper},t.createElement(W.l6,{autoFocus:!0,openMenuOnFocus:!0,placeholder:"Replace with",options:c.alternatives,isOpen:!0,onCloseMenu:h,onChange:p=>{if(p.value){const x=m.getOperationDef(p.value.id),E=[...x.defaultParams];for(let y=0;y<Math.min(e.params.length,E.length);y++)x.params[y].type===a.params[y].type&&(E[y]=e.params[y]);const g={...e,params:E,id:p.value.id};s(n,a.changeTypeHandler?a.changeTypeHandler(g,x):g)}}})))});qe.displayName="OperationHeader";const jt=e=>({header:(0,o.css)({borderBottom:`1px solid ${e.colors.border.medium}`,padding:e.spacing(.5,.5,.5,1),display:"flex",alignItems:"center"}),operationHeaderButtons:(0,o.css)({opacity:1}),selectWrapper:(0,o.css)({paddingRight:e.spacing(2)})});var Ge=i(50877),ae=i(51440),Ve=i(10880);function Yt(e){if(e.editor)return e.editor;if(e.options)return Xt;switch(e.type){case"boolean":return Jt;case"number":case"string":default:return Zt}}function Zt(e){return t.createElement(ae.D,{id:(0,ee.OS)(e.operationId,e.index),defaultValue:e.value?.toString(),minWidth:e.paramDef.minWidth,placeholder:e.paramDef.placeholder,title:e.paramDef.description,maxWidth:(e.paramDef.minWidth||20)*3,onCommitChange:a=>{e.onChange(e.index,a.currentTarget.value),e.paramDef.runQueryOnEnter&&a.type==="keydown"&&e.onRunQuery()}})}function Jt(e){return t.createElement(Ve.S,{id:(0,ee.OS)(e.operationId,e.index),value:!!e.value,onChange:a=>e.onChange(e.index,a.currentTarget.checked)})}function Xt({paramDef:e,value:a,index:n,operationId:s,onChange:r}){const m=(0,$.of)(_t);let u=e.options;u[0]?.label||(u=e.options.map(c=>({label:c.toString(),value:c})));let l=u.find(c=>c.value===a)??(0,Ge.z)(a);return!a&&e.optional?t.createElement("div",{className:m.optionalParam},t.createElement(C.$n,{size:"sm",variant:"secondary",title:`Add ${e.name}`,icon:"plus",onClick:()=>r(n,u[0].value)},e.name)):t.createElement(D.B,{gap:.5,direction:"row",alignItems:"center"},t.createElement(W.l6,{id:(0,ee.OS)(s,n),value:l,options:u,placeholder:e.placeholder,allowCustomValue:!0,onChange:c=>r(n,c.value),width:e.minWidth||"auto"}),e.optional&&t.createElement(C.$n,{"data-testid":`operations.${n}.remove-param`,size:"sm",fill:"text",icon:"times",variant:"secondary",title:`Remove ${e.name}`,onClick:()=>r(n,"")}))}const _t=e=>({optionalParam:(0,o.css)({marginTop:e.spacing(1)})});function ea({operation:e,index:a,onRemove:n,onChange:s,onRunQuery:r,queryModeller:m,query:u,datasource:l,flash:c,highlight:f,timeRange:h}){const p=m.getOperationDef(e.id),x=ta(c),E=(0,t.useId)(),g=e.id===Ht.EF.LabelFilter&&(0,Wt.hh)(e,u.operations),y=(0,$.$j)(),d=na(y,g);if(!p)return t.createElement("span",null,"Operation ",e.id," not found");const b=(T,N)=>{const w={...e,params:[...e.params]};w.params[T]=N,ve(p,w,a,T,s)},v=()=>{const T={...e,params:[...e.params,""]};ve(p,T,a,e.params.length,s)},P=T=>{const N={...e,params:[...e.params.slice(0,T),...e.params.slice(T+1)]};ve(p,N,a,T,s)},Q=[];for(let T=0;T<e.params.length;T++){const N=p.params[Math.min(p.params.length-1,T)],w=Yt(N);Q.push(t.createElement("div",{className:d.paramRow,key:`${T}-1`},!N.hideName&&t.createElement("div",{className:d.paramName},t.createElement("label",{htmlFor:(0,ee.OS)(E,T)},N.name),N.description&&t.createElement(G.m,{placement:"top",content:N.description,theme:"info"},t.createElement(We.I,{name:"info-circle",size:"sm",className:d.infoIcon}))),t.createElement("div",{className:d.paramValue},t.createElement(D.B,{gap:.5,direction:"row",alignItems:"center"},t.createElement(w,{index:T,paramDef:N,value:e.params[T],operation:e,operationId:E,onChange:b,onRunQuery:r,query:u,datasource:l,timeRange:h}),N.restParam&&(e.params.length>p.params.length||N.optional)&&t.createElement(C.$n,{"data-testid":`operations.${a}.remove-rest-param`,size:"sm",fill:"text",icon:"times",variant:"secondary",title:`Remove ${N.name}`,onClick:()=>P(T)})))))}let S;if(p.params.length>0){const T=p.params[p.params.length-1];T.restParam&&(S=aa(T,v,a,e.params.length,d))}const Z=T=>{if(!T)return g?!0:void 0};return t.createElement(fe.sx,{draggableId:`operation-${a}`,index:a},(T,N)=>t.createElement(Dt.I,{error:"You have conflicting label filters",invalid:Z(N.isDragging),className:(0,o.cx)(d.error,d.cardWrapper)},t.createElement("div",{className:(0,o.cx)(d.card,(x||f)&&d.cardHighlight,g&&d.cardError),ref:T.innerRef,...T.draggableProps,"data-testid":`operations.${a}.wrapper`},t.createElement(qe,{operation:e,dragHandleProps:T.dragHandleProps,def:p,index:a,onChange:s,onRemove:n,queryModeller:m}),t.createElement("div",{className:d.body},Q),S,a<u.operations.length-1&&t.createElement("div",{className:d.arrow},t.createElement("div",{className:d.arrowLine}),t.createElement("div",{className:d.arrowArrow})))))}function ta(e){const[a,n]=(0,t.useState)(!0);return(0,t.useEffect)(()=>{let s;return e?s=setTimeout(()=>{n(!1)},1e3):n(!0),()=>clearTimeout(s)},[e]),a&&e}function aa(e,a,n,s,r){return t.createElement("div",{className:r.restParam,key:`${s}-2`},t.createElement(C.$n,{size:"sm",icon:"plus",title:`Add ${e.name}`.trimEnd(),variant:"secondary",onClick:a,"data-testid":`operations.${n}.add-rest-param`},e.name))}function ve(e,a,n,s,r){e.paramChangedHandler?r(n,e.paramChangedHandler(s,a,e)):r(n,a)}const na=(e,a)=>({cardWrapper:(0,o.css)({alignItems:"stretch"}),error:(0,o.css)({marginBottom:e.spacing(1)}),card:(0,o.css)({background:e.colors.background.primary,border:`1px solid ${e.colors.border.medium}`,cursor:"grab",borderRadius:e.shape.radius.default,position:"relative",transition:"all 0.5s ease-in 0s",height:a?"auto":"100%"}),cardError:(0,o.css)({boxShadow:`0px 0px 4px 0px ${e.colors.warning.main}`,border:`1px solid ${e.colors.warning.main}`}),cardHighlight:(0,o.css)({boxShadow:`0px 0px 4px 0px ${e.colors.primary.border}`,border:`1px solid ${e.colors.primary.border}`}),infoIcon:(0,o.css)({marginLeft:e.spacing(.5),color:e.colors.text.secondary,":hover":{color:e.colors.text.primary}}),body:(0,o.css)({margin:e.spacing(1,1,.5,1),display:"table"}),paramRow:(0,o.css)({label:"paramRow",display:"table-row",verticalAlign:"middle"}),paramName:(0,o.css)({display:"table-cell",padding:e.spacing(0,1,0,0),fontSize:e.typography.bodySmall.fontSize,fontWeight:e.typography.fontWeightMedium,verticalAlign:"middle",height:"32px"}),paramValue:(0,o.css)({label:"paramValue",display:"table-cell",verticalAlign:"middle"}),restParam:(0,o.css)({padding:e.spacing(0,1,1,1)}),arrow:(0,o.css)({position:"absolute",top:"0",right:"-18px",display:"flex"}),arrowLine:(0,o.css)({height:"2px",width:"8px",backgroundColor:e.colors.border.strong,position:"relative",top:"14px"}),arrowArrow:(0,o.css)({width:0,height:0,borderTop:"5px solid transparent",borderBottom:"5px solid transparent",borderLeft:`7px solid ${e.colors.border.strong}`,position:"relative",top:"10px"})});function ra({query:e,datasource:a,queryModeller:n,onChange:s,onRunQuery:r,highlightedOp:m,timeRange:u}){const l=(0,$.of)(ia),{operations:c}=e,f=sa(c),[h,p]=(0,t.useState)(!1),x=(v,P)=>{const Q=[...c];Q.splice(v,1,P),s({...e,operations:Q})},E=v=>{const P=[...c.slice(0,v),...c.slice(v+1)];s({...e,operations:P})},g=n.getCategories().map(v=>({value:v,label:v,items:n.getOperationsForCategory(v).map(P=>({value:P.id,label:P.name,isLeaf:!0}))})),y=v=>{const P=n.getOperationDef(v);P&&(s(P.addOperationHandler(P,e,n)),p(!1))},d=v=>{if(!v.destination)return;const P=[...c],Q=P[v.source.index];P.splice(v.source.index,1),P.splice(v.destination.index,0,Q),s({...e,operations:P})},b=()=>{p(!1)};return t.createElement(D.B,{gap:1,direction:"column"},t.createElement(D.B,{gap:1},c.length>0&&t.createElement(fe.JY,{onDragEnd:d},t.createElement(fe.gL,{droppableId:"sortable-field-mappings",direction:"horizontal"},v=>t.createElement("div",{className:l.operationList,ref:v.innerRef,...v.droppableProps},c.map((P,Q)=>t.createElement(ea,{key:P.id+JSON.stringify(P.params)+Q,queryModeller:n,index:Q,operation:P,query:e,datasource:a,onChange:x,onRemove:E,onRunQuery:r,flash:f[Q],highlight:m===P,timeRange:u})),v.placeholder))),t.createElement("div",{className:l.addButton},h?t.createElement(zt.v,{options:g,onSelect:y,onBlur:b,autoFocus:!0,alwaysOpen:!0,hideActiveLevelLabel:!0,placeholder:"Search"}):t.createElement(C.$n,{icon:"plus",variant:"secondary",onClick:()=>p(!0),title:"Add operation"},"Operations"))))}function sa(e){const a=(0,Rt.A)(),n=(0,he.A)(e);if(!a())return e.map(()=>!1);if(!n)return e.map(()=>!0);let s=[];if(n.length-1===e.length&&e.every(r=>n.includes(r)))return e.map(()=>!1);if(n.length+1===e.length&&n.every(r=>e.includes(r))){const r=e.find(m=>!n.includes(m));s=e.map(m=>m===r)}else s=e.map((r,m)=>!oa(r.id,n[m]?.id));return s}function oa(e,a){return e===a||`__${e}_by`===a||e===`__${a}_by`}const ia=e=>({heading:(0,o.css)({label:"heading",fontSize:12,fontWeight:e.typography.fontWeightMedium,marginBottom:0}),operationList:(0,o.css)({label:"operationList",display:"flex",flexWrap:"wrap",gap:e.spacing(2)}),addButton:(0,o.css)({label:"addButton",width:126,paddingBottom:e.spacing(1)})});var la=i(55698),ca=i(43854);const Ue=({datasource:e,query:a,onChange:n,data:s,queryModeller:r,buildVisualQueryFromString:m})=>{const[u,l]=(0,t.useState)([]),c=(0,$.of)(ma);return(0,t.useEffect)(()=>{const f={expr:r.renderQuery(a),refId:""},h=e.getQueryHints(f,s?.series||[]).filter(p=>p.fix?.action);l(h)},[e,a,s,r]),t.createElement(t.Fragment,null,u.length>0&&t.createElement("div",{className:c.container},u.map(f=>t.createElement(G.m,{content:`${f.label} ${f.fix?.label}`,key:f.type},t.createElement(C.$n,{onClick:()=>{if((0,k.rR)("grafana_query_builder_hints_clicked",{hint:f.type,datasourceType:e.type}),f?.fix?.action){const h={expr:r.renderQuery(a),refId:""},p=e.modifyQuery(h,f.fix.action),x=m(p.expr);return n(x.query)}},fill:"outline",size:"sm",className:c.hint},"hint: ",f.fix?.title||f.fix?.action?.type.toLowerCase().replace("_"," "))))))};Ue.displayName="QueryBuilderHints";const ma=e=>({container:(0,o.css)`
      display: flex;
      align-items: start;
    `,hint:(0,o.css)`
      margin-right: ${e.spacing(1)};
    `});var ua=i(46777),Ke=i(29158),da=i(25378);const je=t.memo(e=>{const{nestedQuery:a,index:n,datasource:s,onChange:r,onRemove:m,onRunQuery:u,showExplain:l}=e,c=(0,$.of)(ga);return t.createElement("div",{className:c.card},t.createElement("div",{className:c.header},t.createElement("div",{className:c.name},"Operator"),t.createElement(W.l6,{width:"auto",options:pa,value:(0,Ge.z)(a.operator),onChange:f=>{r(n,{...a,operator:f.value})}}),t.createElement("div",{className:c.name},"Vector matches"),t.createElement("div",{className:c.vectorMatchWrapper},t.createElement(W.l6,{width:"auto",value:a.vectorMatchesType||"on",allowCustomValue:!0,options:[{value:"on",label:"on"},{value:"ignoring",label:"ignoring"}],onChange:f=>{r(n,{...a,vectorMatchesType:f.value})}}),t.createElement(ae.D,{className:c.vectorMatchInput,minWidth:20,defaultValue:a.vectorMatches,onCommitChange:f=>{r(n,{...a,vectorMatches:f.currentTarget.value,vectorMatchesType:a.vectorMatchesType||"on"})}})),t.createElement(_.Z,{grow:1}),t.createElement(Ke.K,{name:"times",size:"sm",onClick:()=>m(n),tooltip:"Remove match"})),t.createElement("div",{className:c.body},t.createElement(Be.D,null,t.createElement($e,{showExplain:l,query:a.query,datasource:s,onRunQuery:u,onChange:f=>{r(n,{...a,query:f})}}))))}),pa=da.C8.map(e=>({label:e.sign,value:e.sign}));je.displayName="NestedQuery";const ga=e=>({card:(0,o.css)({label:"card",display:"flex",flexDirection:"column",gap:e.spacing(.5)}),header:(0,o.css)({label:"header",padding:e.spacing(.5,.5,.5,1),gap:e.spacing(1),display:"flex",alignItems:"center"}),name:(0,o.css)({label:"name",whiteSpace:"nowrap"}),body:(0,o.css)({label:"body",paddingLeft:e.spacing(2)}),vectorMatchInput:(0,o.css)({label:"vectorMatchInput",marginLeft:-1}),vectorMatchWrapper:(0,o.css)({label:"vectorMatchWrapper",display:"flex"})});function fa(e){const{query:a,datasource:n,onChange:s,onRunQuery:r,showExplain:m}=e,u=a.binaryQueries??[],l=(f,h)=>{const p=[...u];p.splice(f,1,h),s({...a,binaryQueries:p})},c=f=>{const h=[...u.slice(0,f),...u.slice(f+1)];s({...a,binaryQueries:h})};return t.createElement(D.B,{direction:"column",gap:1},u.map((f,h)=>t.createElement(je,{key:h.toString(),nestedQuery:f,index:h,onChange:l,datasource:n,onRemove:c,onRunQuery:r,showExplain:m})))}var ha=i(52005),ya=i(42418),va=i(10354),Ee=i(62930),Ea=i(5173),ba=i(21744),Ye=i(60782);const xa=[{label:"Yes",value:"yes"},{label:"No",value:"no"}],Sa=[{label:"Too vague",value:"too vague"},{label:"Too technical",value:"too technical"},{label:"Inaccurate",value:"inaccurate"},{label:"Other",value:"other"}];function Ca(e){const{querySuggestion:a,order:n,queryExplain:s,historical:r,onChange:m,closeDrawer:u,last:l,allSuggestions:c,prompt:f}=e,[h,p]=(0,t.useState)(!1),[x,E]=(0,t.useState)(!1),[g,y]=(0,t.useState)(!1),[d,b]=(0,t.useState)({radioInput:"",text:""}),[v,P]=(0,t.useState)({radioInput:"",text:""}),Q=(0,$.$j)(),S=ie(Q),{query:Z,explanation:T}=a,N=w=>{const Cn=J=>{w==="explanation"?P({...v,radioInput:J}):b({...d,radioInput:J})},Pn=J=>{w==="explanation"?P({...v,text:J.currentTarget.value}):b({...d,text:J.currentTarget.value})},Tn=()=>w==="explanation"?!v.radioInput:!d.radioInput,Nn=w==="explanation"?"Why was the explanation not helpful?":"Were the query suggestions helpful?";return t.createElement("div",{className:S.suggestionFeedback},t.createElement("div",null,t.createElement("div",{className:S.feedbackQuestion},t.createElement("h6",null,Nn),t.createElement("i",null,"(Required)")),t.createElement(Ea.a,{name:"default",options:w==="explanation"?Sa:xa,value:w==="explanation"?v.radioInput:d.radioInput,onChange:Cn})),t.createElement("div",{className:(0,o.cx)(w==="explanation"&&S.explationTextInput)},w!=="explanation"&&t.createElement("div",{className:S.feedbackQuestion},t.createElement("h6",null,"How can we improve the query suggestions?")),t.createElement(ba.f,{type:"text","aria-label":"Promqail suggestion text",placeholder:"Enter your feedback",value:w==="explanation"?v.text:d.text,onChange:Pn,cols:100})),t.createElement("div",{className:S.submitFeedback},t.createElement(C.$n,{variant:"primary",size:"sm",disabled:Tn(),onClick:()=>{w==="explanation"?(Ze(v.radioInput,v.text,a,r,f),E(!0)):(Pa(d.radioInput,d.text,c??"",r,f),y(!0))}},"Submit")))};return t.createElement(t.Fragment,null,t.createElement("div",{className:S.querySuggestion},t.createElement("div",{title:Z,className:(0,o.cx)(S.codeText,S.longCode)},`${n}.  ${Z}`),t.createElement("div",{className:S.useButton},t.createElement(C.$n,{variant:"primary",size:"sm",onClick:()=>{(0,k.rR)("grafana_prometheus_promqail_use_query_button_clicked",{query:a.query});const w=(0,R.u)(a.query);m(w.query),u()}},"Use"))),t.createElement("div",null,t.createElement(C.$n,{fill:"text",variant:"secondary",icon:h?"angle-up":"angle-down",onClick:()=>{p(!h),s(n-1)},className:(0,o.cx)(S.bodySmall),size:"sm"},"Explainer"),!h&&n!==5&&t.createElement("div",{className:S.textPadding}),h&&!a.explanation&&t.createElement("div",{className:S.center},t.createElement(Ee.y,null)),h&&a.explanation&&t.createElement(t.Fragment,null,t.createElement("div",{className:(0,o.cx)(S.bodySmall,S.explainPadding)},t.createElement("div",{className:S.textPadding},"This query is trying to answer the question:"),t.createElement("div",{className:S.textPadding},T),t.createElement("div",{className:S.textPadding},"Learn more with this"," ",t.createElement("a",{className:S.doc,href:"https://prometheus.io/docs/prometheus/latest/querying/examples/#query-examples",target:"_blank",rel:"noopener noreferrer"},"Prometheus doc")),t.createElement("div",{className:(0,o.cx)(S.rightButtons,S.secondaryText)},"Was this explanation helpful?",t.createElement("div",{className:S.floatRight},x?"Thank you for your feedback!":t.createElement(t.Fragment,null,t.createElement(C.$n,{fill:"outline",variant:"secondary",size:"sm",className:S.leftButton,onClick:()=>{Ze("Yes","",a,r,f),E(!0)}},"Yes"),t.createElement(Ye.G,{"aria-label":"Suggestion feedback",content:N("explanation"),placement:"bottom-end",closeButton:!0},t.createElement(C.$n,{variant:"success",size:"sm"},"No")))))),!l&&t.createElement("hr",null)),l&&t.createElement("div",{className:(0,o.cx)(S.feedbackStyle)},g?t.createElement(C.$n,{fill:"outline",variant:"secondary",size:"sm",disabled:!0},"Thank you for your feedback!"):t.createElement(Ye.G,{"aria-label":"Suggestion feedback",content:N("suggestion"),placement:"bottom-end",closeButton:!0},t.createElement(C.$n,{fill:"outline",variant:"secondary",size:"sm"},"Give feedback on suggestions")))))}function Ze(e,a,n,s,r){const m="grafana_prometheus_promqail_explanation_feedback";(0,k.rR)(m,{helpful:e,textFeedback:a,suggestionType:s?"historical":"AI",query:n.query,explanation:n.explanation,prompt:r})}function Pa(e,a,n,s,r){const m="grafana_prometheus_promqail_suggestion_feedback";(0,k.rR)(m,{helpful:e,textFeedback:a,suggestionType:s?"historical":"AI",allSuggestions:n,prompt:r})}var M=(e=>(e.Historical="historical",e.AI="AI",e))(M||{});function Je(e){const{suggestionType:a,querySuggestions:n,closeDrawer:s,nextInteraction:r,queryExplain:m,onChange:u,prompt:l}=e,[c,f]=(0,t.useState)(!1),h=(0,$.$j)(),p=ie(h);let x,E,g;return a===M.Historical?(x=`Here are ${n.length} query suggestions:`,g="I want to write a prompt"):a===M.AI&&(x=x="Here is your query suggestion:",E="This query is based off of natural language descriptions of the most commonly used PromQL queries.",g="Refine prompt"),t.createElement(t.Fragment,null,a===M.Historical?t.createElement("div",{className:p.bottomMargin},x):t.createElement(t.Fragment,null,t.createElement("div",{className:p.textPadding},x),t.createElement("div",{className:(0,o.cx)(p.secondaryText,p.bottomMargin)},E)),t.createElement("div",{className:p.infoContainerWrapper},t.createElement("div",{className:p.infoContainer},n.map((y,d)=>t.createElement(Ca,{historical:a===M.Historical,querySuggestion:y,key:d,order:d+1,queryExplain:m,onChange:u,closeDrawer:s,last:d===n.length-1,allSuggestions:n.reduce((b,v)=>b+"$$"+v.query,""),prompt:l??""})))),!c&&t.createElement("div",{className:p.nextInteractionHeight},t.createElement("div",{className:(0,o.cx)(p.afterButtons,p.textPadding)},t.createElement(C.$n,{onClick:()=>{f(!0),r()},"data-testid":Y.refinePrompt,fill:"outline",variant:"secondary",size:"md"},g)),t.createElement("div",{className:(0,o.cx)(p.textPadding,p.floatRight)},t.createElement(C.$n,{fill:"outline",variant:"secondary",size:"md",onClick:s},"Cancel"))))}var Xe=i(96832),j=i(65418),be=i(17172),ne=i(34867),xe=i(20227);async function Ta(e){return(await(0,be.AI)().post("/api/plugins/grafana-llm-app/resources/vector/search",e,{headers:{"Content-Type":"application/json"}})).results}let Se=!1;const _e=async()=>{try{if(!(await(0,be.AI)().get(`${xe.oL}/settings`,void 0,void 0,{showSuccessAlert:!1,showErrorAlert:!1})).enabled)return{enabled:!1,ok:!1,error:"The Grafana LLM plugin is not enabled."}}catch(n){return(0,ne.MD)(String(n)),(0,ne.MD)("Failed to check if the vector service is enabled. This is expected if the Grafana LLM plugin is not installed, and the above error can be ignored."),Se=!0,{enabled:!1,ok:!1,error:"The Grafana LLM plugin is not installed."}}let e;try{e=await(0,be.AI)().get(`${xe.oL}/health`,void 0,void 0,{showSuccessAlert:!1,showErrorAlert:!1})}catch(n){return Se||((0,ne.MD)(String(n)),(0,ne.MD)("Failed to check if vector service is enabled. This is expected if the Grafana LLM plugin is not installed, and the above error can be ignored."),Se=!0),{enabled:!1,ok:!1,error:"The Grafana LLM plugin is not installed."}}const{details:a}=e;return a?.version!==void 0&&(0,xe.$q)(a.version),a?.vector===void 0?{enabled:!1,ok:!1,error:"The Grafana LLM plugin is outdated; please update it."}:typeof a.vector=="boolean"?{enabled:a.vector,ok:a.vector}:a.vector},Qn=async()=>{const e=await _e();return e.enabled&&e.ok};var Ce=i(32799);const Na=`You are an expert in Prometheus, the event monitoring and alerting application.

You are given relevant PromQL documentation, a type and description for a Prometheus metric, and a PromQL query on that metric. Using the provided information for reference, please explain what the output of a given query is in 1 sentences. Do not walk through what the functions do separately, make your answer concise. 

Input will be in the form:


PromQL Documentation:
<PromQL documentation>

PromQL Metrics Metadata:
<metric_name>(<metric type of the metric queried>): <description of what the metric means>

PromQL Expression: 
<PromQL query>

Examples of input and output
----------
PromQL Documentation:
A counter is a cumulative metric that represents a single monotonically increasing counter whose value can only increase or be reset to zero on restart. For example, you can use a counter to represent the number of requests served, tasks completed, or errors.
topk (largest k elements by sample value)
sum (calculate sum over dimensions)
rate(v range-vector) calculates the per-second average rate of increase of the time series in the range vector. Breaks in monotonicity (such as counter resets due to target restarts) are automatically adjusted for. 

PromQL Metrics Metadata:
traces_exporter_sent_spans(counter): Number of spans successfully sent to destination.

PromQL Expression:
topk(3, sum by(cluster) (rate(traces_exporter_sent_spans{exporter="otlp"}[5m])))

This query is trying to answer the question:
What is the top 3 clusters that have successfully sent the most number of spans to the destination?
`;function Qa({documentation:e,metricName:a,metricType:n,metricMetadata:s,query:r}){return e===""&&(e="No documentation provided."),s===""&&(s="No description provided."),`
        PromQL Documentation: 
        ${e}

        PromQL Metrics Metadata:
        ${a}(${n}): ${s}

        PromQL Expression: 
        ${r}

        This query is trying to answer the question:
    `}const wa=`You are a Prometheus Query Language (PromQL) expert assistant inside Grafana.
When the user asks a question, respond with a valid PromQL query and only the query.

To help you answer the question, you will receive:
- List of potentially relevant PromQL templates with descriptions, ranked by semantic search score
- Prometheus metric
- Metric type
- Available Prometheus metric labels
- User question

Policy:
- Do not invent labels names, you can only use the available labels
- For rate queries, use the $__rate_interval variable`;function $a({promql:e,question:a,metricType:n,labels:s,templates:r}){return r===""?r="No templates provided.":r=r.replace(/\n/g,`
  `),`Relevant PromQL templates:
  ${r}
  
  Prometheus metric: ${e}
  Metric type: ${n}
  Available Prometheus metric labels: ${s}
  User question: ${a}
  
  \`\`\`promql`}const Pe=(0,De.Z0)({name:"metrics-modal-state",initialState:et(),reducers:{showExplainer:(e,a)=>{e.showExplainer=a.payload},showStartingMessage:(e,a)=>{e.showStartingMessage=a.payload},indicateCheckbox:(e,a)=>{e.indicateCheckbox=a.payload},askForQueryHelp:(e,a)=>{e.askForQueryHelp=a.payload},addInteraction:(e,a)=>{const n=tt(a.payload.suggestionType,a.payload.isLoading),s=e.interactions;e.interactions=s.concat([n])},updateInteraction:(e,a)=>{const n=a.payload.idx,s=a.payload.interaction;e.interactions=e.interactions.map((r,m)=>m===n?s:r)}}});function et(e,a){return{query:e??{metric:"",labels:[],operations:[]},showExplainer:!1,showStartingMessage:a??!0,indicateCheckbox:!1,askForQueryHelp:!1,interactions:[]}}function tt(e,a){return{suggestionType:e,prompt:"",suggestions:[],isLoading:a??!1,explanationIsLoading:!1}}const re=[{template:"metric_a{}",description:'Get the data for "metric_a"'},{template:"avg by(c) (metric_a{})",description:'Average of all series in "metric_a" grouped by the label "c"'},{template:"count by(d) (metric_a{})",description:'Number of series in the metric "metric_a" grouped by the label "d"'},{template:"sum by(g) (sum_over_time(metric_a{}[1h]))",description:'For each series in the metric "metric_a", sum all values over 1 hour, then group those series by label "g" and sum.'},{template:"count(metric_a{})",description:'Count of series in the metric "metric_a"'},{template:"(metric_a{})",description:'Get the data for "metric_a"'},{template:"count_over_time(metric_a{}[1h])",description:"Number of series of metric_a in a 1 hour interval"},{template:"changes(metric_a{}[1m])",description:"Number of times the values of each series in metric_a have changed in 1 minute periods"},{template:"count(count by(g) (metric_a{}))",description:"Total number of series in metric_a"},{template:"last_over_time(metric_a{}[1h])",description:"For each series in metric_a, get the last value in the 1 hour period."},{template:"sum by(g) (count_over_time(metric_a{}[1h]))",description:'Grouped sum over the label "g" of the number of series of metric_a in a 1 hour period'},{template:"count(metric_a{} == 99)",description:"Number of series of metric_a that have value 99"},{template:"min(metric_a{})",description:'At each timestamp, find the minimum of all series of the metric "metric_a"'},{template:"metric_a{} != 99",description:"Series of metric_a which do not have the value 99"},{template:"metric_a{} - 99",description:"metric_a minus 99"},{template:"quantile_over_time(0.99,metric_a{}[1h])",description:"The 99th quantile of values of metric_a in 1 hour"},{template:'count_values("aaaa",metric_a{})',description:'Count number of label values for a label named "aaaa"'}],Ia=[{template:"sum by(d) (rate(metric_a{}[1h]))",description:'Sum of the rate of increase or decrease of the metric "metric_a" per 1 hour period, grouped by the label "d"'},{template:"rate(metric_a{}[1m])",description:'Rate of change of the metric "metric_a" over 1 minute'},{template:"sum by(a) (increase(metric_a{}[5m]))",description:'Taking the metric "metric_a" find the increase in 5 minute periods of each series and aggregate sum over the label "a"'},{template:"sum(rate(metric_a{}[1m]))",description:'Total rate of change of all series of metric "metric_a" in 1 minute intervals'},{template:"sum(increase(metric_a{}[10m]))",description:'Total increase for each series of metric "metric_a" in 10 minute intervals'},{template:"increase(metric_a{}[1h])",description:'Increase in all series of "metric_a" in 1 hour period'},{template:"sum by(d) (irate(metric_a{}[1h]))",description:'Sum of detailed rate of change of the metric "metric_a" over 1 hour grouped by label "d"'},{template:"irate(metric_a{}[1h])",description:'Detailed rate of change of the metric "metric_a" over 1 hour'},{template:"avg by(d) (rate(metric_a{}[1h]))",description:'Taking the rate of change of the metric "metric_a" in a 1 hour period, group by the label "d" and find the average of each group'},{template:"topk(5,sum by(g) (rate(metric_a{}[1h])))",description:'Top 5 of the summed groups "g" of the rate of change of metric_a'},{template:"sum(rate(metric_a{}[1h])) / sum(rate(metric_a{}[1h]))",description:"Relative sums of metric_a with different labels"},{template:"histogram_quantile(99,rate(metric_a{}[1h]))",description:"99th percentile of the rate of change of metric_a in 1 hour periods"},{template:"avg(rate(metric_a{}[1m]))",description:"Average of the rate of all series of metric_a in 1 minute periods"},{template:"rate(metric_a{}[5m]) > 99",description:"Show series of metric_a only if their rate over 5 minutes is greater than 99"},{template:"count by(g) (rate(metric_a{}[1h]))",description:'Count of series of metric_a over all labels "g"'}],Ma=[{template:"histogram_quantile(99,sum by(le) (rate(metric_a{}[1h])))",description:'Calculate the rate at which the metric "metric_a" is increasing or decreasing, summed over each bucket label "le", and then calculates the 99th percentile of those rates.'},{template:"histogram_quantile(99,sum by(g) (metric_a{}))",description:'99th percentile of the sum of metric_a grouped by label "g"'},{template:"histogram_quantile(99,sum by(g) (irate(metric_a{}[1h])))",description:'99th percentile of the grouped by "g" sum of the rate of each series in metric_a in an hour'},{template:"histogram_quantile(99,metric_a{})",description:"99th percentile of metric_a"}],La=[{template:"sum by(c) (metric_a{})",description:'Sum the metric "metric_a" by each value in label "c"'},{template:"sum(metric_a{})",description:'Total sum of all the series of the metric named "metric_a"'},{template:"max by(dd) (metric_a{})",description:'Grouping the series the metric "metric_a" by the label "dd", get the maximum value of each group'},{template:"max(metric_a{})",description:'Maximum value of all series of the metric "metric_a" '},{template:"avg(metric_a{})",description:'Average value of all the series of metric "metric_a"'},{template:"metric_a{} > 99",description:'Show only the series of metric "metric_a" which currently have value greater than 99'},{template:"metric_a{} / 99",description:'Values for "metric_a" all divided by 99'},{template:"metric_a{} == 99",description:"Show series of metric_a that have value 99"},{template:"sum_over_time(metric_a{}[1h])",description:"Sum each series of metric_a over 1 hour"},{template:"avg_over_time(metric_a{}[1h])",description:"Average of each series of metric_a in a 1 hour period"},{template:"sum(sum_over_time(metric_a{}[1h]))",description:"Sum of all values in all series in a 1 hour period"},{template:"delta(metric_a{}[1m])",description:'Span or delta (maximum - minimum) of values of the metric "metric_a" in a 1 minute period. '},{template:"avg by(g) (avg_over_time(metric_a{}[1h]))",description:'For 1 hour, take each series and find the average, then group by label "g" and find the average of each group'},{template:"max_over_time(metric_a{}[1h])",description:'Maximum values of each series in metric "metric_a" in a 1 hour period'},{template:"metric_a{} * 99",description:"Values of metric_a multiplied by 99"},{template:"metric_a{} < 99",description:"Series of metric_a that have values less than 99"},{template:"max by() (max_over_time(metric_a{}[1h]))",description:"Find maximum value of all series in 1 hour periods"},{template:"topk(99,metric_a{})",description:"First 5 series of metric_a that have the highest values"},{template:"min by(g) (metric_a{})",description:'Minimum values of the series of metric_a grouped by label "g"'},{template:"topk(10,sum by(g) (metric_a{}))",description:"Top 10 of the series of metric_a grouped and summed by the label 'g'"},{template:"avg(avg_over_time(metric_a{}[1h]))",description:"Average of all values inside a 1 hour period"},{template:"quantile by(h) (0.95,metric_a{})",description:'Calculate 95th percentile of metric_a when aggregated by the label "h"'},{template:"avg by(g) (metric_a{} > 99)",description:'Taking all series of metric_a with value greater than 99, group by label "g" and find the average of each group'},{template:"sum(metric_a{}) / 99",description:"Sum of all series of metric_a divided by 99"},{template:"count(sum by(g) (metric_a{}))",description:'Number of series of metric_a grouped by the label "g"'},{template:"max(max_over_time(metric_a{}[1h]))",description:"Find the max value of all series of metric_a in a 1 hour period"}];function H(e,a,n){return{query:e.template.replace("metric_a",a).replace("{}",n),explanation:e.description.replace("metric_a",a)}}function ka(e,a,n){let s=[];switch(a){case"counter":s=s.concat(Ia.map(r=>H(r,e,n)).sort(()=>Math.random()-.5).slice(0,2)),s=s.concat(re.map(r=>H(r,e,n)).sort(()=>Math.random()-.5).slice(0,3));break;case"gauge":s=s.concat(La.map(r=>H(r,e,n)).sort(()=>Math.random()-.5).slice(0,2)),s=s.concat(re.map(r=>H(r,e,n)).sort(()=>Math.random()-.5).slice(0,3));break;case"histogram":s=s.concat(Ma.map(r=>H(r,e,n)).sort(()=>Math.random()-.5).slice(0,2)),s=s.concat(re.map(r=>H(r,e,n)).sort(()=>Math.random()-.5).slice(0,3));break;default:s=s.concat(re.map(r=>H(r,e,n)).sort(()=>Math.random()-.5).slice(0,5));break}return s}const at="gpt-3.5-turbo-1106",Aa="grafana.promql.templates",{updateInteraction:Te}=Pe.actions;function Fa(e,a,n){let s="",r="";const m=(0,R.u)(e);n.languageProvider.metricsMetadata&&(r=(0,Ce.AU)(a,n.languageProvider.metricsMetadata)??"",s=(0,Ce.pK)(a,n.languageProvider.metricsMetadata)??"");const u=m.query.operations.map(l=>{const c=F.z.getOperationDef(l.id);if(!c)return"";const f=c.renderer(l,c,"<expr>"),h=c.explainHandler?c.explainHandler(l,c):c.documentation;return h?`### ${f}:
${h}`:""}).filter(l=>l!=="").join(`
`);return[{role:"system",content:Na},{role:"user",content:Qa({documentation:u,metricName:a,metricType:r,metricMetadata:s,query:e})}]}function Ba({promql:e,question:a,metricType:n,labels:s,templates:r}){return[{role:"system",content:wa},{role:"user",content:$a({promql:e,question:a,metricType:n,labels:s,templates:r})}]}async function nt(e,a,n,s,r,m){const u=s.suggestions[r].query,l=Fa(u,n.metric,m),c=s;return j.qH({model:at,messages:l,temperature:0}).pipe(j.qA()).subscribe(f=>{const h=c.suggestions.map((x,E)=>r===E?{query:c.suggestions[r].query,explanation:f}:x),p={idx:a,interaction:{...c,suggestions:h,explanationIsLoading:!1}};e(Te(p))})}function se(e,a){for(const n of e)if(!a.includes(n))return!1;return!0}function Oa(e,a){if(new Set(["up","scrape_duration_seconds","scrape_samples_post_metric_relabeling","scrape_series_added","scrape_samples_scraped","ALERTS","ALERTS_FOR_STATE"]).has(e))return"counter";if(e.startsWith(":"))return"gauge";if(e.endsWith("_info")||e.endsWith("_created")||e.endsWith("_total"))return"counter";const s=e.lastIndexOf("_");if(s<0)return"gauge";const[r,m]=[e.slice(0,s),e.slice(s+1)];if(["bucket","count","sum"].includes(m)){let l=[`${r}_bucket`,`${r}_count`,`${r}_sum`,r];return se(l,a)?"histogram,summary":(l=[`${r}_bucket`,`${r}_count`,`${r}_sum`],se(l,a)?"histogram":(l=[`${r}_sum`,`${r}_count`,r],se(l,a)?"summary":"counter"))}const u=[`${e}_sum`,`${e}_count`,e];return se(u,a)?a.includes(`${e}_bucket`)?"histogram,summary":"summary":"gauge"}function Ra(e){return e.map(a=>({metric_type:{$eq:a}}))}function za(e){return e.endsWith("_bucket")||e.endsWith("_count")||e.endsWith("_sum")?e.slice(0,e.lastIndexOf("_")):e}async function Da(){const e=j.vK().then(n=>n.ok),a=_e().then(n=>n.ok);return Promise.all([e,a]).then(n=>n.every(s=>s))}async function Ne(e,a,n,s,r,m){const u=m||tt(M.Historical);let l="";if(r.languageProvider.metricsMetadata||await r.languageProvider.loadMetricsMetadata(),r.languageProvider.metricsMetadata){const c=za(n.metric);l=(0,Ce.AU)(c,r.languageProvider.metricsMetadata)??""}if(l===""&&(l=Oa(n.metric,r.languageProvider.metrics)),u.suggestionType===M.Historical)return new Promise(c=>setTimeout(()=>{const f=ka(n.metric,l,F.z.renderLabels(n.labels)),h={idx:a,interaction:{...u,suggestions:f,isLoading:!1}};e(Te(h)),c()},1e3));{const c=await r.languageProvider.fetchLabelsWithMatch(n.metric);let f={metric:n.metric,labels:Object.keys(c).filter(E=>E!=="__name__").join(",")},h=[];m?.suggestionType===M.AI&&(f={...f,prompt:m.prompt},h=await Ta({query:m.prompt,collection:Aa,topK:5,filter:{$or:Ra(l.split(",").concat(["*"]))}}),(0,k.rR)("grafana_prometheus_promqail_vector_results",{metric:n.metric,prompt:m.prompt,results:h}));const p=h.map(E=>`${E.payload.promql} | ${E.payload.description} (score=${(E.score*100).toFixed(1)})`).join(`
`),x=Ba({promql:n.metric,question:m?m.prompt:"",metricType:l,labels:s.join(", "),templates:p});return j.qH({model:at,messages:x,temperature:.5}).pipe(j.qA()).subscribe(E=>{const g={idx:a,interaction:{...u,suggestions:[{query:E,explanation:""}],isLoading:!1}};e(Te(g))})}}const{showStartingMessage:Wa,indicateCheckbox:Ha,addInteraction:oe,updateInteraction:Qe}=Pe.actions,we="SKIP_STARTING_MESSAGE",qa=e=>{const{query:a,closeDrawer:n,onChange:s,datasource:r}=e,m=z.A.getBool(we,!1),[u,l]=(0,t.useReducer)(Pe.reducer,et(a,!m)),[c,f]=(0,t.useState)([]),h=u.interactions.reduce((y,d)=>y+d.suggestions.length,0),p=(0,t.useRef)(null),x=()=>{p&&p?.current?.scrollIntoView({behavior:"smooth"})};(0,t.useEffect)(()=>{x()},[u.interactions.length,h]),(0,t.useEffect)(()=>{(async()=>{let d=await r.languageProvider.fetchLabelsWithMatch(a.metric);f(Object.keys(d))})()},[a,r]);const E=(0,$.$j)(),g=ie(E);return t.createElement("div",{className:g.containerPadding},t.createElement("div",{className:g.header},t.createElement("h3",null,"Query advisor"),t.createElement(C.$n,{icon:"times",fill:"text",variant:"secondary",onClick:n})),t.createElement("div",null,t.createElement("div",{className:g.iconSection},t.createElement("img",{src:Xe,alt:"AI logo color"})," Assistant"),u.showStartingMessage?t.createElement(t.Fragment,null,t.createElement("div",{className:g.dataList},t.createElement("ol",null,t.createElement("li",{className:g.textPadding},"Query Advisor suggests queries based on a metric and requests you type in."),t.createElement("li",{className:g.textPadding},"Query Advisor sends Prometheus metrics, labels and metadata to the LLM provider you've configured. Be sure to align its usage with your company's internal policies."),t.createElement("li",{className:g.textPadding},"An AI-suggested query may not fully answer your question. Always take a moment to understand a query before you use it."))),t.createElement(ya.F,{title:"",severity:"info",key:"promqail-llm-app",className:(0,o.cx)(g.textPadding,g.noMargin)},"Query Advisor is currently in Private Preview. Feedback is appreciated and can be provided on explanations and suggestions."),t.createElement("div",{className:g.textPadding},t.createElement(Ve.S,{checked:u.indicateCheckbox,value:u.indicateCheckbox,onChange:()=>{const y=z.A.getBool(we,!1);z.A.set(we,!y),l(Ha(!y))},label:"Don't show this message again"})),t.createElement("div",{className:g.rightButtonsWrapper},t.createElement("div",{className:g.rightButtons},t.createElement(C.$n,{className:g.leftButton,fill:"outline",variant:"secondary",onClick:n},"Cancel"),t.createElement(C.$n,{fill:"solid",variant:"primary",onClick:()=>l(Wa(!1)),"data-testid":Y.securityInfoButton},"Continue")))):t.createElement("div",{className:g.bodySmall},t.createElement("div",{className:g.textPadding},"Here is the metric you have selected:"),t.createElement("div",{className:g.infoContainerWrapper},t.createElement("div",{className:g.infoContainer},t.createElement("table",{className:g.metricTable},t.createElement("tbody",null,t.createElement("tr",null,t.createElement("td",{className:g.metricTableName},"metric"),t.createElement("td",{className:g.metricTableValue},u.query.metric),t.createElement("td",null,t.createElement(C.$n,{fill:"outline",variant:"secondary",onClick:n,className:g.metricTableButton,size:"sm"},"Choose new metric"))),u.query.labels.map((y,d)=>{const b=d===0?"labels":"";return t.createElement("tr",{key:`${y.label}-${d}`},t.createElement("td",null,b),t.createElement("td",{className:g.metricTableValue},`${y.label}${y.op}${y.value}`),t.createElement("td",null," "))}))))),!u.askForQueryHelp&&u.interactions.length===0&&t.createElement(t.Fragment,null,t.createElement("div",{className:g.queryQuestion},"Do you know what you want to query?"),t.createElement("div",{className:g.rightButtonsWrapper},t.createElement("div",{className:g.rightButtons},t.createElement(C.$n,{className:g.leftButton,fill:"solid",variant:"secondary","data-testid":Y.clickForHistorical,onClick:()=>{const d=M.Historical;l(oe({suggestionType:d,isLoading:!0})),(0,k.rR)("grafana_prometheus_promqail_know_what_you_want_to_query",{promVisualQuery:a,doYouKnow:"no"}),Ne(l,0,a,c,r)}},"No"),t.createElement(C.$n,{fill:"solid",variant:"primary","data-testid":Y.clickForAi,onClick:()=>{(0,k.rR)("grafana_prometheus_promqail_know_what_you_want_to_query",{promVisualQuery:a,doYouKnow:"yes"});const y=!1,d=M.AI;l(oe({suggestionType:d,isLoading:y}))}},"Yes")))),u.interactions.map((y,d)=>t.createElement("div",{key:d},y.suggestionType===M.AI?t.createElement(t.Fragment,null,t.createElement("div",{className:g.textPadding},"What kind of data do you want to see with your metric?"),t.createElement("div",{className:(0,o.cx)(g.secondaryText,g.bottomMargin)},t.createElement("div",null,"You do not need to enter in a metric or a label again in the prompt."),t.createElement("div",null,"Example: I want to monitor request latency, not errors.")),t.createElement("div",{className:g.inputPadding},t.createElement(va.p,{value:y.prompt,spellCheck:!1,placeholder:"Enter prompt",disabled:y.suggestions.length>0,onChange:b=>{const v=b.currentTarget.value,P={idx:d,interaction:{...y,prompt:v}};l(Qe(P))}})),y.suggestions.length===0?y.isLoading?t.createElement(t.Fragment,null,t.createElement("div",{className:g.loadingMessageContainer},"Waiting for OpenAI ",t.createElement(Ee.y,{className:g.floatRight}))):t.createElement(t.Fragment,null,t.createElement("div",{className:g.rightButtonsWrapper},t.createElement("div",{className:g.rightButtons},t.createElement(C.$n,{className:g.leftButton,fill:"outline",variant:"secondary",onClick:n},"Cancel"),t.createElement(C.$n,{className:g.leftButton,fill:"outline",variant:"secondary",onClick:()=>{const b={...y,suggestionType:M.Historical,isLoading:!0},v={idx:d,interaction:b};(0,k.rR)("grafana_prometheus_promqail_suggest_query_instead",{promVisualQuery:a}),l(Qe(v)),Ne(l,d,a,c,r,b)}},"Suggest queries instead"),t.createElement(C.$n,{fill:"solid",variant:"primary","data-testid":Y.submitPrompt+d,onClick:()=>{const b={...y,isLoading:!0},v={idx:d,interaction:b};(0,k.rR)("grafana_prometheus_promqail_prompt_submitted",{promVisualQuery:a,prompt:y.prompt}),l(Qe(v)),Ne(l,d,a,c,r,y)}},"Submit")))):t.createElement(Je,{suggestionType:M.AI,querySuggestions:y.suggestions,closeDrawer:n,nextInteraction:()=>{const v=M.AI;l(oe({suggestionType:v,isLoading:!1}))},queryExplain:b=>y.suggestions[b].explanation===""?nt(l,d,a,y,b,r):y.suggestions[b].explanation,onChange:s,prompt:y.prompt??""})):y.isLoading?t.createElement(t.Fragment,null,t.createElement("div",{className:g.loadingMessageContainer},"Waiting for OpenAI ",t.createElement(Ee.y,{className:g.floatRight}))):t.createElement(Je,{suggestionType:M.Historical,querySuggestions:y.suggestions,closeDrawer:n,nextInteraction:()=>{const v=M.AI;l(oe({suggestionType:v,isLoading:!1}))},queryExplain:b=>y.suggestions[b].explanation===""?nt(l,d,a,y,b,r):y.suggestions[b].explanation,onChange:s,prompt:y.prompt??""}))))),t.createElement("div",{ref:p}))},ie=e=>({sectionPadding:(0,o.css)({padding:"20px"}),header:(0,o.css)({display:"flex",button:{marginLeft:"auto"}}),iconSection:(0,o.css)({padding:"0 0 10px 0",color:`${e.colors.text.secondary}`,img:{paddingRight:"4px"}}),rightButtonsWrapper:(0,o.css)({display:"flex"}),rightButtons:(0,o.css)({marginLeft:"auto"}),leftButton:(0,o.css)({marginRight:"10px"}),dataList:(0,o.css)({padding:"0px 28px 0px 28px"}),textPadding:(0,o.css)({paddingBottom:"12px"}),containerPadding:(0,o.css)({padding:"28px"}),infoContainer:(0,o.css)({border:`${e.colors.border.strong}`,padding:"16px",backgroundColor:`${e.colors.background.secondary}`,borderRadius:"8px",borderBottomLeftRadius:0}),infoContainerWrapper:(0,o.css)({paddingBottom:"24px"}),metricTable:(0,o.css)({width:"100%"}),metricTableName:(0,o.css)({width:"15%"}),metricTableValue:(0,o.css)({fontFamily:`${e.typography.fontFamilyMonospace}`,fontSize:`${e.typography.bodySmall.fontSize}`,overflow:"scroll",textWrap:"nowrap",maxWidth:"150px",width:"60%",maskImage:"linear-gradient(to right, rgba(0, 0, 0, 1) 90%, rgba(0, 0, 0, 0))"}),metricTableButton:(0,o.css)({float:"right"}),queryQuestion:(0,o.css)({textAlign:"end",padding:"8px 0"}),secondaryText:(0,o.css)({color:`${e.colors.text.secondary}`}),loadingMessageContainer:(0,o.css)({border:`${e.colors.border.strong}`,padding:"16px",backgroundColor:`${e.colors.background.secondary}`,marginBottom:"20px",borderRadius:"8px",color:`${e.colors.text.secondary}`,fontStyle:"italic"}),floatRight:(0,o.css)({float:"right"}),codeText:(0,o.css)({fontFamily:`${e.typography.fontFamilyMonospace}`,fontSize:`${e.typography.bodySmall.fontSize}`}),bodySmall:(0,o.css)({fontSize:`${e.typography.bodySmall.fontSize}`}),explainPadding:(0,o.css)({paddingLeft:"26px"}),bottomMargin:(0,o.css)({marginBottom:"20px"}),topPadding:(0,o.css)({paddingTop:"22px"}),doc:(0,o.css)({textDecoration:"underline"}),afterButtons:(0,o.css)({display:"flex",justifyContent:"flex-end"}),feedbackStyle:(0,o.css)({margin:0,textAlign:"right",paddingTop:"22px",paddingBottom:"22px"}),nextInteractionHeight:(0,o.css)({height:"88px"}),center:(0,o.css)({display:"flex",alignItems:"center",justifyContent:"center"}),inputPadding:(0,o.css)({paddingBottom:"24px"}),querySuggestion:(0,o.css)({display:"flex",flexWrap:"nowrap"}),longCode:(0,o.css)({width:"90%",textWrap:"nowrap",overflow:"scroll",maskImage:"linear-gradient(to right, rgba(0, 0, 0, 1) 90%, rgba(0, 0, 0, 0))",div:{display:"inline-block"}}),useButton:(0,o.css)({marginLeft:"auto"}),suggestionFeedback:(0,o.css)({textAlign:"left"}),feedbackQuestion:(0,o.css)({display:"flex",padding:"8px 0px",h6:{marginBottom:0},i:{marginTop:"1px"}}),explationTextInput:(0,o.css)({paddingLeft:"24px"}),submitFeedback:(0,o.css)({padding:"16px 0"}),noMargin:(0,o.css)({margin:0}),enableButtonTooltip:(0,o.css)({padding:8}),enableButtonTooltipText:(0,o.css)({color:`${e.colors.text.secondary}`,ul:{marginLeft:16}}),link:(0,o.css)({color:`${e.colors.text.link} !important`})}),Y={promQail:"prom-qail",securityInfoButton:"security-info-button",clickForHistorical:"click-for-historical",clickForAi:"click-for-ai",submitPrompt:"submit-prompt",refinePrompt:"refine-prompt"};function Ga(e){const{llmAppEnabled:a,metric:n,setShowDrawer:s}=e,r=!a,m=!n,u=(0,$.$j)(),l=ie(u),c=()=>t.createElement(C.$n,{variant:"secondary",onClick:()=>{(0,k.rR)("grafana_prometheus_promqail_ai_button_clicked",{metric:n}),s(!0)},disabled:!n||!a,"data-testid":A.Tp.components.DataSource.Prometheus.queryEditor.builder.queryAdvisor},t.createElement("img",{height:16,src:Xe,alt:"AI logo black and white"}),"\xA0","Get query suggestions"),f=t.createElement(G.m,{content:"First, select a metric.",placement:"bottom-end"},c()),h=t.createElement(G.m,{interactive:!0,placement:"auto-end",content:t.createElement("div",{className:l.enableButtonTooltip},t.createElement("h6",null,"Query Advisor is disabled"),t.createElement("div",{className:l.enableButtonTooltipText},"To enable Query Advisor you must:"),t.createElement("div",{className:l.enableButtonTooltipText},t.createElement("ul",null,t.createElement("li",null,t.createElement("a",{href:"https://grafana.com/docs/grafana-cloud/alerting-and-irm/machine-learning/llm-plugin/",target:"_blank",rel:"noreferrer noopener",className:l.link},"Install and enable the LLM plugin")),t.createElement("li",null,"Select a metric"))))},c());return r?h:m?f:c()}const rt=pe.$.featureToggles.prometheusPromQAIL,$e=t.memo(e=>{const{datasource:a,query:n,onChange:s,onRunQuery:r,data:m,showExplain:u}=e,[l,c]=(0,t.useState)(),[f,h]=(0,t.useState)(!1),[p,x]=(0,t.useState)(!1),E={grammar:ue.Ay,name:"promql"},g=a.getInitHints();return(0,t.useEffect)(()=>{async function y(){const d=await Da();x(d)}y()},[]),t.createElement(t.Fragment,null,rt&&f&&t.createElement(Bt._,{closeOnMaskClick:!1,onClose:()=>h(!1)},t.createElement(qa,{query:n,closeDrawer:()=>h(!1),onChange:s,datasource:a})),t.createElement(ge.U,null,t.createElement(ua.I,{query:n,onChange:s,datasource:a})),g.length?t.createElement("div",{className:"query-row-break"},t.createElement("div",{className:"prom-query-field-info text-warning"},g[0].label," ",g[0].fix?t.createElement("button",{type:"button",className:"text-warning"},g[0].fix.label):null)):null,u&&t.createElement(Ot.r,{stepNumber:1,title:t.createElement(me.Z,{query:`${n.metric} ${F.z.renderLabels(n.labels)}`,lang:E})},ha.W),t.createElement(ca.i,null,t.createElement(ra,{queryModeller:F.z,datasource:a,query:n,onChange:s,onRunQuery:r,highlightedOp:l}),rt&&t.createElement("div",{className:(0,o.css)({padding:"0 0 0 6px"})},t.createElement(Ga,{llmAppEnabled:p,metric:n.metric,setShowDrawer:h})),t.createElement("div",{"data-testid":A.Tp.components.DataSource.Prometheus.queryEditor.builder.hints},t.createElement(Ue,{datasource:a,query:n,onChange:s,data:m,queryModeller:F.z,buildVisualQueryFromString:R.u}))),u&&t.createElement(la.k,{lang:E,query:n,stepNumber:2,queryModeller:F.z,onMouseEnter:y=>c(y),onMouseLeave:()=>c(void 0)}),n.binaryQueries&&n.binaryQueries.length>0&&t.createElement(fa,{query:n,datasource:a,onChange:s,onRunQuery:r,showExplain:u}))});$e.displayName="PromQueryBuilder";var Va=i(97801);function Ua({query:e}){return e?t.createElement(ge.U,null,t.createElement(Va.B,null,t.createElement(me.Z,{query:e,lang:{grammar:ue.Ay,name:"promql"}}))):null}var Ka=i(13567);const Ie=pe.$.featureToggles.prometheusMetricEncyclopedia;function ja(e){const{query:a,onChange:n,onRunQuery:s,datasource:r,data:m,showExplain:u}=e,[l,c]=(0,t.useReducer)(st.reducer,{expr:a.expr});(0,t.useEffect)(()=>{c(Ja(a.expr)),Ie&&c(Xa({useBackend:a.useBackend??!1,disableTextWrap:a.disableTextWrap??!1,fullMetaSearch:a.fullMetaSearch??!1,includeNullMetadata:a.includeNullMetadata??!0}))},[a]),(0,t.useEffect)(()=>{r.languageProvider.start(m?.timeRange)},[m?.timeRange,r.languageProvider]);const f=h=>{const p=F.z.renderQuery(h);if(c(Za({visQuery:h,expr:p})),Ie){const x=(0,Ka.mt)(h);n({...e.query,expr:p,...x})}else n({...e.query,expr:p})};return l.visQuery?t.createElement(t.Fragment,null,t.createElement($e,{query:l.visQuery,datasource:r,onChange:f,onRunQuery:s,data:m,showExplain:u}),t.createElement(Ua,{query:a.expr})):null}const Ya={expr:""},st=(0,De.Z0)({name:"prom-builder-container",initialState:Ya,reducers:{visualQueryChange:(e,a)=>{e.expr=a.payload.expr,e.visQuery=a.payload.visQuery},exprChanged:(e,a)=>{if(!e.visQuery||e.expr!==a.payload){e.expr=a.payload;const n=(0,R.u)(a.payload??"");e.visQuery=n.query}},setMetricsModalSettings:(e,a)=>{e.visQuery&&Ie&&(e.visQuery.useBackend=a.payload.useBackend,e.visQuery.disableTextWrap=a.payload.disableTextWrap,e.visQuery.fullMetaSearch=a.payload.fullMetaSearch,e.visQuery.includeNullMetadata=a.payload.includeNullMetadata)}}}),{visualQueryChange:Za,exprChanged:Ja,setMetricsModalSettings:Xa}=st.actions;var V=i(81580),_a=i(79458),ot=i(38894),en=i(76892);function tn({datasource:e,onChange:a,query:n,...s}){const[r,m]=(0,t.useState)(null),u=(0,$.of)(an),l=(0,he.A)(r);(0,t.useEffect)(()=>{e.exemplarsAvailable?n.instant&&!n.range?(m("Exemplars are not available for instant queries"),a(!1)):(m(null),l&&!r&&a(!0)):(m("Exemplars for this query are not available"),a(!1))},[e.exemplarsAvailable,n.instant,n.range,a,l,r]);const c=(0,o.cx)({[u.activeIcon]:!!n.exemplar},u.eyeIcon);return t.createElement(en.c,{width:"auto","data-testid":s["data-testid"]},t.createElement(G.m,{content:r??""},t.createElement("div",{className:u.iconWrapper},"Exemplars",t.createElement(Ke.K,{name:"eye",tooltip:n.exemplar?"Disable query with exemplars":"Enable query with exemplars",disabled:!!r,className:c,onClick:()=>{a(!n.exemplar)}}))))}function an(e){return{eyeIcon:(0,o.css)`
      margin-left: ${e.spacing(2)};
    `,activeIcon:(0,o.css)`
      color: ${e.colors.primary.main};
    `,iconWrapper:(0,o.css)`
      display: flex;
      align-items: center;
    `}}const nn=(0,t.memo)(({query:e,datasource:a,onChange:n,onRunQuery:s})=>{const r=it(!0),m=(0,he.A)(e),u=(0,t.useCallback)(p=>{(!(0,O.isEqual)(e,m)||p!==e.exemplar)&&n({...e,exemplar:p})},[m,e,n]);function l(p){n({...e,interval:p})}function c(p){p.currentTarget.value!==e.interval&&l(p.currentTarget.value)}function f(p){p.key==="Enter"&&p.shiftKey&&s()}const h=lt(e,n);return t.createElement("div",{"aria-label":"Prometheus extra field",className:"gf-form-inline","data-testid":Me.extraFieldEditor},t.createElement("div",{"data-testid":Me.queryTypeField,className:(0,o.cx)("gf-form explore-input-margin",(0,o.css)`
            flex-wrap: nowrap;
          `),"aria-label":"Query type field"},t.createElement(ot.I,{width:"auto"},"Query type"),t.createElement(de.z,{options:r,value:e.range&&e.instant?"both":e.instant?"instant":"range",onChange:h})),t.createElement("div",{"data-testid":Me.stepField,className:(0,o.cx)("gf-form",(0,o.css)`
            flex-wrap: nowrap;
          `),"aria-label":"Step field"},t.createElement(ot.I,{width:6,tooltip:"Time units and built-in variables can be used here, for example: $__interval, $__rate_interval, 5s, 1m, 3h, 1d, 1y (Default if no unit is specified: s)"},"Min step"),t.createElement("input",{type:"text",className:"gf-form-input width-4",placeholder:"auto",onChange:c,onKeyDown:f,value:e.interval??""})),t.createElement(tn,{onChange:u,datasource:a,query:e}))});nn.displayName="PromExploreExtraField";function it(e){const a=[{value:"range",label:"Range",description:"Run query over a range of time"},{value:"instant",label:"Instant",description:'Run query against a single point in time. For this query, the "To" time is used'}];return e&&a.push({value:"both",label:"Both",description:"Run an Instant query and a Range query"}),a}function lt(e,a){return n=>{a(n==="instant"?{...e,instant:!0,range:!1,exemplar:!1}:n==="range"?{...e,instant:!1,range:!0}:{...e,instant:!0,range:!0})}}const Me={extraFieldEditor:"prom-editor-extra-field",stepField:"prom-editor-extra-field-step",queryTypeField:"prom-editor-extra-field-query-type"};var rn=i(42941),sn=i(83195);function on({title:e,children:a,collapsedInfo:n,queryStats:s}){const[r,m]=(0,rn.A)(!1),u=(0,$.of)(ln);return t.createElement("div",{className:u.wrapper},t.createElement(Oe.S,{className:u.collapse,collapsible:!0,isOpen:r,onToggle:m,label:t.createElement(D.B,{gap:0},t.createElement("h6",{className:u.title},e),!r&&t.createElement("div",{className:u.description},n.map((l,c)=>t.createElement("span",{key:c},l))))},t.createElement("div",{className:u.body},a)),s&&pe.$.featureToggles.lokiQuerySplitting&&t.createElement(G.m,{content:"Note: the query will be split into multiple parts and executed in sequence. Query limits will only apply each individual part."},t.createElement(We.I,{tabIndex:0,name:"info-circle",className:u.tooltip,size:"sm"})),s&&t.createElement("p",{className:u.stats},cn(s)))}const ln=e=>({collapse:(0,o.css)({backgroundColor:"unset",border:"unset",marginBottom:0,["> button"]:{padding:e.spacing(0,1)}}),wrapper:(0,o.css)({width:"100%",display:"flex",justifyContent:"space-between",alignItems:"baseline"}),title:(0,o.css)({flexGrow:1,overflow:"hidden",fontSize:e.typography.bodySmall.fontSize,fontWeight:e.typography.fontWeightMedium,margin:0}),description:(0,o.css)({color:e.colors.text.secondary,fontSize:e.typography.bodySmall.fontSize,fontWeight:e.typography.bodySmall.fontWeight,paddingLeft:e.spacing(2),gap:e.spacing(2),display:"flex"}),body:(0,o.css)({display:"flex",gap:e.spacing(2),flexWrap:"wrap"}),stats:(0,o.css)({margin:"0px",color:e.colors.text.secondary,fontSize:e.typography.bodySmall.fontSize}),tooltip:(0,o.css)({marginRight:e.spacing(.25)})}),cn=e=>e.message?e.message:`This query will process approximately ${mn(e)}.`,mn=e=>{const{text:a,suffix:n}=(0,sn.j_)("bytes")(e.bytes,1);return a+n},Le=[{label:"Auto",value:I.m_.Auto,description:"Only includes unique labels"},{label:"Verbose",value:I.m_.Verbose,description:"All label names and values"},{label:"Custom",value:I.m_.Custom,description:"Provide a naming template"}],ct=t.memo(({legendFormat:e,onChange:a,onRunQuery:n})=>{const s=mt(e),r=(0,t.useRef)(null),m=l=>{let c=l.currentTarget.value;c.length===0&&(c=I.m_.Auto),c!==e&&(a(c),n())},u=l=>{switch(l.value){case I.m_.Auto:a(I.m_.Auto);break;case I.m_.Custom:a("{{label_name}}"),setTimeout(()=>{r.current?.focus(),r.current?.setSelectionRange(2,12,"forward")},10);break;case I.m_.Verbose:a("");break}n()};return t.createElement(V.c,{label:"Legend",tooltip:"Series name override or template. Ex. {{hostname}} will be replaced with label value for hostname.","data-testid":A.Tp.components.DataSource.Prometheus.queryEditor.legend},t.createElement(t.Fragment,null,s===I.m_.Custom&&t.createElement(ae.D,{id:"legendFormat",minWidth:22,placeholder:"auto",defaultValue:e,onCommitChange:m,ref:r}),s!==I.m_.Custom&&t.createElement(W.l6,{inputId:"legend.mode",isSearchable:!1,placeholder:"Select legend mode",options:Le,width:22,onChange:u,value:Le.find(l=>l.value===s)})))});ct.displayName="PromQueryLegendEditor";function mt(e){return e===I.m_.Auto?I.m_.Auto:e==null||e===""?I.m_.Verbose:I.m_.Custom}function un(e){const a=mt(e);return a!==I.m_.Custom?Le.find(n=>n.value===a)?.label:e}const ut=t.memo(({query:e,app:a,onChange:n,onRunQuery:s})=>{const r=E=>{n({...e,format:E.value}),s()},m=E=>{n({...e,interval:E.currentTarget.value}),s()},u=it(a===L.Jk.Explore||a===L.Jk.Correlations||a===L.Jk.PanelEditor),l=lt(e,n),c=E=>{const g=E.currentTarget.checked;n({...e,exemplar:g}),s()},f=E=>{n({...e,intervalFactor:E.value}),s()},h=ke.find(E=>E.value===e.format)||ke[0],p=dn(e),x=u.find(E=>E.value===p).label;return t.createElement(ge.U,null,t.createElement("div",{"data-testid":A.Tp.components.DataSource.Prometheus.queryEditor.options},t.createElement(on,{title:"Options",collapsedInfo:pn(e,h.label,x,a)},t.createElement(ct,{legendFormat:e.legendFormat,onChange:E=>n({...e,legendFormat:E}),onRunQuery:s}),t.createElement(V.c,{label:"Min step",tooltip:t.createElement(t.Fragment,null,"An additional lower limit for the step parameter of the Prometheus query and for the"," ",t.createElement("code",null,"$__interval")," and ",t.createElement("code",null,"$__rate_interval")," variables.")},t.createElement(ae.D,{id:A.Tp.components.DataSource.Prometheus.queryEditor.step,type:"text","aria-label":"Set lower limit for the step parameter",placeholder:"auto",minWidth:10,onCommitChange:m,defaultValue:e.interval})),t.createElement(V.c,{label:"Format"},t.createElement(W.l6,{"data-testid":A.Tp.components.DataSource.Prometheus.queryEditor.format,value:h,allowCustomValue:!0,onChange:r,options:ke})),t.createElement(V.c,{label:"Type","data-testid":A.Tp.components.DataSource.Prometheus.queryEditor.type},t.createElement(de.z,{options:u,value:p,onChange:l})),dt(e,a)&&t.createElement(V.c,{label:"Exemplars"},t.createElement(_a.C,{value:e.exemplar||!1,onChange:c,id:A.Tp.components.DataSource.Prometheus.queryEditor.exemplars})),e.intervalFactor&&e.intervalFactor>1&&t.createElement(V.c,{label:"Resolution"},t.createElement(W.l6,{"aria-label":"Select resolution",isSearchable:!1,options:pt,onChange:f,value:pt.find(E=>E.value===e.intervalFactor)})))))});function dt(e,a){return!(a===L.Jk.UnifiedAlerting||!e.range)}function dn(e){return e.range&&e.instant?"both":e.instant?"instant":"range"}function pn(e,a,n,s){const r=[];return r.push(`Legend: ${un(e.legendFormat)}`),r.push(`Format: ${a}`),r.push(`Step: ${e.interval??"auto"}`),r.push(`Type: ${n}`),dt(e,s)&&(e.exemplar?r.push("Exemplars: true"):r.push("Exemplars: false")),r}ut.displayName="PromQueryBuilderOptions";var gn=i(63492);const ke=[{label:"Time series",value:"time_series"},{label:"Table",value:"table"},{label:"Heatmap",value:"heatmap"}],pt=(0,O.map)([1,2,3,4,5,10],e=>({value:e,label:"1/"+e})),gt=t.memo(e=>{const{onChange:a,onRunQuery:n,data:s,app:r,onAddQuery:m,datasource:{defaultEditor:u},queries:l}=e,[c,f]=(0,t.useState)(!1),[h,p]=(0,t.useState)(!1),[x,E]=(0,t.useState)(!1),{flag:g,setFlag:y}=wt(Tt),d=Ft(e.query,r,u),b=d.editorMode,v=(0,t.useCallback)(S=>{if((0,k.rR)("user_grafana_prometheus_editor_mode_clicked",{newEditor:S,previousEditor:d.editorMode??"",newQuery:!d.expr,app:r??""}),S===B.f.Builder&&(0,R.u)(d.expr||"").errors.length){f(!0);return}ze(d,S,a)},[a,d,r]);(0,t.useEffect)(()=>{E(!1)},[s]);const P=S=>{(0,O.isEqual)(S,e.query)||E(!0),a(S)},Q=S=>{y(S.currentTarget.checked)};return t.createElement(t.Fragment,null,t.createElement(ht.u,{isOpen:c,title:"Parsing error: Switch to the builder mode?",body:"There is a syntax error, or the query structure cannot be visualized when switching to the builder mode. Parts of the query may be lost. ",confirmText:"Continue",onConfirm:()=>{ze(d,B.f.Builder,a),f(!1)},onDismiss:()=>f(!1)}),t.createElement(Ct,{isOpen:h,onClose:()=>p(!1),query:d,queries:l,app:r,onChange:a,onAddQuery:m}),t.createElement(ft.X,null,t.createElement(C.$n,{"data-testid":A.Tp.components.QueryBuilder.queryPatterns,variant:"secondary",size:"sm",onClick:()=>p(S=>!S)},"Kick start your query"),t.createElement("div",{"data-testid":A.Tp.components.DataSource.Prometheus.queryEditor.explain},t.createElement(Lt,{label:"Explain",value:g,onChange:Q})),t.createElement(_.Z,{grow:1}),r!==L.Jk.Explore&&r!==L.Jk.Correlations&&t.createElement(C.$n,{variant:x?"primary":"secondary",size:"sm",onClick:n,icon:s?.state===Fe.Gu.Loading?"spinner":void 0,disabled:s?.state===Fe.Gu.Loading},"Run queries"),t.createElement("div",{"data-testid":A.Tp.components.DataSource.Prometheus.queryEditor.editorToggle},t.createElement(It,{mode:b,onChange:v}))),t.createElement(yt.$,{v:.5}),t.createElement(Be.D,null,b===B.f.Code&&t.createElement(gn.$,{...e,query:d,showExplain:g,onChange:P}),b===B.f.Builder&&t.createElement(ja,{query:d,datasource:e.datasource,onChange:P,onRunQuery:e.onRunQuery,data:s,showExplain:g}),t.createElement(ut,{query:d,app:e.app,onChange:a,onRunQuery:n})))});gt.displayName="PromQueryEditorSelector";var fn=i(60042);function hn(e){const{datasource:a,query:n,range:s,data:r,onChange:m,onRunQuery:u}=e;return t.createElement(fn.A,{datasource:a,query:n,onRunQuery:u,onChange:m,history:[],range:s,data:r,"data-testid":yn.editor})}const yn={editor:"prom-editor-cloud-alerting"};function vn(e){const{app:a}=e;switch(a){case L.Jk.CloudAlerting:return t.createElement(hn,{...e});default:return t.createElement(gt,{...e})}}const En=(0,t.memo)(vn);var bn=i(4253),xn=i(87066);const Sn=new U.tD(xn.UD).setQueryEditor(En).setConfigEditor(bn._p).setQueryEditorHelp(le)}}]);

//# sourceMappingURL=4254.c5f4a5512b252e3a5796.js.map