"use strict";(self.webpackChunkgrafana=self.webpackChunkgrafana||[]).push([[5372],{9458:(Je,re,e)=>{e.r(re),e.d(re,{default:()=>Vt});var n=e(39953),y=e(20653),t=e(41393),N=e(57721),A=e(41407),U=e(33155),v=e(82803),O=e(4919);function de({title:u,children:f}){return n.createElement(U.b,{className:(0,v.wW)(V).warning,severity:"warning",title:u},n.createElement("p",null,f),n.createElement(O.Qj,{href:"alerting/list"},"To rule list"))}const V=u=>({warning:(0,A.css)`
    margin: ${u.spacing(4)};
  `});var J=e(86832),me=e(13601),q=e(84766),B=e(14058),Ne=e(53721),be=e(17716),ze=e(27366),Fe=e(32688),Se=e(54538),_=e(12223),fe=e(28409),le=e(64447),$e=e(32840),oe=e(16924),ge=e(90634),se=e(21308),K=e(9661),E=e(67650),ee=e(79517),pe=e(26544),b=e(79493),j=e(10235),ie=e(57675),z=e(90839),Re=e(30391),Le=e(26516),Ae=e(91753),Oe=e(42527),D=e(15898);const w=({alertUid:u,exportFormat:f,onClose:G})=>{const{currentData:$="",isFetching:Y}=Le.alertRuleApi.endpoints.exportRules.useQuery({ruleUid:u,format:f}),Q=`${u}-${new Date().getTime()}`;return Y?n.createElement(q.u,{text:"Loading...."}):n.createElement(Ae.u,{format:f,textDefinition:$,downloadFileName:Q,onClose:G})},T=({onClose:u,alertUid:f})=>{const[G,$]=(0,n.useState)("yaml");return n.createElement(Oe.i,{activeTab:G,onTabChange:$,onClose:u,formatProviders:Object.values(D.uN)},n.createElement(w,{alertUid:f,exportFormat:G,onClose:u}))};var M=e(33484),m=e(28894),P=e(96227),R=e(38637),p=e(9006),W=e(9558),ce=e(66793),te=e(4835);const ne=({rulesSourceName:u})=>{const{control:f,watch:G,formState:{errors:$},setValue:Y}=(0,B.Gc)(),Q=(0,v.wW)(Ve),ve=(0,pe._)(ae=>ae.rulerRules),k=(0,N.useDispatch)();(0,n.useEffect)(()=>{k((0,b.UR)({rulesSourceName:u}))},[u,k]);const X=ve[u]?.result,Ee=G("namespace"),ye=(0,n.useMemo)(()=>X?Object.keys(X).map(ae=>({label:ae,value:ae})):[],[X]),Ue=(0,n.useMemo)(()=>Ee&&X?.[Ee]?.map(ae=>({label:ae.name,value:ae.name}))||[],[Ee,X]);return n.createElement("div",{className:Q.flexRow},n.createElement(P.g,{"data-testid":"namespace-picker",label:"Namespace",error:$.namespace?.message,invalid:!!$.namespace?.message},n.createElement(p.g,{render:({field:{onChange:ae,ref:H,...ke}})=>n.createElement(W.LT,{...ke,allowCustomValue:!0,className:Q.input,onChange:tt=>{Y("group",""),ae(tt.value)},options:ye,width:42}),name:"namespace",control:f,rules:{required:{value:!0,message:"Required."},validate:{pathSeparator:te.p0}}})),n.createElement(P.g,{"data-testid":"group-picker",label:"Group",error:$.group?.message,invalid:!!$.group?.message},n.createElement(p.g,{render:({field:{ref:ae,...H}})=>n.createElement(W.LT,{...H,allowCustomValue:!0,options:Ue,width:42,onChange:ke=>{Y("group",ke.value??"")},className:Q.input}),name:"group",control:f,rules:{required:{value:!0,message:"Required."},validate:{pathSeparator:te.p0}}})))},Ve=u=>({flexRow:(0,A.css)`
    display: flex;
    flex-direction: row;
    justify-content: flex-start;

    & > * + * {
      margin-left: ${u.spacing(3)};
    }
  `,input:(0,A.css)`
    width: 330px !important;
  `});var We=e(23905),Ye=e(95941);const at=()=>{const u=(0,v.wW)(Xe),{register:f,control:G,watch:$,formState:{errors:Y}}=(0,B.Gc)(),Q=$("type"),ve=$("dataSourceName");return n.createElement(Ye.z,{stepNo:3,title:"Set evaluation behavior"},n.createElement(P.g,{label:"Pending period",description:"Period in which an alert rule can be in breach of the condition until the alert rule fires."},n.createElement("div",{className:u.flexRow},n.createElement(P.g,{invalid:!!Y.forTime?.message,error:Y.forTime?.message,className:u.inlineField},n.createElement(R.I,{...f("forTime",{pattern:{value:/^\d+$/,message:"Must be a positive integer."}}),width:8})),n.createElement(p.g,{name:"forTimeUnit",render:({field:{onChange:k,ref:X,...Ee}})=>n.createElement(W.Ph,{...Ee,options:ce.qr,onChange:ye=>k(ye?.value),width:15,className:u.timeUnit}),control:G}))),Q===j.$.cloudAlerting&&ve&&n.createElement(ne,{rulesSourceName:ve}),n.createElement(We.Y,null))},Xe=u=>({inlineField:(0,A.css)`
    margin-bottom: 0;
  `,flexRow:(0,A.css)`
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    align-items: flex-start;
  `,timeUnit:(0,A.css)`
    margin-left: ${u.spacing(.5)};
  `});var Te=e(98710),Dt=e(21341);function Pt(){const{watch:u}=(0,B.Gc)(),f=u("dataSourceName");return f?n.createElement(Ye.z,{stepNo:3,title:"Add namespace and group",description:"Select the Namespace and Group for your recording rule."},n.createElement(ne,{rulesSourceName:f})):null}var At=e(89525),Tt=e(4416);const rt=({existing:u,prefill:f})=>{const G=(0,v.wW)(ft),$=(0,N.useDispatch)(),Y=(0,ge.iG)(),[Q]=(0,E.K)(),[ve,k]=(0,n.useState)(!1),[X,Ee]=(0,n.useState)(u?.group.interval??z.EB),ye=(0,Ne.UO)(),Ue=(0,te.KP)(ye.type),ae=ye.id,H=Q.returnTo?String(Q.returnTo):"/alerting/list",[ke,tt]=(0,n.useState)(!1),nt=(0,n.useMemo)(()=>u?(0,z.eZ)(u):f?Qt(f):typeof Q.defaults=="string"?$t(Q.defaults,Ue):{...(0,z.uZ)(),condition:"C",queries:(0,z.s0)(),type:Ue||j.$.grafana,evaluateEvery:X},[u,f,Q,X,Ue]),st=(0,B.cI)({mode:"onSubmit",defaultValues:nt,shouldFocusError:!0}),{handleSubmit:lt,watch:qe}=st,Ke=qe("type"),gt=qe("dataSourceName"),pt=!!(Ke&&(Ke===j.$.grafana||gt)),Qe=(0,pe._)(Z=>Z.ruleForm.saveRule)||ie.oq;(0,K.x)(Z=>Z.unifiedAlerting.ruleForm.saveRule=ie.oq);const[it,vt]=(0,n.useState)(""),Et=(Z="")=>{vt(Z)},ct=(Z,Kt)=>{if(it!==""){Y.error(it);return}$((0,b.wy)({values:{...nt,...Z,annotations:Z.annotations?.map(({key:Me,value:_e})=>({key:Me.trim(),value:_e.trim()})).filter(({key:Me,value:_e})=>!!Me&&!!_e)??[],labels:Z.labels?.map(({key:Me,value:_e})=>({key:Me.trim(),value:_e.trim()})).filter(({key:Me})=>!!Me)??[]},existing:u,redirectOnSave:Kt?H:void 0,initialAlertRuleName:nt.name,evaluateEvery:X}))},yt=()=>{if(u){const Z=Re.Zk(u.ruleSourceName,u.namespace,u.group.name,u.rule);$((0,b.hS)(Z,{navigateTo:"/alerting/list"}))}},ut=Z=>{u||(0,ee.Z0)({grafana_version:Fe.config.buildInfo.version,org_id:se.Vt.user.orgId,user_id:se.Vt.user.id,error:Object.keys(Z).toString()}),Y.error("There are errors in the form. Please correct them and try again!")},ht=()=>{(0,Se.PN)(ee.z7.cancelSavingAlertRule)},dt=qe("evaluateEvery");(0,n.useEffect)(()=>Ee(dt),[dt]);const xt=n.createElement(_.Lh,{height:"auto",justify:"flex-end"},u&&n.createElement(O.zx,{variant:"primary",type:"button",size:"sm",onClick:lt(Z=>ct(Z,!1),ut),disabled:Qe.loading},Qe.loading&&n.createElement(fe.$,{className:G.buttonSpinner,inline:!0}),"Save rule"),n.createElement(O.zx,{variant:"primary",type:"button",size:"sm",onClick:lt(Z=>ct(Z,!0),ut),disabled:Qe.loading},Qe.loading&&n.createElement(fe.$,{className:G.buttonSpinner,inline:!0}),"Save rule and exit"),n.createElement(be.Link,{to:H},n.createElement(O.zx,{variant:"secondary",disabled:Qe.loading,type:"button",onClick:ht,size:"sm"},"Cancel")),u?n.createElement(O.zx,{fill:"outline",variant:"destructive",type:"button",onClick:()=>tt(!0),size:"sm"},"Delete"):null,u&&Nt(qe)&&n.createElement(O.zx,{variant:"secondary",type:"button",onClick:()=>k(!0),disabled:Qe.loading,size:"sm"},"Edit YAML"));return n.createElement(B.RV,{...st},n.createElement(oe.A,{actions:xt}),n.createElement("form",{onSubmit:Z=>Z.preventDefault(),className:G.form},n.createElement("div",{className:G.contentOuter},n.createElement(le.$,{autoHeightMin:"100%",hideHorizontalTrack:!0},n.createElement(ze.K,{direction:"column",gap:3},n.createElement(M.n,null),n.createElement(Tt.V,{editingExistingRule:!!u,onDataChange:Et}),pt&&n.createElement(n.Fragment,null,Ke===j.$.grafana&&n.createElement(Te.w,{evaluateEvery:X,setEvaluateEvery:Ee,existing:!!u,enableProvisionedGroups:!1}),Ke===j.$.cloudAlerting&&n.createElement(at,null),Ke===j.$.cloudRecording&&n.createElement(Pt,null),Ke!==j.$.cloudRecording&&n.createElement(m.Z,null),n.createElement(Dt.v,{alertUid:ae})))))),ke?n.createElement($e.s,{isOpen:!0,title:"Delete rule",body:"Deleting this rule will permanently remove it. Are you sure you want to delete this rule?",confirmText:"Yes, delete",icon:"exclamation-triangle",onConfirm:yt,onDismiss:()=>tt(!1)}):null,ve?Ke===j.$.grafana?n.createElement(T,{alertUid:ae,onClose:()=>k(!1)}):n.createElement(At.CU,{onClose:()=>k(!1)}):null)},Nt=u=>{const[f,G]=u(["type","dataSourceName"]);return(f===j.$.cloudAlerting||f===j.$.cloudRecording)&&G!==""};function $t(u,f){let G;try{G=JSON.parse(u)}catch{return{...(0,z.uZ)(),queries:(0,z.s0)()}}return(0,z.QN)({...(0,z.uZ)(),...G,annotations:(0,z.TN)(G.annotations??[]),queries:G.queries??(0,z.s0)(),type:f||j.$.grafana,evaluateEvery:z.EB})}function Qt(u){return(0,z.QN)({...(0,z.uZ)(),...u})}const ft=u=>({buttonSpinner:(0,A.css)({marginRight:u.spacing(1)}),form:(0,A.css)({width:"100%",height:"100%",display:"flex",flexDirection:"column"}),contentOuter:(0,A.css)({background:u.colors.background.primary,overflow:"hidden",flex:1}),flexRow:(0,A.css)({display:"flex",flexDirection:"row",justifyContent:"flex-start"})});var Mt=e(31559),He=e(15032),wt=e(24597);function Gt({sourceRuleId:u}){const f=(0,N.useDispatch)(),{loading:G,value:$,error:Y}=(0,y.Z)(()=>f((0,b.on)(u)).unwrap(),[u]);if(G)return n.createElement(q.u,{text:"Loading the rule"});if($){const Q=Lt($),ve=(0,z.DQ)(Q);return n.createElement(rt,{prefill:ve})}return Y?n.createElement(U.b,{title:"Error",severity:"error"},Y.message):n.createElement(U.b,{title:"Cannot copy the rule. The rule does not exist",buttonContent:"Go back to alert list",onRemove:()=>me.E1.replace((0,wt.u)("/alerting/list"))})}function Ft(u,f){(0,He.Pc)(u)&&(u.grafana_alert.title=f),(0,He.cG)(u)&&(u.alert=f),(0,He.yF)(u)&&(u.record=f)}function Lt(u){const f=(0,J.cloneDeep)(u);return Ft(f.rule,(0,Mt.G)((0,He.PW)(f.rule),f.group.rules.map(He.PW))),(0,He.Pc)(f.rule)&&(f.rule.grafana_alert.uid="",f.rule.grafana_alert.provenance&&(f.group={name:"",rules:f.group.rules})),f}var ot=e(41222);function Ot({identifier:u,id:f}){(0,K.x)(ye=>ye.unifiedAlerting.ruleForm.existingRule=ie.oq);const{loading:G,result:$,error:Y,dispatched:Q}=(0,pe._)(ye=>ye.ruleForm.existingRule),ve=(0,N.useDispatch)(),{isEditable:k,loading:X}=(0,ot.M)(Re.s0(u),$?.rule),Ee=G||X;return(0,n.useEffect)(()=>{Q||ve((0,b.on)(u))},[Q,ve,u]),Ee||k===void 0?n.createElement(q.u,{text:"Loading rule..."}):Y?n.createElement(U.b,{severity:"error",title:"Failed to load rule"},Y.message):$?k===!1?n.createElement(de,{title:"Cannot edit rule"},"Sorry! You do not have permission to edit this rule."):n.createElement(rt,{existing:$}):n.createElement(de,{title:"Rule not found"},"Sorry! This rule does not exist.")}var Wt=e(762),Ut=e(88617),Bt=e(84367);const et={icon:"bell",id:"alert-rule-view"},bt=(u,f)=>f==="recording"?u?{...et,id:"alert-rule-edit",text:"Edit recording rule"}:{...et,id:"alert-rule-add",text:"New recording rule"}:u?{...et,id:"alert-rule-edit",text:"Edit rule"}:{...et,id:"alert-rule-add",text:"New alert rule"},zt=({match:u})=>{const f=(0,N.useDispatch)(),[G]=(0,Ut.j)(),{id:$,type:Y}=u.params,Q=Re.OA($,!0),ve=G.get("copyFrom")??void 0,k=Re.OA(ve),{loading:X=!0}=(0,y.Z)(async()=>{Q&&await f((0,b.nw)({rulesSourceName:Q.ruleSourceName})),k&&await f((0,b.nw)({rulesSourceName:k.ruleSourceName}))},[f]),{canCreateGrafanaRules:Ee,canCreateCloudRules:ye,canEditRules:Ue}=(0,Bt.B)(),ae=(0,n.useCallback)(()=>{if(!X)return!Q&&!Ee&&!ye?n.createElement(de,{title:"Cannot create rules"},"Sorry! You are not allowed to create rules."):Q&&!Ue(Q.ruleSourceName)?n.createElement(de,{title:"Cannot edit rules"},"Sorry! You are not allowed to edit rules."):Q?n.createElement(Ot,{key:$,identifier:Q,id:$}):k?n.createElement(Gt,{sourceRuleId:k}):n.createElement(rt,null)},[ye,Ee,Ue,k,$,Q,X]);return n.createElement(Wt.J,{isLoading:X,pageId:"alert-list",pageNav:bt(Q,Y)},ae())},Vt=(0,t.Pf)(zt,{style:"page"})},34733:(Je,re,e)=>{e.r(re),e.d(re,{default:()=>Oe});var n=e(39953),y=e(20653),t=e(13601),N=e(84766),A=e(33155),U=e(57721),v=e(79493),O=e(90839),de=e(30391),V=e(15032),J=e(24597),me=e(762),q=e(14058),B=e(27366),Ne=e(4919),be=e(64447),ze=e(90634),Fe=e(67650),Se=e(16924),_=e(26516),fe=e(98301),le=e(75690),$e=e(95712),oe=e(91753),ge=e(42527),se=e(15898),K=e(33484),E=e(28894),ee=e(98710),pe=e(21341),b=e(4416);function j({ruleForm:D,alertUid:w}){const T=(0,q.cI)({mode:"onSubmit",defaultValues:D,shouldFocusError:!0}),[M]=(0,Fe.K)(),m=!!D,P=(0,ze.iG)(),R=M.returnTo?String(M.returnTo):"/alerting/list",[p,W]=(0,n.useState)(void 0),[ce,te]=(0,n.useState)(""),[ne,Ve]=(0,n.useState)(D?.evaluateEvery??O.EB),We=(Te="")=>{te(Te)},Ye=Te=>{if(ce!==""){P.error(ce);return}W(Te)},at=(0,n.useCallback)(()=>{W(void 0)},[W]),Xe=[n.createElement(Ne.Qj,{href:R,key:"cancel",size:"sm",variant:"secondary",onClick:()=>Ye(void 0)},"Cancel"),n.createElement(Ne.zx,{key:"export-rule",size:"sm",onClick:T.handleSubmit(Te=>Ye(Te))},"Export")];return n.createElement(n.Fragment,null,n.createElement(q.RV,{...T},n.createElement(Se.A,{actions:Xe}),n.createElement("form",{onSubmit:Te=>Te.preventDefault()},n.createElement("div",null,n.createElement(be.$,{autoHeightMin:"100%",hideHorizontalTrack:!0},n.createElement(B.K,{direction:"column",gap:3},n.createElement(K.n,null),n.createElement(b.V,{editingExistingRule:m,onDataChange:We}),n.createElement(ee.w,{evaluateEvery:ne,setEvaluateEvery:Ve,existing:!!m,enableProvisionedGroups:!0}),n.createElement(E.Z,null),n.createElement(pe.v,{alertUid:w}))))),p&&n.createElement(Ae,{exportValues:p,onClose:at,uid:w})))}const ie=(D,w)=>{const{dsFeatures:T}=(0,le.eq)($e.GC),M=T?.rulerConfig;return(0,y.Z)(async()=>M?await(0,fe.jJ)(M,D,w):void 0,[M,D,w])},z=(D,w,T)=>{const M=(0,O.mI)(w),m={...M,grafana_alert:{...M.grafana_alert,uid:D}};if(T?.rules){let P=!1;const R=T.rules.map(p=>(0,V.Pc)(p)&&p.grafana_alert.uid===D?(P=!0,m):p);return P||R.push(m),{...T,rules:R}}else return{name:T?.name??"",rules:[m]}},Re=(D,w)=>{const T=ie(D.folder?.title??"",D.group);return{payload:(0,n.useMemo)(()=>z(w,D,T?.value),[w,T,D]),loadingGroup:T.loading}},Le=({exportFormat:D,exportValues:w,onClose:T,uid:M})=>{const[m,P]=_.alertRuleApi.endpoints.exportModifiedRuleGroup.useMutation(),{loadingGroup:R,payload:p}=Re(w,M),W=w.folder?.title??"";if((0,n.useEffect)(()=>{!R&&m({payload:p,format:D,nameSpace:W})},[W,D,p,m,R]),P.isLoading)return n.createElement(N.u,{text:"Loading...."});const ce=`modify-export-${p.name}-${M}-${new Date().getTime()}`;return n.createElement(oe.u,{format:D,textDefinition:P.data??"",downloadFileName:ce,onClose:T})},Ae=n.memo(({onClose:D,exportValues:w,uid:T})=>{const[M,m]=(0,n.useState)("yaml");return n.createElement(ge.i,{title:"Export Group",activeTab:M,onTabChange:m,onClose:D,formatProviders:Object.values(se.uN)},n.createElement(Le,{exportFormat:M,onClose:D,exportValues:w,uid:T}))});Ae.displayName="GrafanaRuleDesignExporter";function Oe({match:D}){const w=(0,U.useDispatch)(),[T,M]=(0,n.useState)(void 0);(0,n.useEffect)(()=>{const W=de.OA(D.params.id,!0);M(W)},[D.params.id]);const{loading:m=!0}=(0,y.Z)(async()=>{T&&await w((0,v.nw)({rulesSourceName:T.ruleSourceName}))},[w,T]),{loading:P,value:R,error:p}=(0,y.Z)(async()=>{if(T)return await w((0,v.on)(T)).unwrap()},[T,m]);return T?P?n.createElement(N.u,{text:"Loading the rule"}):p?n.createElement(A.b,{title:"Cannot load modify export",severity:"error"},p.message):!R&&!P&&!m?n.createElement(me.J,{isLoading:P,pageId:"alert-list",pageNav:{text:"Modify export"}},n.createElement(A.b,{title:"Cannot load the rule. The rule does not exist",buttonContent:"Go back to alert list",onRemove:()=>t.E1.replace((0,J.u)("/alerting/list"))})):R&&!(0,V.Pc)(R.rule)?n.createElement(me.J,{isLoading:P,pageId:"alert-list",pageNav:{text:"Modify export"}},n.createElement(A.b,{title:"This rule is not a Grafana-managed alert rule",buttonContent:"Go back to alert list",onRemove:()=>t.E1.replace((0,J.u)("/alerting/list"))})):n.createElement(me.J,{isLoading:P,pageId:"alert-list",pageNav:{text:"Modify export",subTitle:"Modify the current alert rule and export the rule definition in the format of your choice. Any changes you make will not be saved."}},R&&n.createElement(j,{ruleForm:(0,O.eZ)(R),alertUid:D.params.id??""})):n.createElement("div",null,"Rule not found")}},33484:(Je,re,e)=>{e.d(re,{n:()=>de});var n=e(39953),y=e(14058),t=e(98632),N=e(96227),A=e(38637),U=e(10235),v=e(95941);const O={message:"Recording rule name must be valid metric name. It may only contain letters, numbers, and colons. It may not contain whitespace.",value:/^[a-zA-Z_:][a-zA-Z0-9_:]*$/},de=()=>{const{register:V,watch:J,formState:{errors:me}}=(0,y.Gc)(),q=J("type"),B=q===U.$.cloudRecording?"recording rule":"alert rule";return n.createElement(v.z,{stepNo:1,title:`Enter ${B} name`,description:n.createElement(t.x,{variant:"bodySmall",color:"secondary"},"Enter a name to identify your ",B,".")},n.createElement(N.g,{label:"Name",error:me?.name?.message,invalid:!!me.name?.message},n.createElement(A.I,{id:"name",width:35,...V("name",{required:{value:!0,message:"Must enter a name"},pattern:q===U.$.cloudRecording?O:void 0}),"aria-label":"name",placeholder:`Give your ${B} a name`})))}},21341:(Je,re,e)=>{e.d(re,{v:()=>oe});var n=e(39953),y=e(14058),t=e(27366),N=e(98632),A=e(12190),U=e(10235),v=e(95712),O=e(34685),de=e(86992),V=e(95941),J=e(41407),me=e(86832),q=e(82803),B=e(4919),Ne=e(84766),be=e(26516),ze=e(65577),Fe=e(47858),Se=e(37546);const _=()=>{const{currentData:ge}=Se.alertmanagerApi.useGetAlertmanagerChoiceStatusQuery(void 0),se=(0,v.Rz)().map(ee=>({name:ee.name,img:ee.meta.info.logos.small})),K=ge?.alertmanagersChoice;return K===Fe.TE.Internal?[{name:v.GC,img:"public/img/grafana_icon.svg"}]:K===Fe.TE.External?se:[{name:v.GC,img:"public/img/grafana_icon.svg"},...se]},fe=(0,n.lazy)(()=>e.e(6035).then(e.bind(e,46035))),le=({alertQueries:ge,customLabels:se,condition:K,folder:E,alertName:ee,alertUid:pe})=>{const b=(0,q.wW)($e),j=!K||!E,ie=be.alertRuleApi.endpoints.preview,[z,{data:Re=[],isLoading:Le,isUninitialized:Ae}]=ie.useMutation(),Oe=(0,me.compact)(Re.flatMap(M=>M?.labels)),D=()=>{!E||!K||z({alertQueries:ge,condition:K,customLabels:se,folder:E,alertName:ee,alertUid:pe})},w=_(),T=w.length===1;return n.createElement(ze.K,{direction:"column"},n.createElement("div",{className:b.routePreviewHeaderRow},n.createElement("div",{className:b.previewHeader},n.createElement(N.x,{element:"h4"},"Alert instance routing preview"),Le&&Ae&&n.createElement(N.x,{color:"secondary",variant:"bodySmall"},"Loading..."),Ae?n.createElement(N.x,{color:"secondary",variant:"bodySmall"},'When you have your folder selected and your query and labels are configured, click "Preview routing" to see the results here.'):n.createElement(N.x,{color:"secondary",variant:"bodySmall"},"Based on the labels added, alert instances are routed to the following notification policies. Expand each notification policy below to view more details.")),n.createElement("div",{className:b.button},n.createElement(B.zx,{icon:"sync",variant:"secondary",type:"button",onClick:D,disabled:j},"Preview routing"))),!Le&&!Ae&&Oe.length>0&&n.createElement(n.Suspense,{fallback:n.createElement(Ne.u,{text:"Loading preview..."})},w.map(M=>n.createElement(fe,{alertManagerSource:M,potentialInstances:Oe,onlyOneAM:T,key:M.name}))))},$e=ge=>({collapsableSection:(0,J.css)`
    width: auto;
    border: 0;
  `,previewHeader:(0,J.css)`
    margin: 0;
  `,routePreviewHeaderRow:(0,J.css)`
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: flex-start;
  `,collapseLabel:(0,J.css)`
    flex: 1;
  `,button:(0,J.css)`
    justify-content: flex-end;
  `,tagsInDetails:(0,J.css)`
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
  `,policyPathItemMatchers:(0,J.css)`
    display: flex;
    flex-direction: row;
    gap: ${ge.spacing(1)};
  `}),oe=({alertUid:ge})=>{const{watch:se}=(0,y.Gc)(),[K,E,ee,pe,b,j]=se(["type","labels","queries","condition","folder","name"]),ie=se("dataSourceName")??v.GC,z=K===U.$.grafana,Re=()=>n.createElement(t.K,{direction:"row",gap:.5,alignItems:"baseline"},n.createElement(N.x,{variant:"bodySmall",color:"secondary"},"Add custom labels to change the way your notifications are routed."),n.createElement(de.h,{contentText:n.createElement(t.K,{gap:1},n.createElement(t.K,{direction:"row",gap:0},n.createElement(n.Fragment,null,"Firing alert rule instances are routed to notification policies based on matching labels. All alert rules and instances, irrespective of their labels, match the default notification policy. If there are no nested policies, or no nested policies match the labels in the alert rule or alert instance, then the default notification policy is the matching policy."),n.createElement("a",{href:"https://grafana.com/docs/grafana/latest/alerting/fundamentals/notification-policies/notifications/",target:"_blank",rel:"noreferrer"},n.createElement(N.x,{color:"link"},"Read about notification routing. ",n.createElement(A.J,{name:"external-link-alt"})))),n.createElement(t.K,{direction:"row",gap:0},n.createElement(n.Fragment,null,"Custom labels change the way your notifications are routed. First, add labels to your alert rule and then connect them to your notification policy by adding label matchers."),n.createElement("a",{href:"https://grafana.com/docs/grafana/latest/alerting/fundamentals/annotation-label/",target:"_blank",rel:"noreferrer"},n.createElement(N.x,{color:"link"},"Read about Labels and annotations. ",n.createElement(A.J,{name:"external-link-alt"}))))),title:"Notification routing"}));return n.createElement(V.z,{stepNo:K===U.$.cloudRecording?4:5,title:K===U.$.cloudRecording?"Add labels":"Configure notifications",description:n.createElement(t.K,{direction:"row",gap:.5,alignItems:"baseline"},K===U.$.cloudRecording?n.createElement(N.x,{variant:"bodySmall",color:"secondary"},"Add labels to help you better manage your recording rules"):n.createElement(Re,null)),fullWidth:!0},n.createElement(O.Z,{dataSourceName:ie}),z&&n.createElement(le,{alertQueries:ee,customLabels:E,condition:pe,folder:b,alertName:j,alertUid:ge}))}},23905:(Je,re,e)=>{e.d(re,{Y:()=>Oe,u:()=>D});var n=e(41407),y=e(39953),t=e(14058),N=e(87786),A=e(84698),U=e(48069),v=e(10694),O=e(26205),de=e(82803),V=e(12223),J=e(4919),me=e(33155),q=e(63302),B=e(71476),Ne=e(10752),be=e(52325),ze=e(89079),Fe=e(93313),Se=e(54554),_=e(4148),fe=e(43882);function le(m){return"expr"in m}function $e(m){return"grafana_condition"in m}var oe=e(10235),ge=e(95712);function se(m){if(le(m))return K(m,m.dataSourceUid,oe.$.cloudAlerting);if($e(m))return K(m,ge.GC,oe.$.grafana);throw new Error("unsupported preview rule request")}function K(m,P,R){return(0,ze.x)({whileLoading:E(R),source:(0,_.i)().fetch({method:"POST",url:`/api/v1/rule/test/${P}`,data:m}).pipe((0,B.U)(({data:p})=>E(R,{state:v.Gu.Done,series:p.instances.map(Fe.vP)})),(0,Ne.K)(p=>(0,q.of)(E(R,{state:v.Gu.Error,error:(0,fe.P)(p)}))),(0,be.B)())})}function E(m,P={}){return{ruleType:m,data:{state:v.Gu.Loading,series:[],timeRange:(0,Se.JK)(),...P}}}var ee=e(87523),pe=e(19977),b=e(86981),j=e(51103),ie=e(34547),z=e(57675);function Re(m){const{preview:P}=m,R=(0,de.wW)(Le),p={defaults:{},overrides:[{matcher:{id:b.mi.byName,options:"Info"},properties:[{id:"custom.displayMode",value:ie.h2.JSONView}]}]};if(!P)return null;const{data:W,ruleType:ce}=P;return W.state===v.Gu.Loading?y.createElement("div",{className:R.container},y.createElement("span",null,"Loading preview...")):W.state===v.Gu.Error?y.createElement("div",{className:R.container},W.error?(0,z.kk)(W.error):"Failed to preview alert rule"):y.createElement("div",{className:R.container},y.createElement("span",null,"Preview based on the result of running the query, for this moment."," ",ce===oe.$.grafana?"Configuration for `no data` and `error handling` is not applied.":null),y.createElement("div",{className:R.table},y.createElement(pe.Z,null,({width:te,height:ne})=>y.createElement("div",{style:{width:`${te}px`,height:`${ne}px`}},y.createElement(j.$,{title:"",width:te,height:ne,pluginId:"table",data:W,fieldConfig:p})))))}function Le(m){return{container:(0,n.css)`
      margin: ${m.spacing(2)} 0;
    `,table:(0,n.css)`
      flex: 1 1 auto;
      height: 135px;
      margin-top: ${m.spacing(2)};
      border: 1px solid ${m.colors.border.medium};
      border-radius: ${m.shape.radius.default};
    `}}const Ae=["type","dataSourceName","condition","queries","expression"];function Oe(){const m=(0,de.wW)(M),[P,R]=D(),{watch:p}=(0,t.Gc)(),[W,ce,te]=p(["type","condition","queries"]),{allDataSourcesAvailable:ne}=(0,ee.S)(te);if(W===oe.$.cloudRecording||W===oe.$.cloudAlerting)return null;const Ve=!!ce&&ne;return y.createElement("div",{className:m.container},y.createElement(V.Lh,null,ne&&y.createElement(J.zx,{disabled:!Ve,type:"button",variant:"primary",onClick:R},"Preview alerts"),!ne&&y.createElement(me.b,{title:"Preview is not available",severity:"warning"},"Cannot display the query preview. Some of the data sources used in the queries are not available.")),y.createElement(Re,{preview:P}))}function D(){const[m,P]=(0,y.useState)(),{getValues:R}=(0,t.Gc)(),p=(0,N.Z)(),W=(0,y.useCallback)(()=>{const ce=R(Ae),te=w(ce);se(te).pipe((0,A.o)(ne=>!T(ne),!0)).subscribe(ne=>{p()&&P(ne)})},[R,p]);return[m,W]}function w(m){const[P,R,p,W,ce]=m,te=(0,O.F)().getInstanceSettings(R);if(!te)throw new Error(`Cannot find data source settings for ${R}`);switch(P){case oe.$.cloudAlerting:return{dataSourceUid:te.uid,dataSourceName:R,expr:ce};case oe.$.grafana:return{grafana_condition:{condition:p,data:W,now:(0,U.lf)(Date.now())}};default:throw new Error(`Alert type ${P} not supported by preview.`)}}function T(m){switch(m.data.state){case v.Gu.Done:case v.Gu.Error:return!0;default:return!1}}function M(m){return{container:(0,n.css)`
      margin-top: ${m.spacing(2)};
      max-width: ${m.breakpoints.values.xxl}px;
    `}}},4416:(Je,re,e)=>{e.d(re,{V:()=>rn});var n=e(41407),y=e(86832),t=e(39953),N=e(14058),A=e(54554),U=e(28888),v=e(27366),O=e(26205),de=e(32688),V=e(82803),J=e(96227),me=e(9006),q=e(69865),B=e(4919),Ne=e(33155),be=e(13767),ze=e(85001),Fe=e(58047),Se=e(12190),_=e(98632),fe=e(89260),le=e(29409),$e=e(57721),oe=e(95712),ge=e(26544);function se(){const r=(0,ge._)(a=>a.dataSources);return Object.values(r).map(a=>a.result).filter(a=>!!a?.rulerConfig).map(a=>(0,oe.c$)(a.name)).filter(a=>!!a)}var K=e(79493),E=e(10235),ee=e(90839),pe=e(20653),b=e(10694),j=e(34265),ie=e(96083),z=e(3532),Re=e(68694),Le=e(10162),Ae=e(17330);function Oe({fields:r}){const o=r.filter(c=>!["State","Info"].includes(c.name)),a=r.findIndex(c=>c.name==="State"),s=r.findIndex(c=>c.name==="Info"),l=o.map(c=>r.indexOf(c)),i=r[a]?.values.length??0,d=[];for(let c=0;c<i;c++){const h=l.map(L=>[r[L].name,r[L].values[c]]),F=r[a]?.values?.[c],S=r[s]?.values?.[c];(0,Ae.Yb)(F)&&d.push({state:F,info:S,labels:Object.fromEntries(h)})}return{instances:d}}function D({preview:r}){const o=(0,V.wW)(w),a=Oe(r);return t.createElement("table",{className:o.table},t.createElement("caption",null,t.createElement("div",null,"Alerts preview"),t.createElement("span",null,"Preview based on the result of running the query for this moment.")),t.createElement("thead",null,t.createElement("tr",null,t.createElement("th",null,"State"),t.createElement("th",null,"Labels"),t.createElement("th",null,"Info"))),t.createElement("tbody",null,a.instances.map(({state:s,info:l,labels:i},d)=>{const c=(0,Re.P3)(i);return t.createElement("tr",{key:d},t.createElement("td",null,t.createElement(Le.l,{state:s})),t.createElement("td",null,t.createElement(z.P,{tags:c,className:o.tagList})),t.createElement("td",null,l&&t.createElement(q.u,{content:l},t.createElement(Se.J,{name:"info-circle"}))))})))}const w=r=>({table:(0,n.css)`
    width: 100%;
    margin: ${r.spacing(2,0)};

    caption {
      caption-side: top;
      color: ${r.colors.text.primary};

      & > span {
        font-size: ${r.typography.bodySmall.fontSize};
        color: ${r.colors.text.secondary};
      }
    }

    td,
    th {
      padding: ${r.spacing(1,1)};
    }

    td + td,
    th + th {
      padding-left: ${r.spacing(3)};
    }

    thead th {
      &:nth-child(1) {
        width: 80px;
      }

      &:nth-child(2) {
        width: auto;
      }

      &:nth-child(3) {
        width: 40px;
      }
    }

    td:nth-child(3) {
      text-align: center;
    }

    tbody tr:nth-child(2n + 1) {
      background-color: ${r.colors.background.secondary};
    }
  `,tagList:(0,n.css)`
    justify-content: flex-start;
  `});var T=e(23905);const M=({value:r,onChange:o,dataSourceName:a,showPreviewAlertsButton:s=!0})=>{const l=(0,V.wW)(m),{mapToValue:i,mapToQuery:d}=P(a),c=d({refId:"A",hide:!1},r),{error:h,loading:F,value:S}=(0,pe.Z)(()=>(0,O.F)().get(a),[a]),L=(0,t.useCallback)(De=>{o(i(De))},[o,i]),[Ce,C]=(0,T.u)(),x=async()=>{C()};if(F||S?.name!==a)return null;const he=(0,O.F)().getInstanceSettings(a);if(h||!S||!S?.components?.QueryEditor||!he){const De=h?.message||"Data source plugin does not export any Query Editor component";return t.createElement("div",null,"Could not load query editor due to: ",De)}const xe=Ce?.data.state===b.Gu.Done,Ie=S?.components?.QueryEditor,we=Ce?.data?.series?.find(De=>De.name==="evaluation results"),je=we&&we.fields.some(De=>De.values.length>0);return t.createElement(t.Fragment,null,t.createElement(j.n,{instanceSettings:he},t.createElement(Ie,{query:c,queries:[c],app:ie.zj.CloudAlerting,onChange:L,onRunQuery:y.noop,datasource:S})),s&&t.createElement("div",{className:l.preview},t.createElement(B.zx,{type:"button",onClick:x,disabled:Ce?.data.state===b.Gu.Loading},"Preview alerts"),xe&&!je&&t.createElement(Ne.b,{title:"Alerts preview",severity:"info",className:l.previewAlert},"There are no firing alerts for your query."),je&&t.createElement(D,{preview:we})))},m=r=>({preview:(0,n.css)`
    padding: ${r.spacing(2,0)};
    max-width: ${r.breakpoints.values.xl}px;
  `,previewAlert:(0,n.css)`
    margin: ${r.spacing(1,0)};
  `});function P(r){return(0,t.useMemo)(()=>{switch((0,O.F)().getInstanceSettings(r)?.type){case"loki":case"prometheus":return{mapToValue:a=>a.expr,mapToQuery:(a,s)=>({...a,expr:s})};default:throw new Error(`${r} is not supported as an expression editor`)}},[r])}var R=e(7225),p=e(4835);const W=({condition:r,onSetCondition:o,queries:a,panelData:s,onUpdateRefId:l,onRemoveExpression:i,onUpdateExpressionType:d,onUpdateQueryExpression:c})=>{const h=(0,t.useMemo)(()=>a.reduce((S,L)=>(0,fe.j)(L.model)?S.concat(L.model):S,[]),[a]),F=(0,V.wW)(ce);return t.createElement("div",{className:F.wrapper},h.map(S=>{const L=s[S.refId],Ce=r===S.refId,C=L?(0,p._m)(L):void 0,x=L?(0,p.Yq)(L.series):void 0;return t.createElement(R.A2,{key:S.refId,isAlertCondition:Ce,data:L,error:C,warning:x,queries:a,query:S,onSetCondition:o,onRemoveExpression:i,onUpdateRefId:l,onUpdateExpressionType:d,onChangeQuery:c})}))},ce=r=>({wrapper:(0,n.css)`
    display: flex;
    gap: ${r.spacing(2)};
    align-content: stretch;
    flex-wrap: wrap;
  `});var te=e(86992),ne=e(24058),Ve=e(81626),We=e(4236),Ye=e(98324),at=e(52436),Xe=e(69171),Te=e(38637),Dt=e(29581),Pt=e(66793),At=e(25825),Tt=e(92403),rt=e(36884),Nt=e(47158);const $t=({query:r,queryOptions:o,onChangeTimeRange:a,onChangeQueryOptions:s,index:l})=>{const i=(0,V.wW)(Qt),[d,c]=(0,t.useState)(!1),h=r.relativeTimeRange?(0,Ve.relativeToTimeRange)(r.relativeTimeRange):void 0;return t.createElement(t.Fragment,null,t.createElement(rt.P,{content:t.createElement("div",{className:i.queryOptions},a&&t.createElement(Xe._,{label:"Time Range"},t.createElement(Nt.x,{timeRange:r.relativeTimeRange??(0,A.Rr)(),onChange:F=>a(F,l)})),t.createElement(Ft,{options:o,onChange:F=>s(F,l)}),t.createElement(Lt,{options:o,onChange:F=>s(F,l)})),closeButton:!0,placement:"bottom-start"},t.createElement("button",{type:"button",className:i.actionLink,onClick:()=>c(!d)},"Options ",d?t.createElement(Se.J,{name:"angle-right"}):t.createElement(Se.J,{name:"angle-down"}))),t.createElement("div",{className:i.staticValues},t.createElement("span",null,(0,Tt.CQ)(h?.from).locale("en").fromNow(!0)),o.maxDataPoints&&t.createElement("span",null,", MD = ",o.maxDataPoints),o.minInterval&&t.createElement("span",null,", Min. Interval = ",o.minInterval)))},Qt=r=>{const o=(0,B.gN)(r);return{queryOptions:(0,n.css)`
      > div {
        justify-content: space-between;
      }
    `,staticValues:(0,n.css)`
      color: ${r.colors.text.secondary};
      margin-right: ${r.spacing(1)};
    `,actionLink:(0,n.css)`
      ${o};
      color: ${r.colors.text.link};
      cursor: pointer;

      &:hover {
        text-decoration: underline;
      }
    `}};var ft=e(65478);const Mt=43200,He="1s",wt=({data:r,error:o,dsSettings:a,index:s,onChangeDataSource:l,onChangeQuery:i,onChangeTimeRange:d,onRunQueries:c,onRemoveQuery:h,onDuplicateQuery:F,query:S,queries:L,thresholds:Ce,thresholdsType:C,onChangeThreshold:x,condition:he,onSetCondition:xe,onChangeQueryOptions:Ie})=>{const we=(0,V.wW)(ot),[je,De]=(0,t.useState)(),mt={...je?.getDefaultQuery?je.getDefaultQuery(ie.zj.UnifiedAlerting):{},...(0,y.cloneDeep)(S.model)};function Be(){const ue=(0,V.wW)(ot);return t.createElement("div",{className:ue.dsTooltip},t.createElement(q.u,{content:t.createElement(t.Fragment,null,"Not finding the data source you want? Some data sources are not supported for alerting. Click on the icon for more information.")},t.createElement(Se.J,{name:"info-circle",onClick:()=>window.open(" https://grafana.com/docs/grafana/latest/alerting/fundamentals/data-source-alerting/","_blank")})))}function St({query:ue,error:Rt,index:Ze}){const Ct={maxDataPoints:ue.model.maxDataPoints,minInterval:ue.model.intervalMs?(0,Pt.gS)(ue.model.intervalMs):void 0},Ge={maxDataPoints:Ct.maxDataPoints,minInterval:Ct.minInterval},Jt=he===ue.refId;return t.createElement(v.K,{direction:"row",alignItems:"center",gap:1},t.createElement(Be,null),t.createElement($t,{onChangeTimeRange:d,query:ue,queryOptions:Ge,onChangeQueryOptions:Ie,index:Ze}),t.createElement(At.H,{error:Rt,onSetCondition:()=>xe(ue.refId),isCondition:Jt}))}const Zt=r.state!==b.Gu.NotStarted;return t.createElement(v.K,{direction:"column",gap:.5},t.createElement("div",{className:we.wrapper},t.createElement(Dt.x,{alerting:!0,collapsable:!1,dataSource:a,onDataSourceLoaded:De,onChangeDataSource:ue=>l(ue,s),id:S.refId,index:s,key:S.refId,data:r,query:mt,onChange:ue=>i(ue,s),onRemoveQuery:h,onAddQuery:()=>F((0,y.cloneDeep)(S)),onRunQuery:c,queries:L,renderHeaderExtras:()=>t.createElement(St,{query:S,index:s,error:o}),app:ie.zj.UnifiedAlerting,hideDisableQuery:!0})),Zt&&t.createElement(ft.l,{data:r,thresholds:Ce,thresholdsType:C,onThresholdsChange:x?ue=>x(ue,s):void 0}))},Gt=({children:r})=>{const o=(0,V.wW)(ot);return t.createElement("div",{className:o.wrapper},r)};function Ft({options:r,onChange:o}){const a=r.maxDataPoints??"",s=l=>{const i=parseInt(l.target.value,10),d=isNaN(i)||i===0?void 0:i;d!==r.maxDataPoints&&o({...r,maxDataPoints:d})};return t.createElement(Xe._,{labelWidth:24,label:"Max data points",tooltip:"The maximum data points per series. Used directly by some data sources and used in calculation of auto interval. With streaming data this value is used for the rolling buffer."},t.createElement(Te.I,{type:"number",width:10,placeholder:Mt.toLocaleString(),spellCheck:!1,onBlur:s,defaultValue:a}))}function Lt({options:r,onChange:o}){const a=r.minInterval??"",s=l=>{const i=l.target.value;i!==a&&o({...r,minInterval:i})};return t.createElement(Xe._,{label:"Min interval",labelWidth:24,tooltip:t.createElement(t.Fragment,null,"A lower limit for the interval. Recommended to be set to write frequency, for example ",t.createElement("code",null,"1m")," if your data is written every minute.")},t.createElement(Te.I,{type:"text",width:10,placeholder:He,spellCheck:!1,onBlur:s,defaultValue:a}))}const ot=r=>({wrapper:(0,n.css)`
    label: AlertingQueryWrapper;
    margin-bottom: ${r.spacing(1)};
    border: 1px solid ${r.colors.border.weak};
    border-radius: ${r.shape.radius.default};

    button {
      overflow: visible;
    }
  `,dsTooltip:(0,n.css)`
    display: flex;
    align-items: center;
    &:hover {
      opacity: 0.85;
      cursor: pointer;
    }
  `});class Ot extends t.PureComponent{constructor(o){super(o),this.onRemoveQuery=a=>{const{queries:s,onQueriesChange:l}=this.props;l(s.filter(i=>i.refId!==a.refId))},this.onChangeTimeRange=(a,s)=>{const{queries:l,onQueriesChange:i}=this.props;i(l.map((d,c)=>c!==s?d:{...d,relativeTimeRange:a}))},this.onChangeQueryOptions=(a,s)=>{const{queries:l,onQueriesChange:i}=this.props;i(l.map((d,c)=>c!==s?d:{...d,model:{...d.model,maxDataPoints:a.maxDataPoints,intervalMs:a.minInterval?Ve.intervalToMs(a.minInterval):void 0}}))},this.onChangeDataSource=(a,s)=>{const{queries:l,onQueriesChange:i}=this.props,d=l.map((c,h)=>{if(h!==s)return c;const F=this.getDataSourceSettings(c);return a.type===F?.type?Wt(c,a):Ut(c,a)});i(d)},this.onChangeQuery=(a,s)=>{const{queries:l,onQueriesChange:i}=this.props;i(l.map((d,c)=>c!==s?d:{...d,refId:a.refId,queryType:d.model.queryType??"",model:{...d.model,...a,datasource:a.datasource}}))},this.onDragEnd=a=>{const{queries:s,onQueriesChange:l}=this.props;if(!a||!a.destination)return;const i=a.source.index,d=a.destination.index;if(i===d)return;const c=Array.from(s),[h]=c.splice(i,1);c.splice(d,0,h),l(c)},this.getDataSourceSettings=a=>(0,O.F)().getInstanceSettings(a.datasourceUid)}render(){const{queries:o,expressions:a}=this.props,s=(0,p.Fu)([...o,...a]);return t.createElement(ne.Z5,{onDragEnd:this.onDragEnd},t.createElement(ne.bK,{droppableId:"alerting-queries",direction:"vertical"},l=>t.createElement("div",{ref:l.innerRef,...l.droppableProps},t.createElement(v.K,{direction:"column"},o.map((i,d)=>{const c=this.props.condition===i.refId,h=this.props.data?.[i.refId]??{series:[],state:b.Gu.NotStarted},F=this.getDataSourceSettings(i);let S;return h&&c?S=(0,p.Ps)(h):h&&(S=(0,p._m)(h)),F?t.createElement(wt,{index:d,key:i.refId,dsSettings:F,data:h,error:S,query:i,onChangeQuery:this.onChangeQuery,onRemoveQuery:this.onRemoveQuery,queries:[...o,...a],onChangeDataSource:this.onChangeDataSource,onDuplicateQuery:this.props.onDuplicateQuery,onChangeTimeRange:this.onChangeTimeRange,onChangeQueryOptions:this.onChangeQueryOptions,thresholds:s[i.refId]?.config,thresholdsType:s[i.refId]?.mode,onRunQueries:this.props.onRunQueries,condition:this.props.condition,onSetCondition:this.props.onSetCondition}):t.createElement(Bt,{key:`${i.refId}-${d}`,index:d,model:i.model,onUpdateDatasource:()=>{const L=(0,at.ak)().getInstanceSettings(null);L&&this.onChangeDataSource(L,d)},onRemoveQuery:()=>{this.onRemoveQuery(i)}})}),l.placeholder))))}}function Wt(r,o){return{...r,model:{...(0,y.omit)(r.model,"datasource"),datasource:{type:o.type,uid:o.uid}},datasourceUid:o.uid}}function Ut(r,o){return{refId:r.refId,relativeTimeRange:r.relativeTimeRange,queryType:"",datasourceUid:o.uid,model:{refId:r.refId,hide:!1,datasource:{type:o.type,uid:o.uid}}}}const Bt=({index:r,onUpdateDatasource:o,onRemoveQuery:a,model:s})=>{const l=s.refId,[i,d]=(0,t.useState)(!1),c=()=>{d(F=>!F)},h=()=>{o()};return t.createElement(Gt,null,t.createElement(Ye.t,{title:l,draggable:!0,index:r,id:l,isOpen:!0,collapsable:!1},t.createElement(We.Z,null,t.createElement(We.Z.Heading,null,"This datasource has been removed"),t.createElement(We.Z.Description,null,"The datasource for this query was not found, it was either removed or is not installed correctly."),t.createElement(We.Z.Figure,null,t.createElement(Se.J,{name:"question-circle"})),t.createElement(We.Z.Actions,null,t.createElement(B.zx,{key:"update",variant:"secondary",onClick:h},"Update datasource"),t.createElement(B.zx,{key:"remove",variant:"destructive",onClick:a},"Remove query")),t.createElement(We.Z.SecondaryActions,null,t.createElement(B.zx,{key:"details",onClick:c,icon:i?"angle-up":"angle-down",fill:"text",size:"sm"},"Show details"))),i&&t.createElement("div",null,t.createElement("pre",null,t.createElement("code",null,JSON.stringify(s,null,2))))))},et=({queries:r,expressions:o,panelData:a,onRunQueries:s,onChangeQueries:l,onDuplicateQuery:i,condition:d,onSetCondition:c})=>{const h=(0,V.wW)(bt);return t.createElement("div",{className:h.container},t.createElement(Ot,{data:a,queries:r,expressions:o,onRunQueries:s,onQueriesChange:l,onDuplicateQuery:i,condition:d,onSetCondition:c}))},bt=r=>({container:(0,n.css)`
    background-color: ${r.colors.background.primary};
    height: 100%;
  `});var zt=e(6278);const Vt=({queries:r,onChangeQuery:o,runQueries:a,panelData:s,dataSourceName:l})=>{const[i,d]=(0,t.useState)({series:[],state:b.Gu.NotStarted,timeRange:(0,zt.$t)().timeRange()}),c=(0,V.wW)(u);(0,t.useEffect)(()=>{d(s?.[r[0]?.refId])},[s,r]);const{error:h,loading:F,value:S}=(0,pe.Z)(()=>(0,O.F)().get(l),[l]),L=x=>{const he=r[0],xe=(0,O.F)().getInstanceSettings(l)?.uid;if(!(0,ee.tO)(x)||!xe)return;const Ie=x.expr,we={...he,...x,datasourceUid:xe,expr:Ie,model:{expr:Ie,datasource:x.datasource,refId:x.refId,editorMode:x.editorMode,instant:!!x.instant,range:!!x.range,legendFormat:x.legendFormat}};o([we])};if(F||S?.name!==l)return null;const Ce=(0,O.F)().getInstanceSettings(l);if(h||!S||!S?.components?.QueryEditor||!Ce){const x=h?.message||"Data source plugin does not export any Query Editor component";return t.createElement("div",null,"Could not load query editor due to: ",x)}const C=S.components.QueryEditor;return t.createElement(t.Fragment,null,r.length&&t.createElement(C,{query:r[0],queries:r,app:ie.zj.UnifiedAlerting,onChange:L,onRunQuery:a,datasource:S}),i&&t.createElement("div",{className:c.vizWrapper},t.createElement(ft.l,{data:i})))},u=r=>({vizWrapper:(0,n.css)`
    margin: ${r.spacing(1,0)};
  `});var f=e(95941),G=e(92811),$=e(74600);function Y({value:r,disabled:o,...a}){const s=se(),{loading:l=!0}=(0,pe.Z)(()=>(0,$.WI)((0,K.dV)()),[$.WI]),i=(0,t.useCallback)(d=>!!s.find(({id:c})=>c===d.id),[s]);return t.createElement(G.q,{disabled:l||o,noDefault:!0,alerting:!0,filter:i,current:r,...a})}const Q=({disabled:r,onChangeCloudDatasource:o})=>{const{control:a,formState:{errors:s},setValue:l,watch:i}=(0,N.Gc)(),d=(0,V.wW)(ve),c=i("type");return t.createElement(t.Fragment,null,t.createElement("div",{className:d.flexRow},(c===E.$.cloudAlerting||c===E.$.cloudRecording)&&t.createElement(J.g,{className:d.formInput,label:r?"Data source":"Select data source",error:s.dataSourceName?.message,invalid:!!s.dataSourceName?.message,"data-testid":"datasource-picker"},t.createElement(me.g,{render:({field:{onChange:h,ref:F,...S}})=>t.createElement(Y,{...S,disabled:r,onChange:L=>{l("location",void 0),l("expression",""),h(L?.name??null),o(L?.uid??null)}}),name:"dataSourceName",control:a,rules:{required:{value:!0,message:"Please select a data source"}}}))))},ve=r=>({formInput:(0,n.css)`
    width: 330px;
    & + & {
      margin-left: ${r.spacing(3)};
    }
  `,flexRow:(0,n.css)`
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    align-items: flex-end;
  `});var k=e(20454),X=e(21308);function Ee(){const r=X.Vt.hasPermission($e.AccessControlAction.AlertingRuleCreate),o=X.Vt.hasPermission($e.AccessControlAction.AlertingRuleExternalWrite),a=r?E.$.grafana:E.$.cloudAlerting,s=[];return r&&s.push(E.$.grafana),o&&s.push(E.$.cloudAlerting,E.$.cloudRecording),{enabledRuleTypes:s,defaultRuleType:a}}const ye=r=>r.filter(o=>o.datasourceUid!==le.Yq).length===1,Ue=({queries:r,ruleFormType:o,rulesSourcesWithRuler:a})=>{const s=Ee(),l=ye(r),i=r[0]?.datasourceUid??"",d=o===E.$.cloudRecording,c=!d&&l&&a.some(C=>C.uid===i),h=!d,F=s.enabledRuleTypes.includes(E.$.grafana),S=s.enabledRuleTypes.includes(E.$.cloudAlerting),L=o===E.$.cloudAlerting&&F&&h,Ce=o===E.$.grafana&&c&&S&&c;return L||Ce};function ae({editingExistingRule:r,rulesSourcesWithRuler:o,queries:a,onClickSwitch:s}){const{getValues:l}=(0,N.Gc)(),[i]=l(["type"]),d=Ue({queries:a,ruleFormType:i,rulesSourcesWithRuler:o}),c=[{label:"Grafana-managed",value:E.$.grafana},{label:"Data source-managed",value:E.$.cloudAlerting}],h=d?[]:[E.$.cloudAlerting];return t.createElement(v.K,{direction:"column",gap:1,alignItems:"flex-start"},t.createElement(v.K,{direction:"column",gap:0},t.createElement(_.x,{variant:"h5"},"Rule type"),t.createElement(v.K,{direction:"row",gap:.5,alignItems:"baseline"},t.createElement(_.x,{variant:"bodySmall",color:"secondary"},"Select where the alert rule will be managed."),t.createElement(te.h,{contentText:t.createElement(t.Fragment,null,t.createElement(_.x,{color:"primary",variant:"h6"},"Grafana-managed alert rules"),t.createElement("p",null,"Grafana-managed alert rules allow you to create alerts that can act on data from any of our supported data sources, including having multiple data sources in the same rule. You can also add expressions to transform your data and set alert conditions. Using images in alert notifications is also supported."),t.createElement(_.x,{color:"primary",variant:"h6"},"Data source-managed alert rules"),t.createElement("p",null,"Data source-managed alert rules can be used for Grafana Mimir or Grafana Loki data sources which have been configured to support rule creation. The use of expressions or multiple queries is not supported.")),externalLink:"https://grafana.com/docs/grafana/latest/alerting/fundamentals/alert-rules/alert-rule-types/",linkText:"Read about alert rule types",title:"Alert rule types"}))),t.createElement(k.S,{options:c,disabled:r,disabledOptions:h,value:i,onChange:s}),r&&t.createElement(_.x,{color:"secondary"},"The alert rule type cannot be changed for an existing rule."),!r&&t.createElement(t.Fragment,null,d?t.createElement(_.x,{color:"secondary"},i===E.$.grafana?"The data source selected in your query supports alert rule management. Switch to data source-managed if you want the alert rule to be managed by the data source instead of Grafana.":"Switch to Grafana-managed to use expressions, multiple queries, images in notifications and various other features."):t.createElement(_.x,{color:"secondary"},"Based on the selected data sources this alert rule will be Grafana-managed.")))}var H=e(77960),ke=e(78354);const tt=r=>{try{return JSON.stringify(r),!1}catch{return!0}},nt=(r,o)=>{if(tt(r))return null;if(o.datasourceUid!==le.Yq)return o;{const a=r.find(s=>s.refId===o.model.expression);return a?nt(r,a):null}};var st=e(1464),lt=e(96841);const qe=(r,o)=>{const a=r.find(l=>l.refId===o);return a&&nt(r,a)},Ke={queries:[]},gt=(0,H.PH)("duplicateQuery"),pt=(0,H.PH)("addNewDataQuery"),Qe=(0,H.PH)("setDataQueries"),it=(0,H.PH)("addNewExpression"),vt=(0,H.PH)("removeExpression"),Et=(0,H.PH)("removeExpressions"),ct=(0,H.PH)("addExpressions"),yt=(0,H.PH)("updateExpression"),ut=(0,H.PH)("updateExpressionRefId"),ht=(0,H.PH)("rewireExpressions"),dt=(0,H.PH)("updateExpressionType"),xt=(0,H.PH)("updateExpressionTimeRange"),Z=(0,H.PH)("updateMaxDataPoints"),Kt=(0,H.PH)("updateMinInterval"),Me=(0,H.PH)("setRecordingRulesQueries"),_e=(0,H.Lq)(Ke,r=>{r.addCase(gt,(o,{payload:a})=>{o.queries=Ht(o.queries,a)}).addCase(pt,o=>{const a=(0,oe.P)();a&&(o.queries=Ht(o.queries,{datasourceUid:a.uid,model:{refId:"",datasource:{type:a.type,uid:a.uid}}}))}).addCase(Qe,(o,{payload:a})=>{const s=o.queries.filter(l=>(0,fe.j)(l.model));o.queries=[...a,...s]}).addCase(Me,(o,{payload:a})=>{const s=a.recordingRuleQueries[0],l={...s,expr:a.expression,model:s?.model};o.queries=[l]}).addCase(Z,(o,a)=>{o.queries=o.queries.map(s=>s.refId===a.payload.refId?{...s,model:{...s.model,maxDataPoints:a.payload.maxDataPoints}}:s)}).addCase(Kt,(o,a)=>{o.queries=o.queries.map(s=>s.refId===a.payload.refId?{...s,model:{...s.model,intervalMs:a.payload.minInterval?Ve.intervalToMs(a.payload.minInterval):void 0}}:s)}),r.addCase(it,(o,{payload:a})=>{o.queries=Ht(o.queries,{datasourceUid:le.Yq,model:st.mV.newQuery({type:a,conditions:[{...lt.R,query:{params:[]}}],expression:""})})}).addCase(vt,(o,{payload:a})=>{o.queries=o.queries.filter(s=>s.refId!==a)}).addCase(Et,o=>{o.queries=o.queries.filter(a=>!(0,fe.j)(a.model))}).addCase(ct,(o,{payload:a})=>{o.queries=[...o.queries,...a]}).addCase(yt,(o,{payload:a})=>{o.queries=o.queries.map(s=>{const l=qe(o.queries,a.expression),i=l?l.relativeTimeRange:(0,A.Rr)();return s.refId===a.refId&&(s.model=a,a.type===le.Us.resample&&(s.relativeTimeRange=i)),s})}).addCase(xt,o=>{const a=o.queries.map(s=>{if(s.datasourceUid===le.Yq){const l=qe(o.queries,s.model.expression),i=l?l.relativeTimeRange:(0,A.Rr)();s.relativeTimeRange=i}return s});o.queries=a}).addCase(ut,(o,{payload:a})=>{const{newRefId:s,oldRefId:l}=a;if((0,p.Dr)(o.queries,s))return;const d=(0,p.Ry)(o.queries,l,s);o.queries=d.map(c=>c.refId===l?{...c,refId:s,model:{...c.model,refId:s}}:c)}).addCase(ht,(o,{payload:a})=>{o.queries=(0,p.Ry)(o.queries,a.oldRefId,a.newRefId)}).addCase(dt,(o,a)=>{o.queries=o.queries.map(s=>s.refId===a.payload.refId?{...s,model:{...st.mV.newQuery({type:a.payload.type,conditions:[{...lt.R,query:{params:[]}}],expression:""}),refId:a.payload.refId}}:s)})}),Ht=(r,o)=>{const a=(0,ke.Hs)(r),s={...o,refId:a,queryType:"",model:{...o.model,hide:!1,refId:a},relativeTimeRange:o.relativeTimeRange??tn(o.model)};return[...r,s]},tn=r=>{if(!(0,fe.j)(r))return(0,A.Rr)()};var nn=e(92103);function an(){const[r,o]=(0,t.useState)({}),a=(0,t.useRef)(new nn.v);(0,t.useEffect)(()=>{const c=a.current;return c.get().subscribe(h=>{o(h)}),()=>{c.destroy()}},[]);const s=(0,t.useCallback)(()=>{o({})},[]),l=(0,t.useCallback)(()=>{a.current.cancel()},[]),i=(0,t.useCallback)(c=>{a.current.run(c)},[]),d=(0,t.useMemo)(()=>Object.values(r).some(c=>c.state===b.Gu.Loading),[r]);return{queryPreviewData:r,runQueries:i,cancelQueries:l,isPreviewLoading:d,clearPreviewData:s}}const rn=({editingExistingRule:r,onDataChange:o})=>{const{setValue:a,getValues:s,watch:l,formState:{errors:i},control:d}=(0,N.Gc)(),{queryPreviewData:c,runQueries:h,cancelQueries:F,isPreviewLoading:S,clearPreviewData:L}=an(),Ce={queries:s("queries")},[{queries:C},x]=(0,t.useReducer)(_e,Ce),[he,xe,Ie]=l(["type","condition","dataSourceName"]),we=he===E.$.grafana,je=he===E.$.cloudRecording,De=he===E.$.cloudAlerting,jt=(0,$e.useDispatch)();(0,t.useEffect)(()=>{jt((0,K.dV)())},[jt]);const mt=se(),Be=(0,t.useCallback)(()=>{De||h(s("queries"))},[De,h,s]);(0,t.useEffect)(()=>{a("queries",C,{shouldValidate:!1})},[C,h,a]);const St=(0,oe.P)()===void 0,Zt=(0,t.useMemo)(()=>C.filter(g=>!(0,fe.j)(g.model)),[C]),ue=(0,t.useMemo)(()=>C.filter(g=>(0,fe.j)(g.model)),[C]),Rt=C.length===0;(0,t.useEffect)(()=>{if(!we)return;const g=s("condition");if(!g)return;const I=c[g];if(!I)return;const Pe=(0,p._m)(I)??(0,p.Ps)(I);o(Pe?.message||"")},[c,s,o,we]);const Ze=(0,t.useCallback)(g=>{g&&(Be(),a("condition",g))},[Be,a]),Ct=(0,t.useCallback)((g,I)=>{(0,p.Dr)(C,I)||(x(ut({oldRefId:g,newRefId:I})),xe===g&&Ze(I))},[xe,C,Ze]),Ge=ln(),Jt=(0,t.useCallback)(g=>{a("queries",g,{shouldValidate:!1}),Ge(g),x(Qe(g)),x(xt());const[I,Pe]=(0,p.eW)(C,g);I&&Pe&&x(ht({oldRefId:I,newRefId:Pe}))},[C,a,Ge]),cn=(0,t.useCallback)(g=>{const I=g[0];if(!(0,ee.tO)(I.model))return;const Pe=I.model.expr;a("queries",g,{shouldValidate:!1}),Ge(g),x(Me({recordingRuleQueries:g,expression:Pe})),Be()},[Be,a,Ge]),Yt=mt[0];(0,t.useEffect)(()=>{if(L(),he===E.$.cloudRecording){const g=s("expression");if(!Yt)return;const Pe={refId:"A",datasourceUid:r&&(0,O.F)().getInstanceSettings(Ie)?.uid||Yt.uid,queryType:"",relativeTimeRange:(0,A.Rr)(),expr:g,model:{refId:"A",hide:!1,expr:g}};x(Me({recordingRuleQueries:[Pe],expression:g}))}},[he,Yt,r,s,Ie,L]);const un=(0,t.useCallback)(g=>{x(gt(g))},[]);(0,t.useEffect)(()=>{if(!(0,p.Dr)(C,xe)){const g=C.at(-1)?.refId??null;Ze(g)}},[xe,C,Ze]);const dn=(0,t.useCallback)(g=>{x(it(g))},[x]),mn=(0,V.wW)(sn),fn=(0,t.useCallback)(g=>{const I=(0,y.cloneDeep)(C);I[0].datasourceUid=g,a("queries",I,{shouldValidate:!1}),Ge(I),x(Qe(I))},[C,a,Ge,x]),gn=g=>{const I=(0,y.cloneDeep)(C);if(I[0].model)if((0,ee.tO)(I[0].model))I[0].model.expr=g;else{const Pe={...(0,y.cloneDeep)(I[0].model),expr:g};I[0].model=Pe}a("queries",I,{shouldValidate:!1}),Ge(I),x(Qe(I)),Be()},kt=(0,t.useCallback)(()=>x(Et()),[x]),qt=(0,t.useCallback)(g=>x(ct(g)),[x]),[It,pn]=(0,t.useState)([]),[Xt,vn]=(0,t.useState)(null),_t=(0,t.useCallback)(()=>{qt(It)},[It,qt]),en=(0,t.useCallback)(()=>{if(s("type")===E.$.cloudAlerting)a("type",E.$.grafana),a("dataSourceName",null),It.length>0&&_t(),Xt&&a("condition",Xt);else{a("type",E.$.cloudAlerting);const I=(0,O.F)().getInstanceSettings(C[0].datasourceUid)?.name;I&&a("dataSourceName",I),Ge(C);const Pe=C.filter(En=>En.datasourceUid===le.Yq);pn(Pe),kt(),vn(xe)}},[s,a,It.length,_t,Xt,Ge,C,kt,xe]);return t.createElement(f.z,{stepNo:2,title:he!==E.$.cloudRecording?"Define query and alert condition":"Define query",description:t.createElement(v.K,{direction:"row",gap:.5,alignItems:"baseline"},t.createElement(_.x,{variant:"bodySmall",color:"secondary"},"Define queries and/or expressions and then choose one of them as the alert rule condition. This is the threshold that an alert rule must meet or exceed in order to fire."),t.createElement(te.h,{contentText:`An alert rule consists of one or more queries and expressions that select the data you want to measure.
          Define queries and/or expressions and then choose one of them as the alert rule condition. This is the threshold that an alert rule must meet or exceed in order to fire.
          For more information on queries and expressions, see Query and transform data.`,externalLink:"https://grafana.com/docs/grafana/latest/panels-visualizations/query-transform-data/",linkText:"Read about query and condition",title:"Define query and alert condition"}))},(he===E.$.cloudRecording||he===E.$.cloudAlerting)&&t.createElement(Q,{onChangeCloudDatasource:fn,disabled:r}),je&&Ie&&t.createElement(J.g,{error:i.expression?.message,invalid:!!i.expression?.message},t.createElement(Vt,{dataSourceName:Ie,queries:C,runQueries:Be,onChangeQuery:cn,panelData:c})),De&&Ie&&t.createElement(v.K,{direction:"column"},t.createElement(J.g,{error:i.expression?.message,invalid:!!i.expression?.message},t.createElement(me.g,{name:"expression",render:({field:{ref:g,...I}})=>t.createElement(M,{...I,dataSourceName:Ie,showPreviewAlertsButton:!je,onChange:gn}),control:d,rules:{required:{value:!0,message:"A valid expression is required"}}})),t.createElement(ae,{editingExistingRule:r,queries:C,rulesSourcesWithRuler:mt,onClickSwitch:en})),we&&t.createElement(v.K,{direction:"column"},t.createElement(et,{queries:Zt,expressions:ue,onRunQueries:Be,onChangeQueries:Jt,onDuplicateQuery:un,panelData:c,condition:xe,onSetCondition:Ze}),t.createElement(q.u,{content:"You appear to have no compatible data sources",show:St},t.createElement(B.zx,{type:"button",onClick:()=>{x(pt())},variant:"secondary","aria-label":U.wl.components.QueryTab.addQuery,disabled:St,className:mn.addQueryButton},"Add query")),t.createElement(ae,{editingExistingRule:r,rulesSourcesWithRuler:mt,queries:C,onClickSwitch:en}),t.createElement(v.K,{direction:"column",gap:0},t.createElement(_.x,{element:"h5"},"Expressions"),t.createElement(_.x,{variant:"bodySmall",color:"secondary"},"Manipulate data returned from queries with math and other operations.")),t.createElement(W,{queries:C,panelData:c,condition:xe,onSetCondition:Ze,onRemoveExpression:g=>{x(vt(g))},onUpdateRefId:Ct,onUpdateExpressionType:(g,I)=>{x(dt({refId:g,type:I}))},onUpdateQueryExpression:g=>{x(yt(g))}}),t.createElement(v.K,{direction:"row"},de.config.expressionsEnabled&&t.createElement(on,{onClickType:dn}),S&&t.createElement(B.zx,{icon:"fa fa-spinner",type:"button",variant:"destructive",onClick:F},"Cancel"),!S&&t.createElement(B.zx,{icon:"sync",type:"button",onClick:Be,disabled:Rt},"Preview")),Rt&&t.createElement(Ne.b,{title:"No queries or expressions have been configured",severity:"warning"},"Create at least one query or expression to be alerted on")))};function on({onClickType:r}){const o=t.createElement(be.v,null,le.EJ.map(a=>t.createElement(q.u,{key:a.value,content:a.description??"",placement:"right"},t.createElement(ze.s,{key:a.value,onClick:()=>r(a.value??le.Us.math),label:a.label??""}))));return t.createElement(Fe.L,{overlay:o},t.createElement(B.zx,{variant:"secondary"},"Add expression",t.createElement(Se.J,{name:"angle-down"})))}const sn=r=>({addQueryButton:(0,n.css)`
    width: fit-content;
  `,helpInfo:(0,n.css)`
    display: flex;
    flex-direction: row;
    align-items: center;
    width: fit-content;
    font-weight: ${r.typography.fontWeightMedium};
    margin-left: ${r.spacing(1)};
    font-size: ${r.typography.size.sm};
    cursor: pointer;
  `,helpInfoText:(0,n.css)`
    margin-left: ${r.spacing(.5)};
    text-decoration: underline;
  `,infoLink:(0,n.css)`
    color: ${r.colors.text.link};
  `}),ln=()=>{const{setValue:r}=(0,N.Gc)();return o=>{const a=o[0];if(!a)return;if(!(0,O.F)().getInstanceSettings(a.datasourceUid))throw new Error("The Data source has not been defined.");if((0,ee.tO)(a.model)){const l=a.model.expr;r("expression",l)}}}},31559:(Je,re,e)=>{e.d(re,{G:()=>n});function n(y,t){const N=y.replace(/\(copy( [0-9]+)?\)$/,"").trim();let A=`${N} (copy)`;for(let U=2;t.includes(A);U++)A=`${N} (copy ${U})`;return A}},65577:(Je,re,e)=>{e.d(re,{K:()=>N});var n=e(41407),y=e(39953),t=e(82803);function N(U){const v=(0,t.wW)(A,U);return y.createElement("div",{className:v.root},U.children)}const A=(U,v)=>({root:(0,n.css)({display:"flex",flexDirection:v.direction??"row",flexWrap:v.wrap??!0?"wrap":void 0,alignItems:v.alignItems,gap:U.spacing(v.gap??2),flexGrow:v.flexGrow})})}}]);

//# sourceMappingURL=AlertingRuleForm.ef0ea4140d4d82a6b9dd.js.map