"use strict";(self.webpackChunkgrafana=self.webpackChunkgrafana||[]).push([[5372],{99632:(Ke,se,o)=>{o.r(se),o.d(se,{default:()=>or});var e=o(27702),K=o(25111),me=o(37647),U=o(18771),u=o(42844),$=o(63439),S=o(66310),R=o(66670);function k({title:t,children:a}){return e.createElement($.b,{className:(0,S.wW)(Ne).warning,severity:"warning",title:t},e.createElement("p",null,a),e.createElement(R.Qj,{href:"alerting/list"},"To rule list"))}const Ne=t=>({warning:(0,u.css)`
    margin: ${t.spacing(4)};
  `});var G=o(89949),be=o(26129),pe=o(52419),C=o(46089),j=o(7662),je=o(85014),fe=o(34667),ye=o(91106),V=o(22209),le=o(1128),xe=o(64022),Se=o(62108),Qe=o(29372),$t=o(3613),Nt=o(75443),bt=o(73807),ie=o(66574),Ze=o(75429),Qt=o(89033),Ye=o(28722),Re=o(10027),q=o(47702),p=o(72821),Ce=o(84369),N=o(85184),Ie=o(96437),ge=o(16310),Me=o(28580),Je=o(447),M=o(95017);const Xe=({rulesSourceName:t})=>{const{control:a,watch:n,formState:{errors:r},setValue:s}=(0,C.Gc)(),l=(0,S.wW)(Mt),c=(0,Re._)(y=>y.rulerRules),i=(0,U.useDispatch)();(0,e.useEffect)(()=>{i((0,q.UR)({rulesSourceName:t}))},[t,i]);const d=c[t]?.result,f=n("namespace"),m=(0,e.useMemo)(()=>d?Object.keys(d).map(y=>({label:y,value:y})):[],[d]),h=(0,e.useMemo)(()=>f&&d?.[f]?.map(y=>({label:y.name,value:y.name}))||[],[f,d]);return e.createElement("div",{className:l.flexRow},e.createElement(V.g,{"data-testid":"namespace-picker",label:"Namespace",error:r.namespace?.message,invalid:!!r.namespace?.message},e.createElement(ge.g,{render:({field:{onChange:y,ref:E,...g}})=>e.createElement(Me.LT,{...g,allowCustomValue:!0,className:l.input,onChange:w=>{s("group",""),y(w.value)},options:m,width:42}),name:"namespace",control:a,rules:{required:{value:!0,message:"Required."},validate:{pathSeparator:M.p0}}})),e.createElement(V.g,{"data-testid":"group-picker",label:"Group",error:r.group?.message,invalid:!!r.group?.message},e.createElement(ge.g,{render:({field:{ref:y,...E}})=>e.createElement(Me.LT,{...E,allowCustomValue:!0,options:h,width:42,onChange:g=>{s("group",g.value??"")},className:l.input}),name:"group",control:a,rules:{required:{value:!0,message:"Required."},validate:{pathSeparator:M.p0}}})))},Mt=t=>({flexRow:(0,u.css)`
    display: flex;
    flex-direction: row;
    justify-content: flex-start;

    & > * + * {
      margin-left: ${t.spacing(3)};
    }
  `,input:(0,u.css)`
    width: 330px !important;
  `});var Ft=o(93562),Lt=o(83639),Ut=o(60956),W=o(53933),B=o(10864),Gt=o(45383),Wt=o(39343),Ot=o(56469),zt=o(32900),Vt=o(35412),Bt=o(66784),ce=o(8508),Ht=o(73289),Kt=o(40545);function jt(t){return"expr"in t}function Zt(t){return"grafana_condition"in t}var te=o(22513);function Yt(t){if(jt(t))return ke(t,t.dataSourceUid,p.$.cloudAlerting);if(Zt(t))return ke(t,te.GC,p.$.grafana);throw new Error("unsupported preview rule request")}function ke(t,a,n){return(0,Vt.x)({whileLoading:Fe(n),source:(0,Ht.i)().fetch({method:"POST",url:`/api/v1/rule/test/${a}`,data:t}).pipe((0,Wt.U)(({data:r})=>Fe(n,{state:W.Gu.Done,series:r.instances.map(Bt.vP)})),(0,Ot.K)(r=>(0,Gt.of)(Fe(n,{state:W.Gu.Error,error:(0,Kt.P)(r)}))),(0,zt.B)())})}function Fe(t,a={}){return{ruleType:t,data:{state:W.Gu.Loading,series:[],timeRange:(0,ce.JK)(),...a}}}var Jt=o(2701),Xt=o(55925),kt=o(19221),qt=o(22323),_t=o(64167);function en(t){const{preview:a}=t,n=(0,S.wW)(tn),r={defaults:{},overrides:[{matcher:{id:kt.mi.byName,options:"Info"},properties:[{id:"custom.displayMode",value:_t.h2.JSONView}]}]};if(!a)return null;const{data:s,ruleType:l}=a;return s.state===W.Gu.Loading?e.createElement("div",{className:n.container},e.createElement("span",null,"Loading preview...")):s.state===W.Gu.Error?e.createElement("div",{className:n.container},s.error?(0,Ce.kk)(s.error):"Failed to preview alert rule"):e.createElement("div",{className:n.container},e.createElement("span",null,"Preview based on the result of running the query, for this moment."," ",l===p.$.grafana?"Configuration for `no data` and `error handling` is not applied.":null),e.createElement("div",{className:n.table},e.createElement(Xt.Z,null,({width:c,height:i})=>e.createElement("div",{style:{width:`${c}px`,height:`${i}px`}},e.createElement(qt.$,{title:"",width:c,height:i,pluginId:"table",data:s,fieldConfig:r})))))}function tn(t){return{container:(0,u.css)`
      margin: ${t.spacing(2)} 0;
    `,table:(0,u.css)`
      flex: 1 1 auto;
      height: 135px;
      margin-top: ${t.spacing(2)};
      border: 1px solid ${t.colors.border.medium};
      border-radius: ${t.shape.borderRadius(1)};
    `}}const nn=["type","dataSourceName","condition","queries","expression"];function an(){const t=(0,S.wW)(sn),[a,n]=qe(),{watch:r}=(0,C.Gc)(),[s,l,c]=r(["type","condition","queries"]),{allDataSourcesAvailable:i}=(0,Jt.S)(c);if(s===p.$.cloudRecording||s===p.$.cloudAlerting)return null;const d=!!l&&i;return e.createElement("div",{className:t.container},e.createElement(xe.Lh,null,i&&e.createElement(R.zx,{disabled:!d,type:"button",variant:"primary",onClick:n},"Preview alerts"),!i&&e.createElement($.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.")),e.createElement(en,{preview:a}))}function qe(){const[t,a]=(0,e.useState)(),{getValues:n}=(0,C.Gc)(),r=(0,Ft.Z)(),s=(0,e.useCallback)(()=>{const l=n(nn),c=rn(l);Yt(c).pipe((0,Lt.o)(i=>!on(i),!0)).subscribe(i=>{r()&&a(i)})},[n,r]);return[t,s]}function rn(t){const[a,n,r,s,l]=t,c=(0,B.F)().getInstanceSettings(n);if(!c)throw new Error(`Cannot find data source settings for ${n}`);switch(a){case p.$.cloudAlerting:return{dataSourceUid:c.uid,dataSourceName:n,expr:l};case p.$.grafana:return{grafana_condition:{condition:r,data:s,now:(0,Ut.lf)(Date.now())}};default:throw new Error(`Alert type ${a} not supported by preview.`)}}function on(t){switch(t.data.state){case W.Gu.Done:case W.Gu.Error:return!0;default:return!1}}function sn(t){return{container:(0,u.css)`
      margin-top: ${t.spacing(2)};
      max-width: ${t.breakpoints.values.xxl}px;
    `}}var ve=o(82669);const ln=()=>{const t=(0,S.wW)(cn),{register:a,control:n,watch:r,formState:{errors:s}}=(0,C.Gc)(),l=r("type"),c=r("dataSourceName");return l===p.$.cloudRecording?null:e.createElement(ve.z,{stepNo:3,title:"Set alert evaluation behavior"},e.createElement(V.g,{label:"Pending period",description:"Period in which an alert rule can be in breach of the condition until the alert rule fires."},e.createElement("div",{className:t.flexRow},e.createElement(V.g,{invalid:!!s.forTime?.message,error:s.forTime?.message,className:t.inlineField},e.createElement(le.I,{...a("forTime",{pattern:{value:/^\d+$/,message:"Must be a positive integer."}}),width:8})),e.createElement(ge.g,{name:"forTimeUnit",render:({field:{onChange:i,ref:d,...f}})=>e.createElement(Me.Ph,{...f,options:Je.qr,onChange:m=>i(m?.value),width:15,className:t.timeUnit}),control:n}))),l===p.$.cloudAlerting&&c&&e.createElement(Xe,{rulesSourceName:c}),e.createElement(an,null))},cn=t=>({inlineField:(0,u.css)`
    margin-bottom: 0;
  `,flexRow:(0,u.css)`
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    align-items: flex-start;
  `,timeUnit:(0,u.css)`
    margin-left: ${t.spacing(.5)};
  `});var F=o(23852),un=o(98321),we=o(51317);function dn(t,a){const n="Add annotations to provide more context in your alert notifications.";if(t===p.$.cloudRecording)return"Select the Namespace and Group for your recording rule.";const r="https://grafana.com/docs/grafana/latest/alerting/fundamentals/annotation-label/variables-label-annotation",s=t===p.$.grafana?` ${n} `:t===p.$.cloudAlerting?`Select the Namespace and evaluation group for your alert. ${n} `:"";return e.createElement(F.K,{gap:.5},`${s}`,e.createElement(we.h,{contentText:`Annotations add metadata to provide more information on the alert in your alert notifications. 
          For example, add a Summary annotation to tell you which value caused the alert to fire or which server it happened on.
          Annotations can contain a combination of text and template code.`,externalLink:r,linkText:"Read about annotations",title:"Annotations"}))}function mn(){const{watch:t}=(0,C.Gc)(),a=(0,S.wW)(pn),n=t("type"),r=t("dataSourceName"),s=t("type");return e.createElement(ve.z,{stepNo:s===p.$.cloudRecording?3:4,title:s===p.$.cloudRecording?"Add namespace and group":"Add annotations",description:dn(s,a)},n===p.$.cloudRecording&&r&&e.createElement(Xe,{rulesSourceName:r}),s!==p.$.cloudRecording&&e.createElement(un.Z,null))}const pn=t=>({needHelpText:(0,u.css)`
    color: ${t.colors.text.primary};
    font-size: ${t.typography.size.sm};
    margin-bottom: ${t.spacing(.5)};
    cursor: pointer;
    text-underline-position: under;
  `,needHelpTooltip:(0,u.css)`
    max-width: 300px;
    font-size: ${t.typography.size.sm};
    margin-left: 5px;

    div {
      margin-top: 5px;
      margin-bottom: 5px;
    }
  `,tooltipHeader:(0,u.css)`
    color: ${t.colors.text.primary};
    font-weight: bold;
  `,tooltipLink:(0,u.css)`
    color: ${t.colors.text.link};
    cursor: pointer;

    &:hover {
      text-decoration: underline;
    }
  `,underline:(0,u.css)`
    text-decoration: underline;
  `});var fn=o(278),gn=o(24393),_=o(73453),Z=o(50230),vn=o(9848),En=o(50115),_e=o(21323),hn=o(85096),yn=o(86954),et=o(62862),xn=o(52646),Sn=o(94752);const Rn=()=>{const{currentData:t}=xn.alertmanagerApi.useGetAlertmanagerChoiceStatusQuery(void 0),a=(0,Sn.S)().map(s=>({name:s.dataSource.name,img:s.dataSource.meta.info.logos.small})),n=t?.alertmanagersChoice;return n===et.TE.Internal?[{name:te.GC,img:"public/img/grafana_icon.svg"}]:n===et.TE.External?a:[{name:te.GC,img:"public/img/grafana_icon.svg"},...a]},Cn=(0,e.lazy)(()=>Promise.all([o.e(642),o.e(8050)]).then(o.bind(o,8050))),In=({alertQueries:t,customLabels:a,condition:n,folder:r,alertName:s,alertUid:l})=>{const c=(0,S.wW)(wn),{usePreviewMutation:i}=hn.alertRuleApi,[d,{data:f=[],isLoading:m,isUninitialized:h}]=i(),y=(0,G.compact)(f.flatMap(A=>A?.labels)),E=()=>{d({alertQueries:t,condition:n,customLabels:a,folder:r,alertName:s,alertUid:l})},g=Rn(),w=g.length===1,D=!f?.length&&!m;return e.createElement(yn.K,{direction:"column",gap:2},e.createElement("div",{className:c.routePreviewHeaderRow},e.createElement("div",{className:c.previewHeader},e.createElement(_e.x,{element:"h4"},"Alert instance routing preview")),e.createElement("div",{className:c.button},e.createElement(R.zx,{icon:"sync",variant:"secondary",type:"button",onClick:E},"Preview routing"))),!D&&e.createElement("div",{className:c.textMuted},"Based on the labels added, alert instances are routed to the following notification policies. Expand each notification policy below to view more details."),m&&e.createElement("div",{className:c.textMuted},"Loading..."),D&&e.createElement("div",{className:c.previewHowToText},'When your query and labels are configured, click "Preview routing" to see the results here.'),!m&&!h&&y.length>0&&e.createElement(e.Suspense,{fallback:e.createElement(pe.u,{text:"Loading preview..."})},g.map(A=>e.createElement(Cn,{alertManagerSource:A,potentialInstances:y,onlyOneAM:w,key:A.name}))))},wn=t=>({collapsableSection:(0,u.css)`
    width: auto;
    border: 0;
  `,textMuted:(0,u.css)`
    color: ${t.colors.text.secondary};
  `,previewHowToText:(0,u.css)`
    display: flex;
    color: ${t.colors.text.secondary};
    justify-content: center;
    font-size: ${t.typography.size.sm};
  `,previewHeader:(0,u.css)`
    margin: 0;
  `,routePreviewHeaderRow:(0,u.css)`
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
  `,collapseLabel:(0,u.css)`
    flex: 1;
  `,button:(0,u.css)`
    justify-content: flex-end;
    display: flex;
  `,tagsInDetails:(0,u.css)`
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
  `,policyPathItemMatchers:(0,u.css)`
    display: flex;
    flex-direction: row;
    gap: ${t.spacing(1)};
  `}),Dn=({alertUid:t})=>{const a=(0,S.wW)(Tn),{watch:n,getValues:r}=(0,C.Gc)(),[s,l,c,i,d,f]=n(["type","labels","queries","condition","folder","name"]),m=n("dataSourceName")??te.GC,h=An(r("labels")).length>0,y=!!i&&!!d&&s===p.$.grafana,E=()=>e.createElement("div",{className:a.stepDescription},e.createElement("div",null,"Add custom labels to change the way your notifications are routed."),e.createElement(we.h,{contentText:e.createElement(F.K,{gap:1},e.createElement(F.K,{direction:"row",gap:0},e.createElement(e.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."),e.createElement("a",{href:"https://grafana.com/docs/grafana/latest/alerting/fundamentals/notification-policies/notifications/",target:"_blank",rel:"noreferrer"},e.createElement("div",{className:a.infoLink},"Read about notification routing. ",e.createElement(_.J,{name:"external-link-alt"})))),e.createElement(F.K,{direction:"row",gap:0},e.createElement(e.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."),e.createElement("a",{href:"https://grafana.com/docs/grafana/latest/alerting/fundamentals/annotation-label/",target:"_blank",rel:"noreferrer"},e.createElement("div",{className:a.infoLink},"Read about Labels and annotations. ",e.createElement(_.J,{name:"external-link-alt"}))))),title:"Notification routing"}));return e.createElement(ve.z,{stepNo:s===p.$.cloudRecording?4:5,title:s===p.$.cloudRecording?"Add labels":"Configure notifications",description:s===p.$.cloudRecording?"Add labels to help you better manage your recording rules":e.createElement(E,null)},e.createElement("div",{className:a.contentWrapper},e.createElement("div",{style:{display:"flex",flexDirection:"column"}},!h&&s!==p.$.cloudRecording&&e.createElement(Z.Z,{className:a.card},e.createElement(Z.Z.Heading,null,"Default policy"),e.createElement(Z.Z.Description,null,"All alert instances are handled by the default policy if no other matching policies are found. To view and edit the default policy, go to ",e.createElement(vn.r,{href:"/alerting/routes"},"Notification Policies"),"\xA0or contact your Admin if you are using provisioning.")),e.createElement(En.Z,{dataSourceName:m}))),y&&i&&d&&e.createElement(In,{alertQueries:c,customLabels:l,condition:i,folder:d,alertName:f,alertUid:t}))};function An(t){return t.filter(a=>a.key&&a.value)}const Tn=t=>({contentWrapper:(0,u.css)`
    display: flex;
    align-items: center;
    margin-top: ${t.spacing(2)};
  `,hideButton:(0,u.css)`
    color: ${t.colors.text.secondary};
    cursor: pointer;
    margin-bottom: ${t.spacing(1)};
  `,card:(0,u.css)`
    max-width: 500px;
  `,flowChart:(0,u.css)`
    margin-right: ${t.spacing(3)};
  `,title:(0,u.css)`
    margin-bottom: ${t.spacing(2)};
  `,stepDescription:(0,u.css)`
    margin-bottom: ${t.spacing(2)};
    display: flex;
    gap: ${t.spacing(1)};
)};
  `,infoLink:(0,u.css)`
    color: ${t.colors.text.link};
  `});var Pn=o(3972),$n=o(74639),De=o(80011),Nn=o(89746),bn=o(79655),Qn=o(80434),ue=o(55692),ee=o(65946);function tt(){const t=(0,Re._)(n=>n.dataSources);return Object.values(t).map(n=>n.result).filter(n=>!!n?.rulerConfig).map(n=>(0,te.c$)(n.name)).filter(n=>!!n)}var Mn=o(61576),Ae=o(62247),Fn=o(86004),Ln=o(77328),Un=o(68614),Gn=o(18447);function Wn({fields:t}){const a=t.filter(i=>!["State","Info"].includes(i.name)),n=t.findIndex(i=>i.name==="State"),r=t.findIndex(i=>i.name==="Info"),s=a.map(i=>t.indexOf(i)),l=t[n]?.values.length??0,c=[];for(let i=0;i<l;i++){const d=s.map(h=>[t[h].name,t[h].values[i]]),f=t[n]?.values?.[i],m=t[r]?.values?.[i];(0,Gn.Yb)(f)&&c.push({state:f,info:m,labels:Object.fromEntries(d)})}return{instances:c}}function On({preview:t}){const a=(0,S.wW)(zn),n=Wn(t);return e.createElement("table",{className:a.table},e.createElement("caption",null,e.createElement("div",null,"Alerts preview"),e.createElement("span",null,"Preview based on the result of running the query for this moment.")),e.createElement("thead",null,e.createElement("tr",null,e.createElement("th",null,"State"),e.createElement("th",null,"Labels"),e.createElement("th",null,"Info"))),e.createElement("tbody",null,n.instances.map(({state:r,info:s,labels:l},c)=>{const i=(0,Ln.P3)(l);return e.createElement("tr",{key:c},e.createElement("td",null,e.createElement(Un.l,{state:r})),e.createElement("td",null,e.createElement(Fn.P,{tags:i,className:a.tagList})),e.createElement("td",null,s&&e.createElement(De.u,{content:s},e.createElement(_.J,{name:"info-circle"}))))})))}const zn=t=>({table:(0,u.css)`
    width: 100%;
    margin: ${t.spacing(2,0)};

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

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

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

    td + td,
    th + th {
      padding-left: ${t.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: ${t.colors.background.secondary};
    }
  `,tagList:(0,u.css)`
    justify-content: flex-start;
  `}),Vn=({value:t,onChange:a,dataSourceName:n,showPreviewAlertsButton:r=!0})=>{const s=(0,S.wW)(Bn),{mapToValue:l,mapToQuery:c}=Hn(n),i=c({refId:"A",hide:!1},t),{error:d,loading:f,value:m}=(0,K.Z)(()=>(0,B.F)().get(n),[n]),h=(0,e.useCallback)(Q=>{a(l(Q))},[a,l]),[y,E]=qe(),g=async()=>{E()};if(f||m?.name!==n)return null;const w=(0,B.F)().getInstanceSettings(n);if(d||!m||!m?.components?.QueryEditor||!w){const Q=d?.message||"Data source plugin does not export any Query Editor component";return e.createElement("div",null,"Could not load query editor due to: ",Q)}const D=y?.data.state===W.Gu.Done,A=m?.components?.QueryEditor,O=y?.data?.series?.find(Q=>Q.name==="evaluation results"),L=O&&O.fields.some(Q=>Q.values.length>0);return e.createElement(e.Fragment,null,e.createElement(Mn.n,{instanceSettings:w},e.createElement(A,{query:i,queries:[i],app:Ae.zj.CloudAlerting,onChange:h,onRunQuery:G.noop,datasource:m})),r&&e.createElement("div",{className:s.preview},e.createElement(R.zx,{type:"button",onClick:g,disabled:y?.data.state===W.Gu.Loading},"Preview alerts"),D&&!L&&e.createElement($.b,{title:"Alerts preview",severity:"info",className:s.previewAlert},"There are no firing alerts for your query."),L&&e.createElement(On,{preview:O})))},Bn=t=>({preview:(0,u.css)`
    padding: ${t.spacing(2,0)};
    max-width: ${t.breakpoints.values.xl}px;
  `,previewAlert:(0,u.css)`
    margin: ${t.spacing(1,0)};
  `});function Hn(t){return(0,e.useMemo)(()=>{switch((0,B.F)().getInstanceSettings(t)?.type){case"loki":case"prometheus":return{mapToValue:n=>n.expr,mapToQuery:(n,r)=>({...n,expr:r})};default:throw new Error(`${t} is not supported as an expression editor`)}},[t])}var Kn=o(68525);const jn=({condition:t,onSetCondition:a,queries:n,panelData:r,onUpdateRefId:s,onRemoveExpression:l,onUpdateExpressionType:c,onUpdateQueryExpression:i})=>{const d=(0,e.useMemo)(()=>n.reduce((m,h)=>(0,ue.j)(h.model)?m.concat(h.model):m,[]),[n]),f=(0,S.wW)(Zn);return e.createElement("div",{className:f.wrapper},d.map(m=>{const h=r[m.refId],y=t===m.refId,E=y&&h?(0,M.Vp)(h.series):void 0,g=y&&h?(0,M.Yq)(h.series):void 0;return e.createElement(Kn.A2,{key:m.refId,isAlertCondition:y,data:h,error:E,warning:g,queries:n,query:m,onSetCondition:a,onRemoveExpression:l,onUpdateRefId:s,onUpdateExpressionType:c,onChangeQuery:i})}))},Zn=t=>({wrapper:(0,u.css)`
    display: flex;
    gap: ${t.spacing(2)};
    align-content: stretch;
    flex-wrap: wrap;
  `});var nt=o(85532),Le=o(76305),Yn=o(10186),Jn=o(5926),at=o(60644),Xn=o(47802),kn=o(51145),qn=o(99633),_n=o(16532),ea=o(2184);const ta=({query:t,queryOptions:a,onChangeTimeRange:n,onChangeQueryOptions:r,index:s})=>{const l=(0,S.wW)(na),[c,i]=(0,e.useState)(!1),d=t.relativeTimeRange?(0,Le.relativeToTimeRange)(t.relativeTimeRange):void 0;return e.createElement(e.Fragment,null,e.createElement(_n.P,{content:e.createElement("div",{className:l.container},e.createElement("div",null,n&&e.createElement("div",{className:l.timeRangeContainer},e.createElement("span",{className:l.timeRangeLabel},"Time Range"),e.createElement(ea.x,{timeRange:t.relativeTimeRange??(0,ce.Rr)(),onChange:f=>n(f,s)}))),e.createElement("div",{className:l.queryOptions},e.createElement(la,{options:a,onChange:f=>r(f,s)}),e.createElement(ia,{options:a,onChange:f=>r(f,s)}))),closeButton:!0,placement:"bottom-start"},e.createElement("button",{type:"button",className:l.actionLink,onClick:()=>i(!c)},"Options ",c?e.createElement(_.J,{name:"angle-right"}):e.createElement(_.J,{name:"angle-down"}))),e.createElement("div",{className:l.staticValues},e.createElement("span",null,(0,qn.CQ)(d?.from).locale("en").fromNow(!0)),a.maxDataPoints&&e.createElement("span",null,", MD = ",a.maxDataPoints),a.minInterval&&e.createElement("span",null,", Min. Interval = ",a.minInterval)))},na=t=>{const a=(0,R.gN)(t);return{container:(0,u.css)`
      display: flex;
      flex-direction: column;
      gap: 10px;
    `,timeRangeContainer:(0,u.css)`
      display: flex;
    `,timeRangeLabel:(0,u.css)`
      width: 20%;
    `,queryOptions:(0,u.css)`
      margin-bottom: -${t.spacing(2)};

      label {
        line-height: 12px;
        padding: 0px;
      }
    `,staticValues:(0,u.css)`
      color: ${t.colors.text.secondary};
      margin-right: ${t.spacing(1)};
    `,actionLink:(0,u.css)`
      ${a};
      color: ${t.colors.text.link};
      cursor: pointer;

      &:hover {
        text-decoration: underline;
      }
    `}};var rt=o(98445);const aa=43200,ra="1s",oa=({data:t,error:a,dsSettings:n,index:r,onChangeDataSource:s,onChangeQuery:l,onChangeTimeRange:c,onRunQueries:i,onRemoveQuery:d,onDuplicateQuery:f,query:m,queries:h,thresholds:y,thresholdsType:E,onChangeThreshold:g,condition:w,onSetCondition:D,onChangeQueryOptions:A})=>{const O=(0,S.wW)(Ue),[L,Q]=(0,e.useState)(),ne={...L?.getDefaultQuery?L.getDefaultQuery(Ae.zj.UnifiedAlerting):{},...(0,G.cloneDeep)(m.model)};function P(){const T=(0,S.wW)(Ue);return e.createElement("div",{className:T.dsTooltip},e.createElement(De.u,{content:e.createElement(e.Fragment,null,"Not finding the data source you want? Some data sources are not supported for alerting. Click on the icon for more information.")},e.createElement(_.J,{name:"info-circle",onClick:()=>window.open(" https://grafana.com/docs/grafana/latest/alerting/fundamentals/data-source-alerting/","_blank")})))}function ae({query:T,error:re,index:H}){const oe={maxDataPoints:T.model.maxDataPoints,minInterval:T.model.intervalMs?(0,Je.gS)(T.model.intervalMs):void 0},Y={maxDataPoints:oe.maxDataPoints,minInterval:oe.minInterval};return e.createElement(F.K,{direction:"row",alignItems:"baseline",gap:1},e.createElement(P,null),e.createElement(ta,{onChangeTimeRange:c,query:T,queryOptions:Y,onChangeQueryOptions:A,index:H}),e.createElement(kn._,{onSetCondition:()=>D(T.refId),enabled:w===T.refId,error:re}))}const he=t.state!==W.Gu.NotStarted;return e.createElement(F.K,{direction:"column",gap:.5},e.createElement("div",{className:O.wrapper},e.createElement(Xn.x,{alerting:!0,collapsable:!1,dataSource:n,onDataSourceLoaded:Q,onChangeDataSource:T=>s(T,r),id:m.refId,index:r,key:m.refId,data:t,query:ne,onChange:T=>l(T,r),onRemoveQuery:d,onAddQuery:()=>f((0,G.cloneDeep)(m)),onRunQuery:i,queries:h,renderHeaderExtras:()=>e.createElement(ae,{query:m,index:r,error:a}),app:Ae.zj.UnifiedAlerting,hideDisableQuery:!0})),he&&e.createElement(rt.l,{data:t,thresholds:y,thresholdsType:E,onThresholdsChange:g?T=>g(T,r):void 0}))},sa=({children:t})=>{const a=(0,S.wW)(Ue);return e.createElement("div",{className:a.wrapper},t)};function la({options:t,onChange:a}){const n=t.maxDataPoints??"",r=s=>{const l=parseInt(s.target.value,10),c=isNaN(l)||l===0?void 0:l;c!==t.maxDataPoints&&a({...t,maxDataPoints:c})};return e.createElement(F.K,{direction:"row",alignItems:"baseline",gap:1},e.createElement(at.c,{width:8,tooltip:e.createElement(e.Fragment,null,"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.")},"Max data points"),e.createElement(le.I,{type:"number",className:"width-6",placeholder:aa.toLocaleString(),spellCheck:!1,onBlur:r,defaultValue:n}))}function ia({options:t,onChange:a}){const n=t.minInterval??"",r=s=>{const l=s.target.value;l!==n&&a({...t,minInterval:l})};return e.createElement(F.K,{direction:"row",alignItems:"baseline",gap:1},e.createElement(at.c,{width:8,tooltip:e.createElement(e.Fragment,null,"A lower limit for the interval. Recommended to be set to write frequency, for example ",e.createElement("code",null,"1m")," if your data is written every minute.")},"Min interval"),e.createElement(le.I,{type:"text",className:"width-6",placeholder:ra,spellCheck:!1,onBlur:r,defaultValue:n}))}const Ue=t=>({wrapper:(0,u.css)`
    label: AlertingQueryWrapper;
    margin-bottom: ${t.spacing(1)};
    border: 1px solid ${t.colors.border.weak};
    border-radius: ${t.shape.borderRadius(1)};

    button {
      overflow: visible;
    }
  `,queryOptions:(0,u.css)`
    margin-bottom: -${t.spacing(2)};
  `,dsTooltip:(0,u.css)`
    display: flex;
    align-items: center;
    &:hover {
      opacity: 0.85;
      cursor: pointer;
    }
  `});class ca extends e.PureComponent{constructor(a){super(a),this.onRemoveQuery=n=>{const{queries:r,onQueriesChange:s}=this.props;s(r.filter(l=>l.refId!==n.refId))},this.onChangeTimeRange=(n,r)=>{const{queries:s,onQueriesChange:l}=this.props;l(s.map((c,i)=>i!==r?c:{...c,relativeTimeRange:n}))},this.onChangeQueryOptions=(n,r)=>{const{queries:s,onQueriesChange:l}=this.props;l(s.map((c,i)=>i!==r?c:{...c,model:{...c.model,maxDataPoints:n.maxDataPoints,intervalMs:n.minInterval?Le.intervalToMs(n.minInterval):void 0}}))},this.onChangeDataSource=(n,r)=>{const{queries:s,onQueriesChange:l}=this.props,c=s.map((i,d)=>{if(d!==r)return i;const f=this.getDataSourceSettings(i);return n.type===f?.type?ua(i,n):da(i,n)});l(c)},this.onChangeQuery=(n,r)=>{const{queries:s,onQueriesChange:l}=this.props;l(s.map((c,i)=>i!==r?c:{...c,refId:n.refId,queryType:c.model.queryType??"",model:{...c.model,...n,datasource:n.datasource}}))},this.onDragEnd=n=>{const{queries:r,onQueriesChange:s}=this.props;if(!n||!n.destination)return;const l=n.source.index,c=n.destination.index;if(l===c)return;const i=Array.from(r),[d]=i.splice(l,1);i.splice(c,0,d),s(i)},this.getDataSourceSettings=n=>(0,B.F)().getInstanceSettings(n.datasourceUid)}render(){const{queries:a,expressions:n}=this.props,r=(0,M.Fu)([...a,...n]);return e.createElement(nt.Z5,{onDragEnd:this.onDragEnd},e.createElement(nt.bK,{droppableId:"alerting-queries",direction:"vertical"},s=>e.createElement("div",{ref:s.innerRef,...s.droppableProps},e.createElement(F.K,{direction:"column"},a.map((l,c)=>{const i=this.props.data?.[l.refId]??{series:[],state:W.Gu.NotStarted},d=this.getDataSourceSettings(l),m=this.props.condition===l.refId?(0,M.Vp)(i.series):void 0;return d?e.createElement(oa,{index:c,key:l.refId,dsSettings:d,data:i,error:m,query:l,onChangeQuery:this.onChangeQuery,onRemoveQuery:this.onRemoveQuery,queries:[...a,...n],onChangeDataSource:this.onChangeDataSource,onDuplicateQuery:this.props.onDuplicateQuery,onChangeTimeRange:this.onChangeTimeRange,onChangeQueryOptions:this.onChangeQueryOptions,thresholds:r[l.refId]?.config,thresholdsType:r[l.refId]?.mode,onRunQueries:this.props.onRunQueries,condition:this.props.condition,onSetCondition:this.props.onSetCondition}):e.createElement(ma,{key:`${l.refId}-${c}`,index:c,model:l.model,onUpdateDatasource:()=>{const h=(0,Jn.ak)().getInstanceSettings(null);h&&this.onChangeDataSource(h,c)},onRemoveQuery:()=>{this.onRemoveQuery(l)}})}),s.placeholder))))}}function ua(t,a){return{...t,model:{...(0,G.omit)(t.model,"datasource"),datasource:{type:a.type,uid:a.uid}},datasourceUid:a.uid}}function da(t,a){return{refId:t.refId,relativeTimeRange:t.relativeTimeRange,queryType:"",datasourceUid:a.uid,model:{refId:t.refId,hide:!1,datasource:{type:a.type,uid:a.uid}}}}const ma=({index:t,onUpdateDatasource:a,onRemoveQuery:n,model:r})=>{const s=r.refId,[l,c]=(0,e.useState)(!1),i=()=>{c(f=>!f)},d=()=>{a()};return e.createElement(sa,null,e.createElement(Yn.t,{title:s,draggable:!0,index:t,id:s,isOpen:!0,collapsable:!1},e.createElement(Z.Z,null,e.createElement(Z.Z.Heading,null,"This datasource has been removed"),e.createElement(Z.Z.Description,null,"The datasource for this query was not found, it was either removed or is not installed correctly."),e.createElement(Z.Z.Figure,null,e.createElement(_.J,{name:"question-circle"})),e.createElement(Z.Z.Actions,null,e.createElement(R.zx,{key:"update",variant:"secondary",onClick:d},"Update datasource"),e.createElement(R.zx,{key:"remove",variant:"destructive",onClick:n},"Remove query")),e.createElement(Z.Z.SecondaryActions,null,e.createElement(R.zx,{key:"details",onClick:i,icon:l?"angle-up":"angle-down",fill:"text",size:"sm"},"Show details"))),l&&e.createElement("div",null,e.createElement("pre",null,e.createElement("code",null,JSON.stringify(r,null,2))))))},pa=({queries:t,expressions:a,panelData:n,onRunQueries:r,onChangeQueries:s,onDuplicateQuery:l,condition:c,onSetCondition:i})=>{const d=(0,S.wW)(fa);return e.createElement("div",{className:d.container},e.createElement(ca,{data:n,queries:t,expressions:a,onRunQueries:r,onQueriesChange:s,onDuplicateQuery:l,condition:c,onSetCondition:i}))},fa=t=>({container:(0,u.css)`
    background-color: ${t.colors.background.primary};
    height: 100%;
  `});var ga=o(66805),va=o(26858);const Ea=({queries:t,onChangeQuery:a,runQueries:n,panelData:r,dataSourceName:s})=>{const[l,c]=(0,e.useState)({series:[],state:ga.Gu.NotStarted,timeRange:(0,va.$t)().timeRange()}),i=(0,S.wW)(ha);(0,e.useEffect)(()=>{c(r?.[t[0]?.refId])},[r,t]);const{error:d,loading:f,value:m}=(0,K.Z)(()=>(0,B.F)().get(s),[s]),h=g=>{const w=t[0],D=(0,B.F)().getInstanceSettings(s)?.uid;if(!(0,N.tO)(g)||!D)return;const A=g.expr,O={...w,refId:g.refId,queryType:g.queryType??"",datasourceUid:D,expr:A,model:{refId:g.refId,expr:A,editorMode:"code"}};a([O])};if(f||m?.name!==s)return null;const y=(0,B.F)().getInstanceSettings(s);if(d||!m||!m?.components?.QueryEditor||!y){const g=d?.message||"Data source plugin does not export any Query Editor component";return e.createElement("div",null,"Could not load query editor due to: ",g)}const E=m.components.QueryEditor;return e.createElement(e.Fragment,null,t.length&&e.createElement(E,{query:t[0],queries:t,app:Ae.zj.UnifiedAlerting,onChange:h,onRunQuery:n,datasource:m}),l&&e.createElement("div",{className:i.vizWrapper},e.createElement(rt.l,{data:l})))},ha=t=>({vizWrapper:(0,u.css)`
    margin: ${t.spacing(1,0)};
  `});var ya=o(53229),ot=o(84749);function xa({value:t,...a}){const n=tt(),{loading:r=!0}=(0,K.Z)(()=>(0,ot.WI)((0,q.dV)()),[ot.WI]),s=(0,e.useCallback)(l=>!!n.find(({id:c})=>c===l.id),[n]);return e.createElement(ya.q,{disabled:r,noDefault:!0,alerting:!0,filter:s,current:t,...a})}const Sa=({onChangeCloudDatasource:t})=>{const{control:a,formState:{errors:n},setValue:r,watch:s}=(0,C.Gc)(),l=(0,S.wW)(Ra),c=s("type");return e.createElement(e.Fragment,null,e.createElement("div",{className:l.flexRow},(c===p.$.cloudAlerting||c===p.$.cloudRecording)&&e.createElement(V.g,{className:l.formInput,label:"Select data source",error:n.dataSourceName?.message,invalid:!!n.dataSourceName?.message,"data-testid":"datasource-picker"},e.createElement(ge.g,{render:({field:{onChange:i,ref:d,...f}})=>e.createElement(xa,{...f,onChange:m=>{r("location",void 0),r("expression",""),i(m?.name??null),t(m?.uid??null)}}),name:"dataSourceName",control:a,rules:{required:{value:!0,message:"Please select a data source"}}}))))},Ra=t=>({formInput:(0,u.css)`
    width: 330px;
    & + & {
      margin-left: ${t.spacing(3)};
    }
  `,flexRow:(0,u.css)`
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    align-items: flex-end;
  `});function Ca(){const t=ie.Vt.hasAccess(U.AccessControlAction.AlertingRuleCreate,ie.Vt.hasEditPermissionInFolders),a=ie.Vt.hasAccess(U.AccessControlAction.AlertingRuleExternalWrite,ie.Vt.isEditor),n=t?p.$.grafana:p.$.cloudAlerting,r=[];return t&&r.push(p.$.grafana),a&&r.push(p.$.cloudAlerting,p.$.cloudRecording),{enabledRuleTypes:r,defaultRuleType:n}}const Ia=t=>t.filter(a=>a.datasourceUid!==ee.Yq).length===1,wa=({queries:t,ruleFormType:a,editingExistingRule:n,rulesSourcesWithRuler:r})=>{const s=Ca(),l=Ia(t),c=t[0]?.datasourceUid??"",i=a===p.$.cloudRecording,d=!n&&!i&&l&&r.some(g=>g.uid===c),f=!n&&!i,m=s.enabledRuleTypes.includes(p.$.grafana),h=s.enabledRuleTypes.includes(p.$.cloudAlerting),y=a===p.$.cloudAlerting&&m&&f,E=a===p.$.grafana&&d&&h&&d;return y||E},Da=(t,a,n,r)=>a?t===p.$.grafana?{contentText:"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. ",title:"This alert rule is managed by Grafana."}:{contentText:"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.",title:`This alert rule is managed by the data source ${n}.`}:r?t===p.$.cloudAlerting?{contentText:"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.",title:`This alert rule is managed by the data source ${n}. If you want to use expressions or have multiple queries, switch to a Grafana-managed alert rule.`}:{contentText:"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.",title:"This alert rule will be managed by Grafana. The selected data source is configured to support rule creation."}:{contentText:"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.",title:"Based on the data sources selected, this alert rule is managed by Grafana."};function st({editingExistingRule:t,rulesSourcesWithRuler:a,queries:n,onClickSwitch:r}){const{getValues:s}=(0,C.Gc)(),[l,c]=s(["type","dataSourceName"]),i=(0,S.wW)(Aa),d=wa({queries:n,ruleFormType:l,editingExistingRule:t,rulesSourcesWithRuler:a}),f=l===p.$.cloudAlerting?"Data source-managed alert rule":"Grafana-managed alert rule",m=l!==p.$.cloudAlerting?"data source-managed":"Grafana-managed",h=l?Da(l,t,c??"",d):void 0;return e.createElement("div",{className:i.alert},e.createElement($.b,{severity:"info",title:f,onRemove:d?r:void 0,buttonContent:`Switch to ${m} alert rule`},e.createElement(F.K,{gap:.5,direction:"row",alignItems:"baseline"},e.createElement("div",{className:i.alertText},h?.title),e.createElement("div",{className:i.needInfo},e.createElement(we.h,{contentText:h?.contentText??"",externalLink:"https://grafana.com/docs/grafana/latest/alerting/fundamentals/alert-rules/alert-rule-types/",linkText:"Read about alert rule types",title:" Alert rule types"})))))}const Aa=t=>({alertText:(0,u.css)`
    max-width: fit-content;
    flex: 1;
  `,alert:(0,u.css)`
    margin-top: ${t.spacing(2)};
  `,needInfo:(0,u.css)`
    flex: 1;
    max-width: fit-content;
  `});var b=o(34099),Ta=o(76897);const Pa=t=>{try{return JSON.stringify(t),!1}catch{return!0}},lt=(t,a)=>{if(Pa(t))return null;if(a.datasourceUid!==ee.Yq)return a;{const n=t.find(r=>r.refId===a.model.expression);return n?lt(t,n):null}};var it=o(11122),ct=o(22283);const ut=(t,a)=>{const n=t.find(s=>s.refId===a);return n&&lt(t,n)},$a={queries:[]},dt=(0,b.PH)("duplicateQuery"),mt=(0,b.PH)("addNewDataQuery"),Te=(0,b.PH)("setDataQueries"),pt=(0,b.PH)("addNewExpression"),ft=(0,b.PH)("removeExpression"),gt=(0,b.PH)("removeExpressions"),vt=(0,b.PH)("addExpressions"),Et=(0,b.PH)("updateExpression"),ht=(0,b.PH)("updateExpressionRefId"),yt=(0,b.PH)("rewireExpressions"),xt=(0,b.PH)("updateExpressionType"),St=(0,b.PH)("updateExpressionTimeRange"),Na=(0,b.PH)("updateMaxDataPoints"),ba=(0,b.PH)("updateMinInterval"),Ge=(0,b.PH)("setRecordingRulesQueries"),Qa=(0,b.Lq)($a,t=>{t.addCase(dt,(a,{payload:n})=>{a.queries=We(a.queries,n)}).addCase(mt,a=>{const n=(0,te.P)();n&&(a.queries=We(a.queries,{datasourceUid:n.uid,model:{refId:"",datasource:{type:n.type,uid:n.uid}}}))}).addCase(Te,(a,{payload:n})=>{const r=a.queries.filter(s=>(0,ue.j)(s.model));a.queries=[...n,...r]}).addCase(Ge,(a,{payload:n})=>{const r=n.recordingRuleQueries[0],s={...r,expr:n.expression,model:{expr:n.expression,refId:r.model.refId}};a.queries=[s]}).addCase(Na,(a,n)=>{a.queries=a.queries.map(r=>r.refId===n.payload.refId?{...r,model:{...r.model,maxDataPoints:n.payload.maxDataPoints}}:r)}).addCase(ba,(a,n)=>{a.queries=a.queries.map(r=>r.refId===n.payload.refId?{...r,model:{...r.model,intervalMs:n.payload.minInterval?Le.intervalToMs(n.payload.minInterval):void 0}}:r)}),t.addCase(pt,(a,{payload:n})=>{a.queries=We(a.queries,{datasourceUid:ee.Yq,model:it.mV.newQuery({type:n,conditions:[{...ct.R,query:{params:[]}}],expression:""})})}).addCase(ft,(a,{payload:n})=>{a.queries=a.queries.filter(r=>r.refId!==n)}).addCase(gt,a=>{a.queries=a.queries.filter(n=>!(0,ue.j)(n.model))}).addCase(vt,(a,{payload:n})=>{a.queries=[...a.queries,...n]}).addCase(Et,(a,{payload:n})=>{a.queries=a.queries.map(r=>{const s=ut(a.queries,n.expression),l=s?s.relativeTimeRange:(0,ce.Rr)();return r.refId===n.refId&&(r.model=n,n.type===ee.Us.resample&&(r.relativeTimeRange=l)),r})}).addCase(St,a=>{const n=a.queries.map(r=>{if(r.datasourceUid===ee.Yq){const s=ut(a.queries,r.model.expression),l=s?s.relativeTimeRange:(0,ce.Rr)();r.relativeTimeRange=l}return r});a.queries=n}).addCase(ht,(a,{payload:n})=>{const{newRefId:r,oldRefId:s}=n;if((0,M.Dr)(a.queries,r))return;const c=(0,M.Ry)(a.queries,s,r);a.queries=c.map(i=>i.refId===s?{...i,refId:r,model:{...i.model,refId:r}}:i)}).addCase(yt,(a,{payload:n})=>{a.queries=(0,M.Ry)(a.queries,n.oldRefId,n.newRefId)}).addCase(xt,(a,n)=>{a.queries=a.queries.map(r=>r.refId===n.payload.refId?{...r,model:{...it.mV.newQuery({type:n.payload.type,conditions:[{...ct.R,query:{params:[]}}],expression:""}),refId:n.payload.refId}}:r)})}),We=(t,a)=>{const n=(0,Ta.Hs)(t),r={...a,refId:n,queryType:"",model:{...a.model,hide:!1,refId:n},relativeTimeRange:a.relativeTimeRange??Ma(a.model)};return[...t,r]},Ma=t=>{if(!(0,ue.j)(t))return(0,ce.Rr)()};var Fa=o(73475);function La(){const[t,a]=(0,e.useState)({}),n=(0,e.useRef)(new Fa.v);(0,e.useEffect)(()=>{const i=n.current;return i.get().subscribe(d=>{a(d)}),()=>{i.destroy()}},[]);const r=(0,e.useCallback)(()=>{a({})},[]),s=(0,e.useCallback)(()=>{n.current.cancel()},[]),l=(0,e.useCallback)(i=>{n.current.run(i)},[]),c=(0,e.useMemo)(()=>Object.values(t).some(i=>i.state===W.Gu.Loading),[t]);return{queryPreviewData:t,runQueries:l,cancelQueries:s,isPreviewLoading:c,clearPreviewData:r}}const Ua=({editingExistingRule:t,onDataChange:a})=>{const{setValue:n,getValues:r,watch:s,formState:{errors:l},control:c}=(0,C.Gc)(),{queryPreviewData:i,runQueries:d,cancelQueries:f,isPreviewLoading:m,clearPreviewData:h}=La(),y={queries:r("queries")},[{queries:E},g]=(0,e.useReducer)(Qa,y),[w,D,A]=s(["type","condition","dataSourceName"]),O=w===p.$.grafana,L=w===p.$.cloudRecording,Q=w===p.$.cloudAlerting,Ee=(0,U.useDispatch)();(0,e.useEffect)(()=>{Ee((0,q.dV)())},[Ee]);const ne=tt(),P=(0,e.useCallback)(()=>{d(r("queries"))},[d,r]);(0,e.useEffect)(()=>{n("queries",E,{shouldValidate:!1})},[E,d,n]);const ae=(0,te.P)()===void 0,he=(0,e.useMemo)(()=>E.filter(v=>!(0,ue.j)(v.model)),[E]),T=(0,e.useMemo)(()=>E.filter(v=>(0,ue.j)(v.model)),[E]),re=E.length===0;(0,e.useEffect)(()=>{const v=r("condition");if(!v||p.$.cloudRecording)return;const x=(0,M.Vp)(i[v]?.series||[]);a(x?.message||"")},[i,r,a]);const H=(0,e.useCallback)(v=>{v&&(P(),n("condition",v))},[P,n]),oe=(0,e.useCallback)((v,x)=>{(0,M.Dr)(E,x)||(g(ht({oldRefId:v,newRefId:x})),D===v&&H(x))},[D,E,H]),Y=Oa(),Pe=(0,e.useCallback)(v=>{n("queries",v,{shouldValidate:!1}),Y(v),g(Te(v)),g(St());const[x,z]=(0,M.eW)(E,v);x&&z&&g(yt({oldRefId:x,newRefId:z}))},[E,n,Y]),Ve=(0,e.useCallback)(v=>{const x=v[0],z=(0,B.F)().getInstanceSettings(x.datasourceUid);if(!z)throw new Error("The Data source has not been defined.");if(!(0,N.tO)(x.model))return;const Pt=x.model.expr;n("queries",v,{shouldValidate:!1}),n("dataSourceName",z.name),n("expression",Pt),g(Ge({recordingRuleQueries:v,expression:Pt})),P()},[P,n]),I=ne[0];(0,e.useEffect)(()=>{if(h(),w===p.$.cloudRecording){const v=r("expression");if(!I)return;const z={refId:"A",datasourceUid:t&&(0,B.F)().getInstanceSettings(A)?.uid||I.uid,queryType:"",relativeTimeRange:(0,ce.Rr)(),expr:v,model:{refId:"A",hide:!1,expr:v}};g(Ge({recordingRuleQueries:[z],expression:v}))}},[w,I,t,r,A,h]);const Be=(0,e.useCallback)(v=>{g(dt(v))},[]);(0,e.useEffect)(()=>{if(!(0,M.Dr)(E,D)){const v=E.at(-1)?.refId??null;H(v)}},[D,E,H]);const J=(0,e.useCallback)(v=>{g(pt(v))},[g]),X=(0,S.wW)(Wa),sr=(0,e.useCallback)(v=>{const x=(0,G.cloneDeep)(E);x[0].datasourceUid=v,n("queries",x,{shouldValidate:!1}),Y(x),g(Te(x))},[E,n,Y,g]),lr=v=>{const x=(0,G.cloneDeep)(E);if(x[0].model)if((0,N.tO)(x[0].model))x[0].model.expr=v;else{const z={...(0,G.cloneDeep)(x[0].model),expr:v};x[0].model=z}n("queries",x,{shouldValidate:!1}),Y(x),g(Te(x)),P()},It=(0,e.useCallback)(()=>g(gt()),[g]),wt=(0,e.useCallback)(v=>g(vt(v)),[g]),[$e,Dt]=(0,e.useState)([]),[He,ir]=(0,e.useState)(null),At=(0,e.useCallback)(()=>{wt($e)},[$e,wt]),Tt=(0,e.useCallback)(()=>{if(r("type")===p.$.cloudAlerting)n("type",p.$.grafana),$e.length>0&&At(),He&&n("condition",He);else{n("type",p.$.cloudAlerting);const x=E.filter(z=>z.datasourceUid===ee.Yq);Dt(x),It(),ir(D)}},[r,n,E,It,At,Dt,$e,He,D]);return e.createElement(ve.z,{stepNo:2,title:w!==p.$.cloudRecording?"Define query and alert condition":"Define query"},(w===p.$.cloudRecording||w===p.$.cloudAlerting)&&e.createElement(Sa,{onChangeCloudDatasource:sr}),L&&A&&e.createElement(V.g,{error:l.expression?.message,invalid:!!l.expression?.message},e.createElement(Ea,{dataSourceName:A,queries:E,runQueries:P,onChangeQuery:Ve,panelData:i})),Q&&A&&e.createElement(F.K,{direction:"column"},e.createElement(V.g,{error:l.expression?.message,invalid:!!l.expression?.message},e.createElement(ge.g,{name:"expression",render:({field:{ref:v,...x}})=>e.createElement(Vn,{...x,dataSourceName:A,showPreviewAlertsButton:!L,onChange:lr}),control:c,rules:{required:{value:!0,message:"A valid expression is required"}}})),e.createElement(st,{editingExistingRule:t,queries:E,rulesSourcesWithRuler:ne,onClickSwitch:Tt})),O&&e.createElement(F.K,{direction:"column"},e.createElement(F.K,{direction:"row",gap:1,alignItems:"baseline"},e.createElement("div",{className:X.mutedText},"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."),e.createElement(we.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"})),e.createElement(pa,{queries:he,expressions:T,onRunQueries:P,onChangeQueries:Pe,onDuplicateQuery:Be,panelData:i,condition:D,onSetCondition:H}),e.createElement(De.u,{content:"You appear to have no compatible data sources",show:ae},e.createElement(R.zx,{type:"button",onClick:()=>{g(mt())},variant:"secondary","aria-label":$n.wl.components.QueryTab.addQuery,disabled:ae,className:X.addQueryButton},"Add query")),e.createElement(st,{editingExistingRule:t,rulesSourcesWithRuler:ne,queries:E,onClickSwitch:Tt}),e.createElement(_e.x,{element:"h5"},"Expressions"),e.createElement("div",{className:X.mutedText},"Manipulate data returned from queries with math and other operations."),e.createElement(jn,{queries:E,panelData:i,condition:D,onSetCondition:H,onRemoveExpression:v=>{g(ft(v))},onUpdateRefId:oe,onUpdateExpressionType:(v,x)=>{g(xt({refId:v,type:x}))},onUpdateQueryExpression:v=>{g(Et(v))}}),e.createElement(F.K,{direction:"row"},fe.config.expressionsEnabled&&e.createElement(Ga,{onClickType:J}),m&&e.createElement(R.zx,{icon:"fa fa-spinner",type:"button",variant:"destructive",onClick:f},"Cancel"),!m&&e.createElement(R.zx,{icon:"sync",type:"button",onClick:P,disabled:re},"Preview")),re&&e.createElement($.b,{title:"No queries or expressions have been configured",severity:"warning"},"Create at least one query or expression to be alerted on")))};function Ga({onClickType:t}){const a=e.createElement(Nn.v,null,ee.EJ.map(n=>e.createElement(De.u,{key:n.value,content:n.description??"",placement:"right"},e.createElement(bn.s,{key:n.value,onClick:()=>t(n.value??ee.Us.math),label:n.label??""}))));return e.createElement(Qn.L,{overlay:a},e.createElement(R.zx,{variant:"secondary"},"Add expression",e.createElement(_.J,{name:"angle-down"})))}const Wa=t=>({mutedText:(0,u.css)`
    color: ${t.colors.text.secondary};
    font-size: ${t.typography.size.sm};
    margin-top: ${t.spacing(-1)};
  `,addQueryButton:(0,u.css)`
    width: fit-content;
  `,helpInfo:(0,u.css)`
    display: flex;
    flex-direction: row;
    align-items: center;
    width: fit-content;
    font-weight: ${t.typography.fontWeightMedium};
    margin-left: ${t.spacing(1)};
    font-size: ${t.typography.size.sm};
    cursor: pointer;
  `,helpInfoText:(0,u.css)`
    margin-left: ${t.spacing(.5)};
    text-decoration: underline;
  `,infoLink:(0,u.css)`
    color: ${t.colors.text.link};
  `}),Oa=()=>{const{setValue:t}=(0,C.Gc)();return a=>{const n=a[0];if(!n)return;const r=(0,B.F)().getInstanceSettings(n.datasourceUid);if(!r)throw new Error("The Data source has not been defined.");if(t("dataSourceName",r.name),(0,N.tO)(n.model)){const s=n.model.expr;t("expression",s)}}},za={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_:]*$/},Va=()=>{const t=(0,S.wW)(Rt),{register:a,watch:n,formState:{errors:r}}=(0,C.Gc)(),s=n("type");return e.createElement(ve.z,{stepNo:1,title:"Set alert rule name."},e.createElement(V.g,{className:t.formInput,label:"Rule name",description:"Name for the alert rule.",error:r?.name?.message,invalid:!!r.name?.message},e.createElement(le.I,{id:"name",...a("name",{required:{value:!0,message:"Must enter an alert name"},pattern:s===p.$.cloudRecording?za:void 0}),placeholder:"Give your alert rule a name."})))},Oe=({existing:t,prefill:a})=>{const n=(0,S.wW)(Rt),r=(0,U.useDispatch)(),s=(0,bt.iG)(),[l]=(0,Qt.K)(),[c,i]=(0,e.useState)(!1),[d,f]=(0,e.useState)(t?.group.interval??N.EB),m=(0,j.UO)(),h=(0,M.KP)(m.type),y=m.id,E=l.returnTo??"/alerting/list",[g,w]=(0,e.useState)(!1),D=(0,e.useMemo)(()=>t?ja(t):a?Ka(a):typeof l.defaults=="string"?Ha(l.defaults,h):{...(0,N.uZ)(),condition:"C",queries:(0,N.s0)(),type:h||p.$.grafana,evaluateEvery:d},[t,a,l,d,h]),A=(0,C.cI)({mode:"onSubmit",defaultValues:D,shouldFocusError:!0}),{handleSubmit:O,watch:L}=A,Q=L("type"),Ee=L("dataSourceName"),ne=!!(Q&&(Q===p.$.grafana||Ee)),P=(0,Re._)(I=>I.ruleForm.saveRule)||Ce.oq;(0,Ze.x)(I=>I.unifiedAlerting.ruleForm.saveRule=Ce.oq);const[ae,he]=(0,e.useState)(""),T=(I="")=>{he(I)},re=(I,Be)=>{if(ae!==""){s.error(ae);return}r((0,q.wy)({values:{...D,...I,annotations:I.annotations?.map(({key:J,value:X})=>({key:J.trim(),value:X.trim()})).filter(({key:J,value:X})=>!!J&&!!X)??[],labels:I.labels?.map(({key:J,value:X})=>({key:J.trim(),value:X.trim()})).filter(({key:J})=>!!J)??[]},existing:t,redirectOnSave:Be?E:void 0,initialAlertRuleName:D.name,evaluateEvery:d}))},H=()=>{if(t){const I=Ie.Zk(t.ruleSourceName,t.namespace,t.group.name,t.rule);r((0,q.hS)(I,{navigateTo:"/alerting/list"}))}},oe=I=>{t||(0,Ye.Z0)({grafana_version:fe.config.buildInfo.version,org_id:ie.Vt.user.orgId,user_id:ie.Vt.user.id,error:Object.keys(I).toString()}),s.error("There are errors in the form. Please correct them and try again!")},Y=()=>{(0,ye.PN)(Ye.z7.cancelSavingAlertRule)},Pe=L("evaluateEvery");(0,e.useEffect)(()=>f(Pe),[Pe]);const Ve=e.createElement(xe.Lh,{height:"auto",justify:"flex-end"},e.createElement(R.zx,{variant:"primary",type:"button",size:"sm",onClick:O(I=>re(I,!1),oe),disabled:P.loading},P.loading&&e.createElement(Se.$,{className:n.buttonSpinner,inline:!0}),"Save rule"),e.createElement(R.zx,{variant:"primary",type:"button",size:"sm",onClick:O(I=>re(I,!0),oe),disabled:P.loading},P.loading&&e.createElement(Se.$,{className:n.buttonSpinner,inline:!0}),"Save rule and exit"),e.createElement(je.Link,{to:E},e.createElement(R.zx,{variant:"secondary",disabled:P.loading,type:"button",onClick:Y,size:"sm"},"Cancel")),t?e.createElement(R.zx,{fill:"outline",variant:"destructive",type:"button",onClick:()=>w(!0),size:"sm"},"Delete"):null,t?e.createElement(R.zx,{variant:"secondary",type:"button",onClick:()=>i(!0),disabled:P.loading,size:"sm"},Ba(L)?"Edit YAML":"View YAML"):null);return e.createElement(C.RV,{...A},e.createElement(Nt.A,{actions:Ve}),e.createElement("form",{onSubmit:I=>I.preventDefault(),className:n.form},e.createElement("div",{className:n.contentOuter},e.createElement(Qe.$,{autoHeightMin:"100%",hideHorizontalTrack:!0},e.createElement("div",{className:n.contentInner},e.createElement(Va,null),e.createElement(Ua,{editingExistingRule:!!t,onDataChange:T}),ne&&e.createElement(e.Fragment,null,Q===p.$.grafana?e.createElement(fn.w,{evaluateEvery:d,setEvaluateEvery:f,existing:!!t}):e.createElement(ln,null),e.createElement(mn,null),e.createElement(Dn,{alertUid:y})))))),g?e.createElement($t.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:H,onDismiss:()=>w(!1)}):null,c?Q===p.$.grafana?e.createElement(gn.i,{alertUid:y,onClose:()=>i(!1)}):e.createElement(Pn.CU,{onClose:()=>i(!1)}):null)},Ba=t=>{const[a,n]=t(["type","dataSourceName"]);return(a===p.$.cloudAlerting||a===p.$.cloudRecording)&&n!==""},ze=t=>({...t,queries:t.queries?.map(a=>(0,G.omit)(a,"model.hide"))});function Ha(t,a){let n;try{n=JSON.parse(t)}catch{return{...(0,N.uZ)(),queries:(0,N.s0)()}}return ze({...(0,N.uZ)(),...n,annotations:(0,N.TN)(n.annotations??[]),queries:n.queries??(0,N.s0)(),type:a||p.$.grafana,evaluateEvery:N.EB})}function Ka(t){return ze({...(0,N.uZ)(),...t})}function ja(t){return ze((0,N.DQ)(t))}const Rt=t=>({buttonSpinner:(0,u.css)`
      margin-right: ${t.spacing(1)};
    `,form:(0,u.css)`
      width: 100%;
      height: 100%;
      display: flex;
      flex-direction: column;
    `,contentInner:(0,u.css)`
      flex: 1;
      padding: ${t.spacing(2)};
    `,contentOuter:(0,u.css)`
      background: ${t.colors.background.primary};
      border: 1px solid ${t.colors.border.weak};
      border-radius: ${t.shape.borderRadius()};
      overflow: hidden;
      flex: 1;
      margin-top: ${t.spacing(1)};
    `,flexRow:(0,u.css)`
      display: flex;
      flex-direction: row;
      justify-content: flex-start;
    `,formInput:(0,u.css)`
      width: 275px;

      & + & {
        margin-left: ${t.spacing(3)};
      }
    `});var Za=o(42481),de=o(22446),Ya=o(59597);function Ja({sourceRuleId:t}){const a=(0,U.useDispatch)(),{loading:n,value:r,error:s}=(0,K.Z)(()=>a((0,q.on)(t)).unwrap(),[t]);if(n)return e.createElement(pe.u,{text:"Loading the rule"});if(r){const l=ka(r),c=(0,N.DQ)(l);return e.createElement(Oe,{prefill:c})}return s?e.createElement($.b,{title:"Error",severity:"error"},s.message):e.createElement($.b,{title:"Cannot copy the rule. The rule does not exist",buttonContent:"Go back to alert list",onRemove:()=>be.E1.replace((0,Ya.u)("/alerting/list"))})}function Xa(t,a){(0,de.Pc)(t)&&(t.grafana_alert.title=a),(0,de.cG)(t)&&(t.alert=a),(0,de.yF)(t)&&(t.record=a)}function ka(t){const a=(0,G.cloneDeep)(t);return Xa(a.rule,(0,Za.G)((0,de.PW)(a.rule),a.group.rules.map(de.PW))),(0,de.Pc)(a.rule)&&(a.rule.grafana_alert.uid="",a.rule.grafana_alert.provenance&&(a.group={name:"",rules:a.group.rules})),a}var qa=o(99322);function _a({identifier:t,id:a}){(0,Ze.x)(m=>m.unifiedAlerting.ruleForm.existingRule=Ce.oq);const{loading:n,result:r,error:s,dispatched:l}=(0,Re._)(m=>m.ruleForm.existingRule),c=(0,U.useDispatch)(),{isEditable:i,loading:d}=(0,qa.M)(Ie.s0(t),r?.rule),f=n||d;return(0,e.useEffect)(()=>{l||c((0,q.on)(t))},[l,c,t]),f||i===void 0?e.createElement(pe.u,{text:"Loading rule..."}):s?e.createElement($.b,{severity:"error",title:"Failed to load rule"},s.message):r?i===!1?e.createElement(k,{title:"Cannot edit rule"},"Sorry! You do not have permission to edit this rule."):e.createElement(Oe,{existing:r}):e.createElement(k,{title:"Rule not found"},"Sorry! This rule does not exist.")}var er=o(81324),tr=o(79003),nr=o(13963);const Ct={icon:"bell",id:"alert-rule-view"},ar=t=>{if(t==="edit")return{...Ct,id:"alert-rule-edit",text:"Edit rule"};if(t==="add")return{...Ct,id:"alert-rule-add",text:"Add rule"}},rr=({match:t})=>{const a=(0,U.useDispatch)(),[n]=(0,tr.j)(),{id:r}=t.params,s=Ie.OA(r,!0),l=n.get("copyFrom")??void 0,c=Ie.OA(l),{loading:i=!0}=(0,K.Z)(async()=>{s&&await a((0,q.nw)({rulesSourceName:s.ruleSourceName}))},[a]),{canCreateGrafanaRules:d,canCreateCloudRules:f,canEditRules:m}=(0,nr.B)(),h=(0,e.useCallback)(()=>{if(!i)return!s&&!d&&!f?e.createElement(k,{title:"Cannot create rules"},"Sorry! You are not allowed to create rules."):s&&!m(s.ruleSourceName)?e.createElement(k,{title:"Cannot edit rules"},"Sorry! You are not allowed to edit rules."):s?e.createElement(_a,{key:r,identifier:s,id:r}):c?e.createElement(Ja,{sourceRuleId:c}):e.createElement(Oe,null)},[f,d,m,c,r,s,i]);return e.createElement(er.J,{isLoading:i,pageId:"alert-list",pageNav:ar(s?"edit":"add")},h())},or=(0,me.Pf)(rr,{style:"page"})},94752:(Ke,se,o)=>{o.d(se,{S:()=>$});var e=o(89949),K=o.n(e),me=o(18771),U=o(52646),u=o(22513);function $(){const{useGetExternalAlertmanagersQuery:R}=U.alertmanagerApi,{currentData:k}=R(),Ne=(0,u.aM)().filter(C=>C.jsonData.handleGrafanaManagedAlerts),G=(0,me.useSelector)(C=>(0,e.keyBy)(C.dataSources.dataSources.filter(j=>j.type==="alertmanager"),j=>j.uid)),be=(0,e.countBy)(k?.droppedAlertManagers,C=>C.url),pe=(0,e.countBy)(k?.activeAlertManagers,C=>C.url);return Ne.map(C=>{const j=G[C.uid];if(!j)return{dataSource:C,status:"pending"};const fe=`${S(j)}/api/v2/alerts`,ye=be[fe]??0,V=pe[fe]??0,le=ye>0,xe=V>0,Se=ye+V>1,Qe=le?"dropped":xe?"active":"pending";return{dataSource:C,url:j.url,status:Qe,statusInconclusive:Se}})}function S(R){return new RegExp("^[^:]*://").test(R.url)?R.url:`http://${R.url}`}},86954:(Ke,se,o)=>{o.d(se,{K:()=>U});var e=o(42844),K=o(27702),me=o(66310);function U($){const S=(0,me.wW)((0,K.useCallback)(R=>u(R,$),[$]));return K.createElement("div",{className:S.root},$.children)}const u=($,S)=>({root:(0,e.css)({display:"flex",flexDirection:S.direction??"row",flexWrap:S.wrap??!0?"wrap":void 0,alignItems:S.alignItems,gap:$.spacing(S.gap??2),flexGrow:S.flexGrow})})}}]);

//# sourceMappingURL=AlertingRuleForm.18f1776ae483b5fc7bdc.js.map