D7net
Home
Console
Upload
information
Create File
Create Folder
About
Tools
:
/
usr
/
share
/
grafana
/
public
/
build
/
Filename :
1518.faa2d2f9ab7416f28bc6.js
back
Copy
"use strict";(self.webpackChunkgrafana=self.webpackChunkgrafana||[]).push([[1518],{75429:(Y,U,i)=>{i.d(U,{x:()=>M});var e=i(27702),b=i(18771),C=i(92071);function M(S){const N=(0,b.useDispatch)(),E=(0,e.useRef)(S);E.current=S,(0,e.useEffect)(()=>()=>{N((0,C.e)({cleanupAction:E.current}))},[N])}},98164:(Y,U,i)=>{i.d(U,{V:()=>S});var e=i(33555),b=i(16881),C=i(8014);const M=b.C.injectEndpoints({endpoints:N=>({contactPointsState:N.query({queryFn:async({amSourceName:E})=>{try{return{data:await(0,C.QE)(E)}}catch(V){return{error:V}}}})})}),S=N=>{const E={receivers:{},errorCount:0},{currentData:V}=M.useContactPointsStateQuery({amSourceName:N??""},{skip:!N,pollingInterval:e.m4});return V??E}},89439:(Y,U,i)=>{i.d(U,{q:()=>C});var e=i(27702),b=i(91368);const C=({actions:M,children:S,fallback:N=!0})=>M.some(E=>b.contextSrv.hasAccess(E,N))?e.createElement(e.Fragment,null,S):null},80118:(Y,U,i)=>{i.d(U,{u:()=>V});var e=i(42844),b=i(27702),C=i(66310),M=i(63439),S=i(62862),N=i(52646),E=i(22513);function V({currentAlertmanager:P}){const _=(0,C.wW)(D),{useGetAlertmanagerChoiceStatusQuery:te}=N.alertmanagerApi,{currentData:k}=te(),G=P===E.GC;if(!(k?.alertmanagersChoice&&[S.TE.External,S.TE.All].includes(k?.alertmanagersChoice))||!G)return null;const u=k.numExternalAlertmanagers>0;return k.alertmanagersChoice===S.TE.External?b.createElement(M.b,{title:"Grafana alerts are not delivered to Grafana Alertmanager"},"Grafana is configured to send alerts to external Alertmanagers only. Changing Grafana Alertmanager configuration will not affect delivery of your alerts.",b.createElement("div",{className:_.adminHint},"To change your Alertmanager setup, go to the Alerting Admin page. If you do not have access, contact your Administrator.")):k.alertmanagersChoice===S.TE.All&&u?b.createElement(M.b,{title:"You have additional Alertmanagers to configure",severity:"warning"},"Ensure you make configuration changes in the correct Alertmanagers; both internal and external. Changing one will not affect the others.",b.createElement("div",{className:_.adminHint},"To change your Alertmanager setup, go to the Alerting Admin page. If you do not have access, contact your Administrator.")):null}const D=P=>({adminHint:(0,e.css)` font-size: ${P.typography.bodySmall.fontSize}; font-weight: ${P.typography.bodySmall.fontWeight}; `})},18629:(Y,U,i)=>{i.d(U,{C0:()=>N,Uv:()=>M,Xq:()=>S});var e=i(27702),b=i(63439),C=i(25357),M=(E=>(E.ContactPoint="contact point",E.Template="template",E.MuteTiming="mute timing",E.AlertRule="alert rule",E.RootNotificationPolicy="root notification policy",E))(M||{});const S=({resource:E})=>e.createElement(b.b,{title:`This ${E} cannot be edited through the UI`,severity:"info"},"This ",E," has been provisioned, that means it was created by config. Please contact your server admin to update this ",E,"."),N=()=>e.createElement(C.C,{text:"Provisioned",color:"purple"})},17978:(Y,U,i)=>{i.r(U),i.d(U,{default:()=>ar});var e=i(27702),b=i(7662),C=i(63439),M=i(52419),S=i(18771),N=i(97529),E=i(10027),V=i(1469),D=i(47702),P=i(22513),_=i(80118),te=i(42481),k=i(89949);function G(t,n){let a=n.trim();if(!a.match(/\{\{\s*define/)){const r=a.split(` `).map(s=>" "+s).join(` `);a=`{{ define "${t}" }} ${r} {{ end }}`}return a}function J(t){const n=(a,r)=>`{{ define "${r}_NEW_${(0,k.now)()}" }}`;return t.replace(/\{\{\s*define\s*\"(?<defineName>.*)\"\s*\}\}/g,n)}var u=i(42844),ne=i(84925),Te=i(55434),xt=i(48335);function Me(t,n){(0,Te.Z)(2,arguments);var a=(0,xt.Z)(n);return(0,ne.Z)(t,-a)}var K=i(46089),ye=i(55925),oe=i(23852),B=i(66310),Rt=i(5229),le=i(22209),me=i(1128),wt=i(15372),ke=i(54281),w=i(66670),Pt=i(62499),Nt=i(62108),xe=i(75429),Ot=i(16881);const It="/api/alertmanager/grafana/config/api/v1/templates/test",Dt=Ot.C.injectEndpoints({endpoints:t=>({previewTemplate:t.mutation({query:({template:n,alerts:a,name:r})=>({url:It,data:{template:n,alerts:a,name:r},method:"POST"})})})}),{usePreviewTemplateMutation:Lt}=Dt;var Z=i(39036),Re=i(84369),ue=i(18629),We=i(80011),ve=i(73453),Ue=i(11649),ge=i(25357),Fe=i(25472),$t=i(65333),ie=i(13741),Mt=i(33716),kt=i(52646),fe=i(77328),Ve=i(57117);function Wt({onSelect:t,isOpen:n,onClose:a}){const r=(0,B.wW)(Ut),[s,c]=(0,e.useState)(),[l,d]=(0,e.useState)(null),{useGetAlertmanagerAlertsQuery:g}=kt.alertmanagerApi,{currentData:m=[],isFetching:p,isError:f}=g({amSourceName:P.GC,filter:{inhibited:!0,silenced:!0,active:!0}}),[h,y]=(0,e.useState)(""),T=(0,e.useMemo)(()=>{const I={};return!p&&m&&m.forEach(x=>{I[x.labels.alertname]||(I[x.labels.alertname]=[]),I[x.labels.alertname].push(x)}),I},[p,m]),R=(0,e.useCallback)(I=>{c(I),d(null)},[]),L=(0,e.useMemo)(()=>{const I=Object.keys(T).filter(v=>v.toLowerCase().includes(h.toLowerCase())),x={};return I.forEach(v=>{x[v]=T[v]}),x},[T,h]);if(f)return null;const A=Object.keys(L||[]),O=({index:I,style:x})=>{if(!L)return null;const v=A[I],$=v===s;return e.createElement("button",{type:"button",title:v,style:x,className:(0,u.cx)(r.rowButton,{[r.rowOdd]:I%2===1,[r.rowSelected]:$}),onClick:()=>R(v)},e.createElement("div",{className:(0,u.cx)(r.ruleTitle,r.rowButtonTitle)},v),e.createElement("div",{className:r.alertFolder},e.createElement(e.Fragment,null,e.createElement(ve.J,{name:"folder"})," ",L[v][0].labels.grafana_folder??"")))},H=(I,x)=>{const $=I.map(se=>se.labels).map(fe.cH),Q=(0,Ve.z)($),W=(0,Ve.r)((0,fe.cH)(x.labels),Q);return W.length?(0,fe.P3)((0,fe.nW)(W)):(0,fe.P3)(x.labels)},F=({index:I,style:x})=>{const v=(0,e.useMemo)(()=>s?T[s]:[],[]),$=v[I],Q=l?.includes($),W=(0,e.useMemo)(()=>H(v,$),[v,$]),z=()=>{if(Q&&l){d(l.filter(se=>se!==$));return}d([...l||[],$])};return e.createElement("button",{type:"button",style:x,className:(0,u.cx)(r.rowButton,r.instanceButton,{[r.rowOdd]:I%2===1,[r.rowSelected]:Q}),onClick:z},e.createElement("div",{className:r.rowButtonTitle,title:$.labels.alertname},e.createElement(We.u,{placement:"bottom",content:e.createElement("pre",null,JSON.stringify($,null,2)),theme:"info"},e.createElement("div",null,W.map((se,$e)=>e.createElement($t.V,{key:$e,name:se,className:r.tag}))))))},j=()=>{const I=l?.map(x=>({annotations:x.annotations,labels:x.labels,startsAt:x.startsAt,endsAt:x.endsAt}))||[];t(I),q()},q=()=>{c(void 0),d(null),y(""),de("")},re=()=>{q(),a()},de=I=>{y(I)};return e.createElement("div",null,e.createElement(ie.u,{title:"Select alert instances",className:r.modal,closeOnEscape:!0,isOpen:n,onDismiss:re,contentClassName:r.modalContent},e.createElement("div",{className:r.container},e.createElement(Mt.H,{value:h,onChange:de,title:"Search alert rule",placeholder:"Search alert rule",autoFocus:!0}),e.createElement("div",null,s&&"Select one or more instances from the list below"||""),e.createElement("div",{className:r.column},p&&e.createElement(M.u,{text:"Loading rules...",className:r.loadingPlaceholder}),!p&&e.createElement(ye.Z,null,({height:I,width:x})=>e.createElement(Fe.t7,{itemSize:50,height:I,width:x,itemCount:A.length},O))),e.createElement("div",{className:r.column},!s&&!p&&e.createElement("div",{className:r.selectedRulePlaceholder},e.createElement("div",null,"Select an alert rule to get a list of available instances")),p&&e.createElement(M.u,{text:"Loading rule...",className:r.loadingPlaceholder}),s&&T[s].length&&!p&&e.createElement(ye.Z,null,({width:I,height:x})=>e.createElement(Fe.t7,{itemSize:32,height:x,width:I,itemCount:T[s].length||0},F)))),e.createElement(ie.u.ButtonRow,null,e.createElement(w.zx,{type:"button",variant:"secondary",onClick:re},"Cancel"),e.createElement(w.zx,{type:"button",variant:"primary",disabled:!(s&&l),onClick:()=>{s&&l&&j()}},"Add alert data to payload"))))}const Ut=t=>{const n=(0,w.gN)(t);return{container:(0,u.css)` display: grid; grid-template-columns: 1fr 1.5fr; grid-template-rows: min-content auto; gap: ${t.spacing(2)}; flex: 1; `,tag:(0,u.css)` margin: 5px; `,column:(0,u.css)` flex: 1 1 auto; `,alertLabels:(0,u.css)` overflow-x: auto; height: 32px; `,ruleTitle:(0,u.css)` height: 22px; font-weight: ${t.typography.fontWeightBold}; `,rowButton:(0,u.css)` ${n}; padding: ${t.spacing(.5)}; overflow: hidden; text-overflow: ellipsis; text-align: left; white-space: nowrap; cursor: pointer; border: 2px solid transparent; &:disabled { cursor: not-allowed; color: ${t.colors.text.disabled}; } `,rowButtonTitle:(0,u.css)` overflow-x: auto; `,rowSelected:(0,u.css)` border-color: ${t.colors.primary.border}; `,rowOdd:(0,u.css)` background-color: ${t.colors.background.secondary}; `,instanceButton:(0,u.css)` display: flex; gap: ${t.spacing(1)}; justify-content: space-between; align-items: center; `,loadingPlaceholder:(0,u.css)` height: 100%; display: flex; justify-content: center; align-items: center; `,selectedRulePlaceholder:(0,u.css)` width: 100%; height: 100%; display: flex; flex-direction: column; justify-content: center; text-align: center; font-weight: ${t.typography.fontWeightBold}; `,modal:(0,u.css)` height: 100%; `,modalContent:(0,u.css)` flex: 1; display: flex; flex-direction: column; `,modalAlert:(0,u.css)` flex-grow: 0; `,warnIcon:(0,u.css)` fill: ${t.colors.warning.main}; `,labels:(0,u.css)` justify-content: flex-start; `,alertFolder:(0,u.css)` height: 20px; font-size: ${t.typography.bodySmall.fontSize}; color: ${t.colors.text.secondary}; display: flex; flex-direction: row; justify-content: flex-start; column-gap: ${t.spacing(1)}; align-items: center; `}},Ft=[{name:"Receiver",type:"string",notes:"Name of the contact point that the notification is being sent to."},{name:"Status",type:"string",notes:"firing if at least one alert is firing, otherwise resolved"},{name:"Alerts",type:"[]Alert",notes:"List of alert objects that are included in this notification."},{name:"Alerts.Firing",type:"[]Alert",notes:"List of firing alerts"},{name:"Alerts.Resolved",type:"[]Alert",notes:"List of resolved alerts"},{name:"GroupLabels",type:"KeyValue",notes:"Labels these alerts were grouped by."},{name:"CommonLabels",type:"KeyValue",notes:"Labels common to all the alerts included in this notification."},{name:"CommonAnnotations",type:"KeyValue",notes:"Annotations common to all the alerts included in this notification."},{name:"ExternalURL",type:"string",notes:"Back link to the Grafana that sent the notification."}],Vt=[{name:"Labels",type:"KeyValue",notes:"Set of labels attached to the alert."},{name:"Annotations",type:"KeyValue",notes:"Set of annotations attached to the alert."},{name:"StartsAt",type:"time.Time",notes:"Time the alert started firing."},{name:"EndsAt",type:"time.Time",notes:"Time the alert ends firing."}],Bt=[{name:"Status",type:"string",notes:"firing or resolved."},{name:"Labels",type:"KeyValue",notes:"Set of labels attached to the alert."},{name:"Annotations",type:"KeyValue",notes:"Set of annotations attached to the alert."},{name:"Values",type:"KeyValue",notes:"The values of all instant queries, reduce and math expressions, and classic conditions for the alert. It does not contain time series data."},{name:"StartsAt",type:"time.Time",notes:"Time the alert started firing."},{name:"EndsAt",type:"time.Time",notes:"Only set if the end time of an alert is known. Otherwise set to a configurable timeout period from the time since the last alert was received."},{name:"GeneratorURL",type:"string",notes:"A back link to Grafana or external Alertmanager."},{name:"SilenceURL",type:"string",notes:"Link to Grafana silence for with labels for this alert pre-filled. Only for Grafana managed alerts."},{name:"DashboardURL",type:"string",notes:"Link to Grafana dashboard, if alert rule belongs to one. Only for Grafana managed alerts."},{name:"PanelURL",type:"string",notes:"Link to Grafana dashboard panel, if alert rule belongs to one. Only for Grafana managed alerts."},{name:"Fingerprint",type:"string",notes:"Fingerprint that can be used to identify the alert."},{name:"ValueString",type:"string",notes:"String that contains the labels and value of each reduced expression in the alert."}],Gt=[{name:"SortedPairs",returns:"KeyValue",notes:"Returns sorted list of key & value string pairs"},{name:"Remove",args:"[]string",returns:"KeyValue",notes:"Returns a copy of the Key/Value map without the given keys."},{name:"Names",returns:"[]string",notes:"List of label names"},{name:"Values",returns:"[]string",notes:"List of label values"}],zt=`{ "summary": "alert summary", "description": "alert description" } `;var Be=i(51453);function Kt(){const t=(0,B.wW)(_t),n=e.createElement(we,{caption:e.createElement("h4",{className:t.header},"Alert template data ",e.createElement("span",null,"Available only when in the context of an Alert (e.g. inside .Alerts loop)")),dataItems:Bt});return e.createElement(oe.K,{gap:2,flexGrow:1},e.createElement(we,{caption:e.createElement("h4",{className:t.header},"Template Data"),dataItems:Ft,typeRenderer:a=>a==="[]Alert"?e.createElement(Be.z,{content:n},e.createElement("div",{className:t.interactiveType},a)):a==="KeyValue"?e.createElement(Be.z,{content:e.createElement(jt,null)},e.createElement("div",{className:t.interactiveType},a)):a}))}const _t=t=>({header:(0,u.css)` color: ${t.colors.text.primary}; span { color: ${t.colors.text.secondary}; font-size: ${t.typography.bodySmall.fontSize}; } `,interactiveType:(0,u.css)` color: ${t.colors.text.link}; `});function we({dataItems:t,caption:n,typeRenderer:a}){const r=(0,B.wW)(Ge);return e.createElement("table",{className:r.table},e.createElement("caption",null,n),e.createElement("thead",null,e.createElement("tr",null,e.createElement("th",null,"Name"),e.createElement("th",null,"Type"),e.createElement("th",null,"Notes"))),e.createElement("tbody",null,t.map(({name:s,type:c,notes:l},d)=>e.createElement("tr",{key:d},e.createElement("td",null,s),e.createElement("td",null,a?a(c):c),e.createElement("td",null,l)))))}function jt(){const t=(0,B.wW)(Ge);return e.createElement("div",null,"KeyValue is a set of key/value string pairs that represent labels and annotations.",e.createElement("pre",null,e.createElement("code",null,zt)),e.createElement("table",{className:t.table},e.createElement("caption",null,"Key-value methods"),e.createElement("thead",null,e.createElement("tr",null,e.createElement("th",null,"Name"),e.createElement("th",null,"Arguments"),e.createElement("th",null,"Returns"),e.createElement("th",null,"Notes"))),e.createElement("tbody",null,Gt.map(({name:n,args:a,returns:r,notes:s})=>e.createElement("tr",{key:n},e.createElement("td",null,n),e.createElement("td",null,a),e.createElement("td",null,r),e.createElement("td",null,s))))))}const Ge=t=>({table:(0,u.css)` border-collapse: collapse; width: 100%; caption { caption-side: top; } td, th { padding: ${t.spacing(1,1)}; } thead { font-weight: ${t.typography.fontWeightBold}; } tbody tr:nth-child(2n + 1) { background-color: ${t.colors.background.secondary}; } tbody td:nth-child(1) { font-weight: ${t.typography.fontWeightBold}; } tbody td:nth-child(2) { font-style: italic; } `});var Ht=i(50230),ze=i(40705),Ke=i(60871),_e=i(50115);const Jt={annotations:[{key:"",value:""}],labels:[{key:"",value:""}],status:"firing"},Qt=({isOpen:t,onDismiss:n,onAccept:a})=>{const r=(0,B.wW)(Yt),[s,c]=(0,e.useState)([]),l=(0,K.cI)({defaultValues:Jt,mode:"onBlur"}),d=l.watch("annotations"),g=l.watch("labels"),[m,p]=(0,e.useState)("firing"),f=()=>{const R={annotations:d.filter(({key:L,value:A})=>!!L&&!!A).reduce((L,{key:A,value:O})=>({...L,[A]:O}),{}),labels:g.filter(({key:L,value:A})=>!!L&&!!A).reduce((L,{key:A,value:O})=>({...L,[A]:O}),{}),startsAt:"2023-04-01T00:00:00Z",endsAt:m==="firing"?(0,ne.Z)(new Date,1).toISOString():Me(new Date,1).toISOString()};c(L=>[...L,R]),l.reset()},h=()=>{a(s),c([]),l.reset(),p("firing")},y=()=>{const R=g.some(A=>A.key!==""&&A.value!==""),L=d.some(A=>A.key!==""&&A.value!=="");return R||L},T=[{label:"Firing",value:"firing"},{label:"Resolved",value:"resolved"}];return e.createElement(ie.u,{onDismiss:n,isOpen:t,title:"Add custom alerts"},e.createElement(K.RV,{...l},e.createElement("form",{onSubmit:R=>{R.preventDefault(),R.stopPropagation(),l.reset(),p("firing")}},e.createElement(e.Fragment,null,e.createElement(Ht.Z,null,e.createElement(oe.K,{direction:"column",gap:1},e.createElement("div",{className:r.section},e.createElement(Ke.Z,null)),e.createElement("div",{className:r.section},e.createElement(_e.Z,null)),e.createElement("div",{className:r.flexWrapper},e.createElement(ze.S,{value:m,options:T,onChange:R=>p(R)}),e.createElement(w.zx,{onClick:f,className:r.onAddButton,icon:"plus-circle",type:"button",variant:"secondary",disabled:!y()},"Add alert data"))))),e.createElement("div",{className:r.onSubmitWrapper}),s.length>0&&e.createElement(oe.K,{direction:"column",gap:1},e.createElement("h5",null," Review alert data to add to the payload:"),e.createElement("pre",{className:r.result,"data-testid":"payloadJSON"},JSON.stringify(s,null,2))),e.createElement("div",{className:r.onSubmitWrapper},e.createElement(ie.u.ButtonRow,null,e.createElement(w.zx,{onClick:h,disabled:s.length===0,className:r.onSubmitButton},"Add alert data to payload"))))))},Yt=t=>({section:(0,u.css)` margin-bottom: ${t.spacing(2)}; `,onAddButton:(0,u.css)` flex: none; width: fit-content; padding-right: ${t.spacing(1)}; margin-left: auto; `,flexWrapper:(0,u.css)` display: flex; flex-direction: row, justify-content: space-between; `,onSubmitWrapper:(0,u.css)` display: flex; flex-direction: row; align-items: baseline; justify-content: flex-end; `,onSubmitButton:(0,u.css)` margin-left: ${t.spacing(2)}; `,result:(0,u.css)` width: 570px; height: 363px; `}),Zt="Reset to default";function Xt({payload:t,setPayload:n,defaultPayload:a,setPayloadFormatError:r,payloadFormatError:s,onPayloadError:c}){const l=(0,B.wW)(je),d=()=>{n(a)},[g,m]=(0,e.useState)(!1),p=()=>{m(!1)},f=s!==null,h=()=>{try{const O=JSON.parse(t);JSON.stringify([...O]),r(null)}catch(O){throw r(O instanceof Error?O.message:"Invalid JSON."),c(),O}},y=()=>{try{h(),m(!0)}catch{}},T=()=>{try{h(),A(!0)}catch{}},R=O=>{p(),A(!1),n(H=>{const F=JSON.parse(H);return JSON.stringify([...F,...O],void 0,2)})},[L,A]=(0,e.useState)(!1);return e.createElement("div",{className:l.wrapper},e.createElement("div",{className:l.editor},e.createElement("div",{className:l.title},"Payload data",e.createElement(We.u,{placement:"top",content:e.createElement(qt,null),theme:"info"},e.createElement(ve.J,{name:"info-circle",className:l.tooltip,size:"xl"}))),e.createElement(ye.Z,{disableHeight:!0},({width:O})=>e.createElement("div",{className:l.editorWrapper},e.createElement(Ue.p,{width:O,height:362,language:"json",showLineNumbers:!0,showMiniMap:!1,value:t,readOnly:!1,onBlur:n}))),e.createElement("div",{className:l.buttonsWrapper},e.createElement(w.zx,{type:"button",variant:"secondary",className:l.button,icon:"bell",disabled:f,onClick:T},"Select alert instances"),e.createElement(w.zx,{onClick:y,className:l.button,icon:"plus-circle",type:"button",variant:"secondary",disabled:f},"Add custom alerts"),e.createElement(w.zx,{onClick:d,className:l.button,icon:"arrow-up",type:"button",variant:"destructive"},Zt),s!==null&&e.createElement(ge.C,{color:"orange",icon:"exclamation-triangle",text:"JSON Error",tooltip:"Fix errors in payload, and click Refresh preview button"}))),e.createElement(Qt,{isOpen:g,onDismiss:p,onAccept:R}),e.createElement(Wt,{onSelect:R,isOpen:L,onClose:()=>A(!1)}))}const qt=()=>{const t=(0,B.wW)(je);return e.createElement(we,{caption:e.createElement("h4",{className:t.templateDataDocsHeader},"Alert template data ",e.createElement("span",null,"This is the list of alert data fields used in the preview.")),dataItems:Vt})},je=t=>({jsonEditor:(0,u.css)` width: 100%; height: 100%; `,buttonsWrapper:(0,u.css)` margin-top: ${t.spacing(1)}; display: flex; flex-wrap: wrap; `,button:(0,u.css)` flex: none; width: fit-content; padding-right: ${t.spacing(1)}; margin-right: ${t.spacing(1)}; margin-bottom: ${t.spacing(1)}; `,title:(0,u.css)` font-weight: ${t.typography.fontWeightBold}; heigth: 41px; padding-top: 10px; padding-left: ${t.spacing(2)}; margin-top: 19px; `,wrapper:(0,u.css)` flex: 1; min-width: 450px; `,tooltip:(0,u.css)` padding-left: ${t.spacing(1)}; `,editorWrapper:(0,u.css)` width: min-content; padding-top: 7px; `,editor:(0,u.css)` display: flex; flex-direction: column; margin-top: ${t.spacing(-1)}; `,templateDataDocsHeader:(0,u.css)` color: ${t.colors.text.primary}; span { color: ${t.colors.text.secondary}; font-size: ${t.typography.bodySmall.fontSize}; } `});var ce=i(21475);function en(t){const n=t.languages.CompletionItemKind.Function;return[{label:ce.AlertmanagerTemplateFunction.toUpper,detail:"function(s string)",kind:n},{label:ce.AlertmanagerTemplateFunction.toLower,detail:"function(s string)",kind:n},{label:ce.AlertmanagerTemplateFunction.title,documentation:"Capitalizes the first letter of each word",detail:"function(s string)",kind:n},{label:ce.AlertmanagerTemplateFunction.join,documentation:{value:"Joins an array of strings using the separator provided."},detail:"function(separator string, s []string)",kind:n},{label:ce.AlertmanagerTemplateFunction.match,detail:"function",kind:n},{label:ce.AlertmanagerTemplateFunction.safeHtml,detail:"function(pattern, repl, text)",kind:n},{label:ce.AlertmanagerTemplateFunction.reReplaceAll,detail:"function(pattern, repl, text)",kind:n},{label:ce.AlertmanagerTemplateFunction.stringSlice,detail:"function(s ...string)",kind:n}]}const tn=` {{ range .Alerts }} Status: {{ .Status }} Starts at: {{ .StartsAt }} {{ end }} `,nn=` [{{.Status}}] {{ .Labels.alertname }} Labels: {{ range .Labels.SortedPairs }} {{ .Name }}: {{ .Value }} {{ end }} {{ if gt (len .Annotations) 0 }} Annotations: {{ range .Annotations.SortedPairs }} {{ .Name }}: {{ .Value }} {{ end }} {{ end }} {{ if gt (len .SilenceURL ) 0 }} Silence alert: {{ .SilenceURL }} {{ end }} {{ if gt (len .DashboardURL ) 0 }} Go to dashboard: {{ .DashboardURL }} {{ end }} `,an=he("GroupLabels.SortedPairs"),rn=he("CommonLabels.SortedPairs"),sn=he("CommonAnnotations.SortedPairs"),on=he("Labels.SortedPairs"),ln=he("Annotations.SortedPairs");function he(t){return` {{ range .${t} }} {{ .Name }} = {{ .Value }} {{ end }}`}function cn(t){const n=t.languages.CompletionItemKind.Field;return[{label:"Alerts",kind:n,detail:"Alert[]",documentation:{value:"An Array containing all alerts"}},{label:"Receiver",kind:n,detail:"string"},{label:"Status",kind:n,detail:"string"},{label:"GroupLabels",kind:n,detail:"[]KeyValue"},{label:"CommonLabels",kind:n,detail:"[]KeyValue"},{label:"CommonAnnotations",kind:n,detail:"[]KeyValue"},{label:"ExternalURL",kind:n,detail:"string"}]}function dn(t){const n=t.languages.CompletionItemKind.Field;return[{label:{label:"Status",detail:"(Alert)",description:"string"},kind:n,detail:"string",documentation:{value:"Status of the alert. It can be `firing` or `resolved`"}},{label:{label:"Labels",detail:"(Alert)"},kind:n,detail:"[]KeyValue",documentation:{value:"A set of labels attached to the alert."}},{label:{label:"Annotations",detail:"(Alert)"},kind:n,detail:"[]KeyValue",documentation:"A set of annotations attached to the alert."},{label:{label:"StartsAt",detail:"(Alert)"},kind:n,detail:"time.Time",documentation:"Time the alert started firing."},{label:{label:"EndsAt",detail:"(Alert)"},kind:n,detail:"time.Time",documentation:"Only set if the end time of an alert is known. Otherwise set to a configurable timeout period from the time since the last alert was received."},{label:{label:"GeneratorURL",detail:"(Alert)"},kind:n,detail:"string",documentation:"Back link to Grafana or external Alertmanager."},{label:{label:"SilenceURL",detail:"(Alert)"},kind:n,detail:"string",documentation:"Link to Grafana silence for with labels for this alert pre-filled. Only for Grafana managed alerts."},{label:{label:"DashboardURL",detail:"(Alert)"},kind:n,detail:"string",documentation:"Link to Grafana dashboard, if alert rule belongs to one. Only for Grafana managed alerts."},{label:{label:"PanelURL",detail:"(Alert)"},kind:n,detail:"string",documentation:"Link to Grafana dashboard panel, if alert rule belongs to one. Only for Grafana managed alerts."},{label:{label:"Fingerprint",detail:"(Alert)"},kind:n,detail:"string",documentation:"Fingerprint that can be used to identify the alert."},{label:{label:"ValueString",detail:"(Alert)"},kind:n,detail:"string",documentation:"String that contains labels and values of each reduced expression in the alert."}]}function mn(t){const n=t.languages.CompletionItemKind.Field;return[{label:"Firing",kind:n,detail:"Alert[]"},{label:"Resolved",kind:n,detail:"Alert[]"}]}function un(t){const n=t.languages.CompletionItemKind.Field;return[{label:"SortedPairs",kind:n,detail:"[]KeyValue"},{label:"Names",kind:n,detail:"[]string"},{label:"Values",kind:n,detail:"[]string"},{label:"Remove",detail:"KeyValue[] function(keys []string)",kind:t.languages.CompletionItemKind.Method}]}const He={alerts:{label:"alertsloop",description:"Renders a loop through alerts",snippet:tn},alertDetails:{label:"alertdetails",description:"Renders all information available about the alert",snippet:nn},groupLabels:{label:"grouplabelsloop",description:"Renders a loop through group labels",snippet:an},commonLabels:{label:"commonlabelsloop",description:"Renders a loop through common labels",snippet:rn},commonAnnotations:{label:"commonannotationsloop",description:"Renders a loop through common annotations",snippet:sn},labels:{label:"labelsloop",description:"Renders a loop through labels",snippet:on},annotations:{label:"annotationsloop",description:"Renders a loop through annotations",snippet:ln}};function pn(t){const n=t.languages.CompletionItemKind.Snippet,a=t.languages.CompletionItemInsertTextRule.InsertAsSnippet,{alerts:r,alertDetails:s,groupLabels:c,commonLabels:l,commonAnnotations:d,labels:g,annotations:m}=He;return[{label:r.label,documentation:r.description,kind:n,insertText:r.snippet,insertTextRules:a},{label:{label:s.label,detail:"(Alert)"},documentation:s.description,kind:n,insertText:s.snippet,insertTextRules:a},{label:c.label,documentation:c.description,kind:n,insertText:c.snippet,insertTextRules:a},{label:l.label,documentation:l.description,kind:n,insertText:l.snippet,insertTextRules:a},{label:d.label,documentation:d.description,kind:n,insertText:d.snippet,insertTextRules:a},{label:{label:g.label,detail:"(Alert)"},documentation:g.description,kind:n,insertText:g.snippet,insertTextRules:a},{label:{label:m.label,detail:"(Alert)"},documentation:m.description,kind:n,insertText:m.snippet,insertTextRules:a}]}function gn(t){const n={triggerCharacters:["."],provideCompletionItems(a,r,s){const c=a.getWordUntilPosition(r),l={startLineNumber:r.lineNumber,endLineNumber:r.lineNumber,startColumn:c.startColumn,endColumn:c.endColumn},d=new hn(t,l);if(!fn(a,r))return d.getSnippetsSuggestions();if(s.triggerKind===t.languages.CompletionTriggerKind.Invoke&&!s.triggerCharacter)return d.getFunctionsSuggestions();const m=a.getWordUntilPosition({lineNumber:r.lineNumber,column:r.column-1});return d.getTemplateDataSuggestions(m.word)}};return t.languages.registerCompletionItemProvider("go-template",n)}function fn(t,n){const a={startLineNumber:n.lineNumber,endLineNumber:n.lineNumber,startColumn:t.getLineMinColumn(n.lineNumber),endColumn:t.getLineMaxColumn(n.lineNumber)},r='\\{\\{[a-zA-Z0-9._() "]+\\}\\}';return t.findMatches(r,a,!0,!1,null,!0).some(c=>c.range.containsPosition(n))}class hn{constructor(n,a){this.monaco=n,this.range=a,this.getSnippetsSuggestions=()=>this.getCompletionsFromDefinitions(pn(this.monaco)),this.getFunctionsSuggestions=()=>this.getCompletionsFromDefinitions(en(this.monaco)),this.getTemplateDataSuggestions=r=>{switch(r){case"":return this.getCompletionsFromDefinitions(cn(this.monaco),dn(this.monaco));case"Alerts":return this.getCompletionsFromDefinitions(mn(this.monaco));case"GroupLabels":case"CommonLabels":case"CommonAnnotations":case"Labels":case"Annotations":return this.getCompletionsFromDefinitions(un(this.monaco));default:return{suggestions:[]}}},this.getCompletionsFromDefinitions=(...r)=>({suggestions:(0,k.concat)(...r).map(c=>En(c,this.range))})}}function En({label:t,detail:n,documentation:a,kind:r,insertText:s},c){const l=typeof t=="string"?t:t.label,d=typeof t=="string"?{label:t,description:n}:{...t};return d.description??=n,{label:d,kind:r,insertText:s??l,range:c,documentation:a,detail:n}}const Je="go-template",yn={id:Je,extensions:[],aliases:[],mimetypes:[],loader:()=>Promise.resolve().then(i.bind(i,21475))},vn=(t,n)=>{const{id:a,loader:r}=n;t.languages.getLanguages().find(c=>c.id===a)||(t.languages.register({id:a}),r().then(c=>{t.languages.setMonarchTokensProvider(a,c.language),t.languages.setLanguageConfiguration(a,c.conf)}))},Qe=t=>{const n=!!t.autoHeight,a=(0,e.useRef)(null),r=s=>{if(n){const c=s.getContentHeight();try{s.layout({height:c,width:NaN})}catch{}}};return(0,e.useEffect)(()=>()=>{a.current?.dispose()},[]),e.createElement(Ue.p,{showLineNumbers:!0,showMiniMap:!1,...t,onEditorDidMount:r,onBeforeEditorMount:s=>{vn(s,yn),a.current=gn(s)},language:Je})},bn=Object.freeze({name:"",content:""}),An=t=>t.pathname.endsWith("/duplicate"),Ye=`[ { "annotations": { "summary": "Instance instance1 has been down for more than 5 minutes" }, "labels": { "instance": "instance1" }, "startsAt": "${Me(new Date,1).toISOString()}" }] `,Pe=({existing:t,alertManagerSourceName:n,config:a,provenance:r})=>{const s=(0,B.wW)(Ne),c=(0,S.useDispatch)();(0,xe.x)(v=>v.unifiedAlerting.saveAMConfig=Re.oq);const{loading:l,error:d}=(0,E._)(v=>v.saveAMConfig),g=(0,b.TH)(),m=An(g),[p,f]=(0,e.useState)(Ye),[h,y]=(0,e.useState)(null),[T,R]=(0,e.useState)("content"),L=()=>R("preview"),A=v=>{const $=G(v.name,v.content),Q={...a.template_files,[v.name]:$};t&&t.name!==v.name&&delete Q[t.name];const W=[...(a.alertmanager_config.templates??[]).filter(se=>se!==t?.name),v.name],z={template_files:Q,alertmanager_config:{...a.alertmanager_config,templates:W}};c((0,D.mM)({alertManagerSourceName:n,newConfig:z,oldConfig:a,successMessage:"Template saved.",redirectPath:"/alerting/notifications"}))},O=(0,K.cI)({mode:"onSubmit",defaultValues:t??bn}),{handleSubmit:H,register:F,formState:{errors:j},getValues:q,setValue:re,watch:de}=O,I=v=>!a.template_files[v]||t?.name===v?!0:"Another template with this name already exists.",x=n===P.GC;return e.createElement(K.RV,{...O},e.createElement("form",{onSubmit:H(A)},e.createElement("h4",null,t&&!m?"Edit notification template":"Create notification template"),d&&e.createElement(C.b,{severity:"error",title:"Error saving template"},d.message||d?.data?.message||String(d)),r&&e.createElement(ue.Xq,{resource:ue.Uv.Template}),e.createElement(Rt.C,{disabled:!!r},e.createElement(le.g,{label:"Template name",error:j?.name?.message,invalid:!!j.name?.message,required:!0},e.createElement(me.I,{...F("name",{required:{value:!0,message:"Required."},validate:{nameIsUnique:I}}),placeholder:"Give your template a name",width:42,autoFocus:!0})),e.createElement(Cn,null),e.createElement("div",{className:s.editorsWrapper},e.createElement("div",{className:s.contentContainer},e.createElement(wt.J,null,e.createElement(ke.O,{label:"Content",active:T==="content",onChangeTab:()=>R("content")}),x&&e.createElement(ke.O,{label:"Preview",active:T==="preview",onChangeTab:()=>R("preview")})),e.createElement("div",{className:s.contentContainerEditor},e.createElement(ye.Z,null,({width:v})=>e.createElement(e.Fragment,null,T==="content"?e.createElement("div",null,e.createElement(le.g,{error:j?.content?.message,invalid:!!j.content?.message,required:!0},e.createElement("div",{className:s.editWrapper},e.createElement(Qe,{value:q("content"),width:v,height:363,onBlur:$=>re("content",$)}))),e.createElement("div",{className:s.buttons},l&&e.createElement(w.zx,{disabled:!0,icon:"fa fa-spinner",variant:"primary"},"Saving..."),!l&&e.createElement(w.zx,{type:"submit",variant:"primary"},"Save template"),e.createElement(w.Qj,{disabled:l,href:(0,Z.eQ)("alerting/notifications",n),variant:"secondary",type:"button"},"Cancel"))):e.createElement(wn,{width:v,payload:p,templateName:de("name"),setPayloadFormatError:y,payloadFormatError:h}))))),x&&e.createElement(Xt,{payload:p,setPayload:f,defaultPayload:Ye,setPayloadFormatError:y,payloadFormatError:h,onPayloadError:L}))),e.createElement(Pt.s,{label:"Data cheat sheet",isOpen:!1,className:s.collapsableSection},e.createElement(Kt,null))))};function Cn(){const t=(0,B.wW)(Ne);return e.createElement(C.b,{title:"Templating guideline",severity:"info"},e.createElement(oe.K,{direction:"row"},e.createElement("div",null,"Grafana uses Go templating language to create notification messages.",e.createElement("br",null),"To find out more about templating please visit our documentation."),e.createElement("div",null,e.createElement(w.Qj,{href:"https://grafana.com/docs/grafana/latest/alerting/manage-notifications/template-notifications/",target:"_blank",icon:"external-link-alt",variant:"secondary"},"Templating documentation"))),e.createElement("div",{className:t.snippets},"To make templating easier, we provide a few snippets in the content editor to help you speed up your workflow.",e.createElement("div",{className:t.code},Object.values(He).map(n=>n.label).join(", "))))}function Sn(t){const n=t.filter(s=>s.text.trim().length>0),a=n.length>1,r=s=>{const c=`Preview for ${s.name}:`,l="=".repeat(c.length).concat(">"),d="<".concat("=".repeat(c.length));return a?`${c} ${l}${s.text}${d} `:`${l}${s.text}${d} `};return n.map(s=>r(s)).join(` `)}function Tn(t){return t.map(n=>n.name?`ERROR in ${n.name}: `.concat(`${n.kind} ${n.message} `):`ERROR: ${n.kind} ${n.message} `).join(` `)}const xn="Preview request failed. Check if the payload data has the correct structure.";function Rn(t,n,a){const r=t?xn:void 0,s=t||!!n,c=n||r,l=a?.results,d=a?.errors,g=l?Sn(l):"",m=d?Tn(d):"";return s?c:`${g} ${m}`}function wn({payload:t,templateName:n,payloadFormatError:a,setPayloadFormatError:r,width:s}){const c=(0,B.wW)(Ne),{watch:l}=(0,K.Gc)(),d=l("content"),[g,{data:m,isError:p,isLoading:f}]=Lt(),h=Rn(p,a,m),y=(0,e.useCallback)(()=>{try{const T=JSON.parse(t);JSON.stringify([...T]),g({template:d,alerts:T,name:n}),r(null)}catch(T){r(T instanceof Error?T.message:"Invalid JSON.")}},[d,n,t,r,g]);return(0,e.useEffect)(()=>y(),[y]),e.createElement("div",{style:{width:`${s}px`},className:c.preview.wrapper},f&&e.createElement(e.Fragment,null,e.createElement(Nt.$,{inline:!0})," Loading preview..."),e.createElement("pre",{className:c.preview.result,"data-testid":"payloadJSON"},h),e.createElement(w.zx,{onClick:y,className:c.preview.button,icon:"arrow-up",type:"button",variant:"secondary"},"Refresh preview"))}const Ne=t=>({contentContainer:(0,u.css)` flex: 1; margin-bottom: ${t.spacing(6)}; `,contentContainerEditor:(0,u.css)` flex:1; display: flex; padding-top: 10px; gap: ${t.spacing(2)}; flex-direction: row; align-items: flex-start; flex-wrap: wrap; ${t.breakpoints.up("xxl")} { flex - wrap: nowrap; } min-width: 450px; height: 363px; `,snippets:(0,u.css)` margin-top: ${t.spacing(2)}; font-size: ${t.typography.bodySmall.fontSize}; `,code:(0,u.css)` color: ${t.colors.text.secondary}; font-weight: ${t.typography.fontWeightBold}; `,buttons:(0,u.css)` display: flex; & > * + * { margin-left: ${t.spacing(1)}; } margin-top: -7px; `,textarea:(0,u.css)` max-width: 758px; `,editWrapper:(0,u.css)` display: flex; width: 100% heigth:100%; position: relative; `,toggle:(0,u.css)` color: theme.colors.text.secondary, marginRight: ${t.spacing(1)}`,preview:{wrapper:(0,u.css)` display: flex; width: 100% heigth:100%; position: relative; flex-direction: column; `,result:(0,u.css)` width: 100%; height: 363px; `,button:(0,u.css)` flex: none; width: fit-content; margin-top: -6px; `},collapsableSection:(0,u.css)` width: fit-content; `,editorsWrapper:(0,u.css)` display: flex; flex: 1; flex-wrap: wrap; gap: ${t.spacing(1)}; `}),Pn=({config:t,templateName:n,alertManagerSourceName:a})=>{const r=t.template_files?.[n];if(!r)return e.createElement(C.b,{severity:"error",title:"Template not found"},"Sorry, this template does not seem to exists.");const s=(0,te.G)(n,Object.keys(t.template_files));return e.createElement(Pe,{alertManagerSourceName:a,config:t,existing:{name:s,content:J(r)}})};function o(t,n,a,r={}){return{propertyName:t,label:n,description:a,element:"input",inputType:"",required:!1,secure:!1,placeholder:"",validationRule:"",showWhen:{field:"",is:""},dependsOn:"",...r}}const Nn=o("basic_auth","Basic auth","Sets the `Authorization` header with the configured username and password. Password and password_file are mutually exclusive.",{element:"subform",subformOptions:[o("username","Username",""),o("password","Password",""),o("password_file","Password file","")]}),Ze=o("tls_config","TLS config","Configures the TLS settings.",{element:"subform",subformOptions:[o("ca_file","CA file","CA certificate to validate the server certificate with."),o("cert_file","Cert file","Certificate for client cert authentication to the server."),o("key_file","Key file","Key file for client cert authentication to the server."),o("server_name","Server name","ServerName extension to indicate the name of the server."),o("insecure_skip_verify","Skip verify","Disable validation of the server certificate.",{element:"checkbox"})]}),ee=o("http_config","HTTP Config","Note that `basic_auth`, `bearer_token` and `bearer_token_file` options are mutually exclusive.",{element:"subform",subformOptions:[o("bearer_token","Bearer token","Sets the `Authorization` header with the configured bearer token."),o("bearer_token_file","Bearer token file","Sets the `Authorization` header with the bearer token read from the configured file."),o("proxy_url","Proxy URL","Optional proxy URL."),Nn,Ze]}),Xe=[{name:"Email",description:"Send notification over SMTP",type:"email",info:"",heading:"Email settings",options:[o("to","To",'The email address to send notifications to. You can enter multiple addresses using a "," separator',{required:!0}),o("from","From","The sender address."),o("smarthost","SMTP host","The SMTP host through which emails are sent."),o("hello","Hello","The hostname to identify to the SMTP server."),o("auth_username","Username","SMTP authentication information"),o("auth_password","Password","SMTP authentication information"),o("auth_secret","Secret","SMTP authentication information"),o("auth_identity","Identity","SMTP authentication information"),o("require_tls","Require TLS","The SMTP TLS requirement",{element:"checkbox"}),o("html","Email HTML body","The HTML body of the email notification.",{placeholder:'{{ template "email.default.html" . }}',element:"textarea"}),o("text","Email text body","The text body of the email notification.",{element:"textarea"}),o("headers","Headers","Further headers email header key/value pairs. Overrides any headers previously set by the notification implementation.",{element:"key_value_map"}),Ze]},{name:"PagerDuty",description:"Send notifications to PagerDuty",type:"pagerduty",info:"",heading:"PagerDuty settings",options:[o("routing_key","Routing key","The PagerDuty integration key (when using PagerDuty integration type `Events API v2`)"),o("service_key","Service key","The PagerDuty integration key (when using PagerDuty integration type `Prometheus`)."),o("url","URL","The URL to send API requests to"),o("client","Client","The client identification of the Alertmanager.",{placeholder:'{{ template "pagerduty.default.client" . }}'}),o("client_url","Client URL","A backlink to the sender of the notification.",{placeholder:'{{ template "pagerduty.default.clientURL" . }}'}),o("description","Description","A description of the incident.",{placeholder:'{{ template "pagerduty.default.description" .}}'}),o("severity","Severity","Severity of the incident.",{placeholder:"error"}),o("details","Details","A set of arbitrary key/value pairs that provide further detail about the incident.",{element:"key_value_map"}),o("images","Images","Images to attach to the incident.",{element:"subform_array",subformOptions:[o("href","URL","",{required:!0}),o("source","Source","",{required:!0}),o("alt","Alt","",{required:!0})]}),o("links","Links","Links to attach to the incident.",{element:"subform_array",subformOptions:[o("href","URL","",{required:!0}),o("text","Text","",{required:!0})]}),ee]},{name:"Pushover",description:"Send notifications to Pushover",type:"pushover",info:"",heading:"Pushover settings",options:[o("user_key","User key","The recipient user\u2019s user key.",{required:!0}),o("token","Token","Your registered application\u2019s API token, see https://pushover.net/app",{required:!0}),o("title","Title","Notification title.",{placeholder:'{{ template "pushover.default.title" . }}'}),o("message","Message","Notification message.",{placeholder:'{{ template "pushover.default.message" . }}'}),o("url","URL","A supplementary URL shown alongside the message.",{placeholder:'{{ template "pushover.default.url" . }}'}),o("priority","Priority","Priority, see https://pushover.net/api#priority",{placeholder:'{{ if eq .Status "firing" }}2{{ else }}0{{ end }}'}),o("retry","Retry","How often the Pushover servers will send the same notification to the user. Must be at least 30 seconds.",{placeholder:"1m"}),o("expire","Expire","How long your notification will continue to be retried for, unless the user acknowledges the notification.",{placeholder:"1h"}),ee]},{name:"Slack",description:"Send notifications to Slack",type:"slack",info:"",heading:"Slack settings",options:[o("api_url","Webhook URL","The Slack webhook URL."),o("channel","Channel","The #channel or @user to send notifications to.",{required:!0}),o("icon_emoji","Emoji icon",""),o("icon_url","Icon URL",""),o("link_names","Names link","",{element:"checkbox"}),o("username","Username","",{placeholder:'{{ template "slack.default.username" . }}'}),o("callback_id","Callback ID","",{placeholder:'{{ template "slack.default.callbackid" . }}'}),o("color","Color","",{placeholder:'{{ if eq .Status "firing" }}danger{{ else }}good{{ end }}'}),o("fallback","Fallback","",{placeholder:'{{ template "slack.default.fallback" . }}'}),o("footer","Footer","",{placeholder:'{{ template "slack.default.footer" . }}'}),o("mrkdwn_in","Mrkdwn fields","An array of field names that should be formatted by mrkdwn syntax.",{element:"string_array"}),o("pretext","Pre-text","",{placeholder:'{{ template "slack.default.pretext" . }}'}),o("short_fields","Short fields","",{element:"checkbox"}),o("text","Message body","",{element:"textarea",placeholder:'{{ template "slack.default.text" . }}'}),o("title","Title","",{placeholder:'{{ template "slack.default.title" . }}'}),o("title_link","Title link","",{placeholder:'{{ template "slack.default.titlelink" . }}'}),o("image_url","Image URL",""),o("thumb_url","Thumbnail URL",""),o("actions","Actions","",{element:"subform_array",subformOptions:[o("text","Text","",{required:!0}),o("type","Type","",{required:!0}),o("url","URL","Either url or name and value are mandatory."),o("name","Name",""),o("value","Value",""),o("confirm","Confirm","",{element:"subform",subformOptions:[o("text","Text","",{required:!0}),o("dismiss_text","Dismiss text",""),o("ok_text","OK text",""),o("title","Title","")]}),o("style","Style","")]}),o("fields","Fields","",{element:"subform_array",subformOptions:[o("title","Title","",{required:!0}),o("value","Value","",{required:!0}),o("short","Short","",{element:"checkbox"})]}),ee]},{name:"OpsGenie",description:"Send notifications to OpsGenie",type:"opsgenie",info:"",heading:"OpsGenie settings",options:[o("api_key","API key","The API key to use when talking to the OpsGenie API."),o("api_url","API URL","The host to send OpsGenie API requests to."),o("message","Message","Alert text limited to 130 characters."),o("description","Description","A description of the incident.",{placeholder:'{{ template "opsgenie.default.description" . }}'}),o("source","Source","A backlink to the sender of the notification.",{placeholder:'{{ template "opsgenie.default.source" . }}'}),o("details","Details","A set of arbitrary key/value pairs that provide further detail about the incident.",{element:"key_value_map"}),o("tags","Tags","Comma separated list of tags attached to the notifications."),o("note","Note","Additional alert note."),o("priority","Priority","Priority level of alert. Possible values are P1, P2, P3, P4, and P5."),o("responders","Responders","List of responders responsible for notifications.",{element:"subform_array",subformOptions:[o("type","Type",'"team", "user", "escalation" or schedule".',{required:!0}),o("id","ID","Exactly one of these fields should be defined."),o("name","Name","Exactly one of these fields should be defined."),o("username","Username","Exactly one of these fields should be defined.")]}),ee]},{name:"VictorOps",description:"Send notifications to VictorOps",type:"victorops",info:"",heading:"VictorOps settings",options:[o("api_key","API key","The API key to use when talking to the VictorOps API."),o("api_url","API URL","The VictorOps API URL."),o("routing_key","Routing key","A key used to map the alert to a team.",{required:!0}),o("message_type","Message type","Describes the behavior of the alert (CRITICAL, WARNING, INFO)."),o("entity_display_name","Entity display name","Contains summary of the alerted problem.",{placeholder:'{{ template "victorops.default.entity_display_name" . }}'}),o("state_message","State message","Contains long explanation of the alerted problem.",{placeholder:'{{ template "victorops.default.state_message" . }}'}),o("monitoring_tool","Monitoring tool","The monitoring tool the state message is from.",{placeholder:'{{ template "victorops.default.monitoring_tool" . }}'}),ee]},{name:"Webhook",description:"Send notifications to a webhook",type:"webhook",info:"",heading:"Webhook settings",options:[o("url","URL","The endpoint to send HTTP POST requests to.",{required:!0}),o("max_alerts","Max alerts","The maximum number of alerts to include in a single webhook message. Alerts above this threshold are truncated. When leaving this at its default value of 0, all alerts are included.",{placeholder:"0",validationRule:"(^\\d+$|^$)"}),ee]},{name:"Discord",description:"Sends notifications to Discord",type:"discord",info:"",heading:"Discord settings",options:[o("title","Title","Templated title of the message",{placeholder:'{{ template "discord.default.title" . }}'}),o("message","Message Content","Mention a group using @ or a user using <@ID> when notifying in a channel",{placeholder:'{{ template "discord.default.message" . }}'}),o("webhook_url","Webhook URL","",{placeholder:"Discord webhook URL",required:!0}),ee]},{name:"Cisco Webex Teams",description:"Sends notifications to Cisco Webex Teams",type:"webex",info:"",heading:"Cisco Webex Teams settings",options:[o("api_url","API URL","The Webex Teams API URL",{placeholder:"https://webexapis.com/v1/messages"}),o("room_id","Room ID","ID of the Webex Teams room where to send the messages",{required:!0}),o("message","Message","Message template",{placeholder:'{{ template "webex.default.message" .}}'}),{...ee,required:!0}]},{name:"Telegram",description:"Sends notifications to Telegram",type:"telegram",info:"",heading:"Telegram settings",options:[o("api_url","API URL","The Telegram API URL",{placeholder:"https://api.telegram.org"}),o("bot_token","Bot token","Telegram bot token",{required:!0}),o("chat_id","Chat ID","ID of the chat where to send the messages",{required:!0,setValueAs:t=>typeof t=="string"?parseInt(t,10):0}),o("message","Message","Message template",{placeholder:'{{ template "webex.default.message" .}}'}),o("disable_notifications","Disable notifications","Disable telegram notifications",{element:"checkbox"}),o("parse_mode","Parse mode","Parse mode for telegram message",{element:"select",defaultValue:{label:"MarkdownV2",value:"MarkdownV2"},selectOptions:[{label:"MarkdownV2",value:"MarkdownV2"},{label:"Markdown",value:"Markdown"},{label:"HTML",value:"HTML"},{label:"plain text",value:""}]}),ee]},{name:"Amazon SNS",description:"Sends notifications to Amazon SNS",type:"sns",info:"",heading:"Amazon SNS settings",options:[o("api_url","API URL","The Amazon SNS API URL"),o("sigv4","SigV4 authentication","Configures AWS's Signature Verification 4 signing process to sign requests",{element:"subform",subformOptions:[o("region","Region","The AWS region. If blank, the region from the default credentials chain is used"),o("access_key","Access key",'The AWS API access_key. If blank the environment variable "AWS_ACCESS_KEY_ID" is used'),o("secret_key","Secret key",'The AWS API secret_key. If blank the environment variable "AWS_ACCESS_SECRET_ID" is used'),o("profile","Profile","Named AWS profile used to authenticate"),o("role_arn","Rule ARN","AWS Role ARN, an alternative to using AWS API keys")]}),o("topic_arn","SNS topic ARN","If you don't specify this value, you must specify a value for the phone_number or target_arn. If you are using a FIFO SNS topic you should set a message group interval longer than 5 minutes to prevent messages with the same group key being deduplicated by the SNS default deduplication window"),o("phone_number","Phone number","Phone number if message is delivered via SMS in E.164 format. If you don't specify this value, you must specify a value for the topic_arn or target_arn"),o("target_arn","Target ARN","The mobile platform endpoint ARN if message is delivered via mobile notifications. If you don't specify this value, you must specify a value for the topic_arn or phone_number"),o("subject","Subject","Subject line when the message is delivered to email endpoints",{placeholder:'{{ template "sns.default.subject" .}}'}),o("message","Message","The message content of the SNS notification",{placeholder:'{{ template "sns.default.message" .}}'}),o("attributes","Attributes","SNS message attributes",{element:"key_value_map"}),ee]},{name:"WeChat",description:"Sends notifications to WeChat",type:"wechat",info:"",heading:"WeChat settings",options:[o("api_url","API URL","The WeChat API URL"),o("api_secret","API Secret","The API key to use when talking to the WeChat API"),o("corp_id","Corp ID","The corp id for authentication"),o("message","Message","API request data as defined by the WeChat API",{placeholder:'{{ template "wechat.default.message" . }}'}),o("message_type","Message type","Type of the message type",{element:"select",defaultValue:{label:"Text",value:"text"},selectOptions:[{label:"Text",value:"text"},{label:"Markdown",value:"markdown"}]}),o("agent_id","Agent ID","",{placeholder:'{{ template "wechat.default.agent_id" . }}'}),o("to_user","to user","",{placeholder:'{{ template "wechat.default.to_user" . }}'}),o("to_party","to party","",{placeholder:'{{ template "wechat.default.to_party" . }}'}),o("to_tag","to tag","",{placeholder:'{{ template "wechat.default.to_tag" . }}'})]}],On=[o("smtp_from","SMTP from","The default SMTP From header field."),o("smtp_smarthost","SMTP smarthost","The default SMTP smarthost used for sending emails, including port number. Port number usually is 25, or 587 for SMTP over TLS (sometimes referred to as STARTTLS). Example: smtp.example.org:587"),o("smtp_hello","SMTP hello","The default hostname to identify to the SMTP server.",{placeholder:"localhost"}),o("smtp_auth_username","SMTP auth username","SMTP Auth using CRAM-MD5, LOGIN and PLAIN. If empty, Alertmanager doesn't authenticate to the SMTP server."),o("smtp_auth_password","SMTP auth password","SMTP Auth using LOGIN and PLAIN."),o("smtp_auth_identity","SMTP auth identity","SMTP Auth using PLAIN."),o("smtp_auth_secret","SMTP auth secret","SMTP Auth using CRAM-MD5."),o("smtp_require_tls","SMTP require TLS","The default SMTP TLS requirement. Note that Go does not support unencrypted connections to remote SMTP endpoints.",{element:"checkbox"}),o("slack_api_url","Slack API URL",""),o("victorops_api_key","VictorOps API key",""),o("victorops_api_url","VictorOps API URL","",{placeholder:"https://alert.victorops.com/integrations/generic/20131114/alert/"}),o("pagerduty_url","PagerDuty URL","https://events.pagerduty.com/v2/enqueue"),o("opsgenie_api_key","OpsGenie API key",""),o("opsgenie_api_url","OpsGenie API URL","",{placeholder:"https://api.opsgenie.com/"}),o("wechat_api_url","WeChat API URL","",{placeholder:"https://qyapi.weixin.qq.com/cgi-bin/"}),o("wechat_api_secret","WeChat API secret",""),o("wechat_api_corp_id","WeChat API corp id",""),o("webex_api_url","Cisco Webex Teams API URL",""),o("telegram_api_url","The Telegram API URL",""),ee,o("resolve_timeout","Resolve timeout","ResolveTimeout is the default value used by alertmanager if the alert does not include EndsAt, after this time passes it can declare the alert as resolved if it has not been updated. This has no impact on alerts from Prometheus, as they always include EndsAt.",{placeholder:"5m"})];function In(t,n){const a={};let r=1;return[{name:t.name,items:t.grafana_managed_receiver_configs?.map(c=>{const l=String(r++);a[l]=c;const d=n.find(({type:g})=>g===c.type);return kn(l,c,d)})??[]},a]}function Dn(t,n){const a={};let r=1;const s=Object.entries(t).filter(([l])=>l.endsWith("_configs")&&l!=="grafana_managed_receiver_configs").map(([l,d])=>[l.replace("_configs",""),d]).map(([l,d])=>d.map(g=>{const m=String(r++);if(a[m]={type:l,config:g},!n.find(f=>f.type===l))throw new Error(`unknown cloud notifier: ${l}`);return Mn(m,l,g)})).flat();return[{name:t.name,items:s},a]}function Ln(t,n,a){return{name:t.name,grafana_managed_receiver_configs:(t.items??[]).map(r=>{const s=n[r.__id];return tt(r,a,t.name,s)})}}function $n(t,n){const a={name:t.name};return t.items.forEach(({__id:r,type:s,settings:c,sendResolved:l})=>{const d=Ee({...c,send_resolved:l??n.sendResolved}),g=`${s}_configs`;a[g]?a[g].push(d):a[g]=[d]}),a}function qe(t,n,a){const r=t.alertmanager_config.receivers??[];if(n.name!==a&&r.find(({name:c})=>c===n.name))throw new Error(`Duplicate receiver name ${n.name}`);if(a&&!r.find(({name:c})=>c===a))throw new Error(`Expected receiver ${a} to exist, but did not find it in the config`);const s={...t,alertmanager_config:{...t.alertmanager_config,receivers:a?r.map(c=>c.name===a?n:c):[...r,n]}};return s.alertmanager_config.route&&a&&n.name!==a&&(s.alertmanager_config.route=et(s.alertmanager_config.route,a,n.name)),s}function et(t,n,a){const r={...t};return r.receiver===n&&(r.receiver=a),r.routes&&(r.routes=r.routes.map(s=>et(s,n,a))),r}function Mn(t,n,a){return{__id:t,type:n,settings:{...a},secureFields:{},secureSettings:{},sendResolved:a.send_resolved}}function kn(t,n,a){const r={__id:t,type:n.type,provenance:n.provenance,secureSettings:{},settings:{...n.settings},secureFields:{...n.secureFields},disableResolveMessage:n.disableResolveMessage};return a?.options.forEach(s=>{s.secure&&r.settings[s.propertyName]&&(delete r.settings[s.propertyName],r.secureFields[s.propertyName]=!0)}),r}function tt(t,n,a,r){const s={settings:Ee({...r&&r.type===t.type?r.settings??{}:{},...t.settings??{}}),secureSettings:Wn(t.secureSettings,r?.secureFields),type:t.type,name:a,disableResolveMessage:t.disableResolveMessage??r?.disableResolveMessage??n.disableResolveMessage};return r&&(s.uid=r.uid),s}const nt=t=>(0,k.isNil)(t)||t==="";function Ee(t){return(0,k.isArray)(t)?t.forEach(Ee):typeof t=="object"&&t!==null&&Object.entries(t).forEach(([n,a])=>{nt(a)?delete t[n]:Ee(a)}),t}function Wn(t={},n={}){return(0,k.omitBy)(t,(a,r)=>nt(a)&&!(r in n))}var Oe=i(83967);const Un=({pathPrefix:t,className:n,readOnly:a=!1})=>{const{register:r}=(0,K.Gc)();return e.createElement("div",{className:n},e.createElement(le.g,{disabled:a},e.createElement(Oe.X,{...r(`${t}sendResolved`),label:"Send resolved",disabled:a,description:"Whether or not to notify about resolved alerts."})))};var Fn=i(73807);const Vn=[];function at(t){const{name:n,formAPI:a,defaults:r,softDelete:s}=t,{watch:c,getValues:l,reset:d,setValue:g}=a,m=c(n)??r??Vn,p=(0,e.useCallback)(f=>{const h=JSON.parse(JSON.stringify(l())),y=f(m??[]);d((0,k.set)(h,n,y))},[l,n,d,m]);return{fields:m,append:(0,e.useCallback)(f=>p(h=>[...h,f]),[p]),remove:(0,e.useCallback)(f=>{s?g(`${n}.${f}.__deleted`,!0):p(h=>{const y=h.slice();return y.splice(f,1),y})},[p,n,g,s])}}var be=i(16310),rt=i(28580),Bn=i(60105),X=i(18686);const Gn=({value:t,onChange:n,readOnly:a=!1})=>{const r=(0,B.wW)(zn),[s,c]=(0,e.useState)(st(t));(0,e.useEffect)(()=>c(st(t)),[t]);const l=m=>{n(Kn(m))},d=m=>{const p=s.slice(),f=p.splice(m,1)[0];c(p),f[0]&&l(p)},g=(m,p)=>{const f=s[p],h=s.map((y,T)=>T===p?m:y);c(h),(m[0]||f[0])&&l(h)};return e.createElement("div",null,!!s.length&&e.createElement("table",{className:r.table},e.createElement("thead",null,e.createElement("tr",null,e.createElement("th",null,"Name"),e.createElement("th",null,"Value"),!a&&e.createElement("th",null))),e.createElement("tbody",null,s.map(([m,p],f)=>e.createElement("tr",{key:f},e.createElement("td",null,e.createElement(me.I,{readOnly:a,value:m,onChange:h=>g([h.currentTarget.value,p],f)})),e.createElement("td",null,e.createElement(me.I,{readOnly:a,value:p,onChange:h=>g([m,h.currentTarget.value],f)})),!a&&e.createElement("td",null,e.createElement(X.A,{icon:"trash-alt",tooltip:"delete",onClick:()=>d(f)})))))),!a&&e.createElement(w.zx,{className:r.addButton,type:"button",variant:"secondary",icon:"plus",size:"sm",onClick:()=>c([...s,["",""]])},"Add"))},zn=t=>({addButton:(0,u.css)` margin-top: ${t.spacing(1)}; `,table:(0,u.css)` tbody td { padding: 0 ${t.spacing(1)} ${t.spacing(1)} 0; } `}),Kn=t=>{const n={};for(const[a,r]of t)a&&(n[a]=r);return n},st=t=>Object.entries(t??{}),_n=({value:t,onChange:n,readOnly:a=!1})=>{const r=(0,B.wW)(jn),s=l=>{if(!t)return;const d=t.slice();d.splice(l,1),n(d)},c=(l,d)=>{t&&n(t.map((g,m)=>m===d?l:g))};return e.createElement("div",null,!!t?.length&&t.map((l,d)=>e.createElement("div",{key:d,className:r.row},e.createElement(me.I,{readOnly:a,value:l,onChange:g=>c(g.currentTarget.value,d)}),!a&&e.createElement(X.A,{className:r.deleteIcon,icon:"trash-alt",tooltip:"delete",onClick:()=>s(d)}))),!a&&e.createElement(w.zx,{className:r.addButton,type:"button",variant:"secondary",icon:"plus",size:"sm",onClick:()=>n([...t??[],""])},"Add"))},jn=t=>({row:(0,u.css)` display: flex; flex-direction: row; margin-bottom: ${t.spacing(1)}; align-items: center; `,deleteIcon:(0,u.css)` margin-left: ${t.spacing(1)}; `,addButton:(0,u.css)` margin-top: ${t.spacing(1)}; `});var ot=i(10759);const Ie=({label:t,description:n,children:a,className:r,size:s="xl"})=>{const c=(0,B.wW)(Hn),[l,d]=(0,e.useState)(!0),g=()=>d(!l);return e.createElement("div",{className:(0,u.cx)(c.wrapper,r)},e.createElement(ot.U,{className:c.toggle,size:s,onToggle:g,isCollapsed:l,text:t}),n&&e.createElement("p",{className:c.description},n),e.createElement("div",{className:l?c.hidden:c.content},a))},Hn=t=>({wrapper:(0,u.css)` margin-top: ${t.spacing(1)}; padding-bottom: ${t.spacing(1)}; `,toggle:(0,u.css)` margin: ${t.spacing(1,0)}; padding: 0; `,hidden:(0,u.css)` display: none; `,description:(0,u.css)` color: ${t.colors.text.secondary}; font-size: ${t.typography.size.sm}; font-weight: ${t.typography.fontWeightRegular}; margin: 0; `,content:(0,u.css)` padding-left: ${t.spacing(3)}; `}),lt=t=>({collapsibleSection:(0,u.css)` margin: 0; padding: 0; `,wrapper:(0,u.css)` margin: ${t.spacing(2,0)}; padding: ${t.spacing(1)}; border: solid 1px ${t.colors.border.medium}; border-radius: ${t.shape.borderRadius(1)}; position: relative; `,description:(0,u.css)` color: ${t.colors.text.secondary}; font-size: ${t.typography.size.sm}; font-weight: ${t.typography.fontWeightRegular}; margin: 0; `,deleteIcon:(0,u.css)` position: absolute; right: ${t.spacing(1)}; top: ${t.spacing(1)}; `,addButton:(0,u.css)` margin-top: ${t.spacing(1)}; `}),Jn=({option:t,pathPrefix:n,errors:a,defaultValues:r,readOnly:s=!1})=>{const c=(0,B.wW)(lt),l=`${n}${t.propertyName}`,d=(0,K.Gc)(),{fields:g,append:m,remove:p}=at({name:l,formAPI:d,defaults:r});return e.createElement("div",{className:c.wrapper},e.createElement(Ie,{className:c.collapsibleSection,label:`${t.label} (${g.length})`,description:t.description},(g??r??[]).map((f,h)=>e.createElement("div",{key:h,className:c.wrapper},!s&&e.createElement(X.A,{"data-testid":`${l}.${h}.delete-button`,icon:"trash-alt",tooltip:"delete",onClick:()=>p(h),className:c.deleteIcon}),t.subformOptions?.map(y=>e.createElement(Ae,{readOnly:s,defaultValue:f?.[y.propertyName],key:y.propertyName,option:y,pathPrefix:`${l}.${h}.`,error:a?.[h]?.[y.propertyName]})))),!s&&e.createElement(w.zx,{"data-testid":`${l}.add-button`,className:c.addButton,type:"button",variant:"secondary",icon:"plus",size:"sm",onClick:()=>m({__id:String(Math.random())})},"Add")))},Qn=({option:t,pathPrefix:n,errors:a,defaultValue:r,readOnly:s=!1})=>{const c=(0,B.wW)(lt),l=`${n}${t.propertyName}`,{watch:d}=(0,K.Gc)(),g=d(l),m=g===void 0?r:g,[p,f]=(0,e.useState)(!!m);return e.createElement("div",{className:c.wrapper,"data-testid":`${l}.container`},e.createElement("h6",null,t.label),t.description&&e.createElement("p",{className:c.description},t.description),p&&e.createElement(e.Fragment,null,!s&&e.createElement(X.A,{"data-testid":`${l}.delete-button`,icon:"trash-alt",tooltip:"delete",onClick:()=>f(!1),className:c.deleteIcon}),(t.subformOptions??[]).map(h=>e.createElement(Ae,{readOnly:s,defaultValue:r?.[h.propertyName],key:h.propertyName,option:h,pathPrefix:`${l}.`,error:a?.[h.propertyName]}))),!p&&!s&&e.createElement(w.zx,{className:c.addButton,type:"button",variant:"secondary",icon:"plus",size:"sm",onClick:()=>f(!0),"data-testid":`${l}.add-button`},"Add"))},Ae=({option:t,invalid:n,pathPrefix:a,pathSuffix:r="",error:s,defaultValue:c,readOnly:l=!1})=>{const d=`${a}${r}`;return t.element==="subform"?e.createElement(Qn,{readOnly:l,defaultValue:c,option:t,errors:s,pathPrefix:d}):t.element==="subform_array"?e.createElement(Jn,{readOnly:l,defaultValues:c,option:t,pathPrefix:d,errors:s}):e.createElement(le.g,{label:t.element!=="checkbox"?t.label:void 0,description:t.description||void 0,invalid:!!s,error:s?.message},e.createElement(Yn,{id:`${d}${t.propertyName}`,defaultValue:c,option:t,invalid:n,pathPrefix:d,readOnly:l,pathIndex:a}))},Yn=({option:t,invalid:n,id:a,pathPrefix:r="",pathIndex:s="",readOnly:c=!1})=>{const{control:l,register:d,unregister:g,getValues:m}=(0,K.Gc)(),p=`${r}${t.propertyName}`;switch((0,e.useEffect)(()=>()=>{g(p,{keepValue:!1})},[g,p]),t.element){case"checkbox":return e.createElement(Oe.X,{id:a,readOnly:c,disabled:c,className:Zn.checkbox,...d(p),label:t.label,description:t.description});case"input":return e.createElement(me.I,{id:a,readOnly:c||qn(t,m,s),invalid:n,type:t.inputType,...d(p,{required:Xn(t,m,s),validate:f=>t.validationRule!==""?it(f,t.validationRule):!0,setValueAs:t.setValueAs}),placeholder:t.placeholder});case"select":return e.createElement(be.g,{render:({field:{onChange:f,ref:h,...y}})=>e.createElement(rt.Ph,{disabled:c,...y,defaultValue:t.defaultValue,options:t.selectOptions??void 0,invalid:n,onChange:T=>f(T.value)}),control:l,name:p});case"textarea":return e.createElement(Bn.K,{id:a,readOnly:c,invalid:n,placeholder:t.placeholder,...d(p,{required:t.required?"Required":!1,validate:f=>t.validationRule!==""?it(f,t.validationRule):!0})});case"string_array":return e.createElement(be.g,{render:({field:{value:f,onChange:h}})=>e.createElement(_n,{readOnly:c,value:f,onChange:h}),control:l,name:p});case"key_value_map":return e.createElement(be.g,{render:({field:{value:f,onChange:h}})=>e.createElement(Gn,{readOnly:c,value:f,onChange:h}),control:l,name:p});default:return console.error("Element not supported",t.element),null}},Zn={checkbox:(0,u.css)` height: auto; // native checkbox has fixed height which does not take into account description `},it=(t,n)=>RegExp(n).test(t)?!0:"Invalid format",Xn=(t,n,a)=>t.dependsOn?(0,k.isEmpty)(n(`${a}secureFields`))?!n(`${a}secureSettings.${t.dependsOn}`)&&t.required?"Required":!1:!n(`${a}secureFields.${t.dependsOn}`)&&t.required?"Required":!1:t.required?"Required":!1,qn=(t,n,a)=>t.dependsOn?(0,k.isEmpty)(n(`${a}secureFields`))?n(`${a}secureSettings.${t.dependsOn}`):n(`${a}secureFields.${t.dependsOn}`):!1;function ct({defaultValues:t,selectedChannelOptions:n,onResetSecureField:a,secureFields:r,errors:s,pathPrefix:c="",readOnly:l=!1}){const{watch:d}=(0,K.Gc)(),g=d();return e.createElement(e.Fragment,null,n.map((m,p)=>{const f=`${m.label}-${p}`,h=c.split("."),y=h.length>=2?g.items[Number(h[1])].settings[m.showWhen.field]:void 0;if(m.showWhen.field&&y!==m.showWhen.is)return null;if(r&&r[m.propertyName])return e.createElement(le.g,{key:f,label:m.label,description:m.description||void 0},e.createElement(me.I,{readOnly:!0,value:"Configured",suffix:l?null:e.createElement(w.zx,{onClick:()=>a(m.propertyName),fill:"text",type:"button",size:"sm"},"Clear")}));const T=(m.secure?s?.secureSettings:s?.settings)?.[m.propertyName],R=t?.settings?.[m.propertyName];return e.createElement(Ae,{defaultValue:R,readOnly:l,key:f,error:T,pathPrefix:c,pathSuffix:m.secure?"secureSettings.":"settings.",option:m})}))}function ea({defaultValues:t,pathPrefix:n,onDuplicate:a,onDelete:r,onTest:s,notifiers:c,errors:l,secureFields:d,commonSettingsComponent:g,isEditable:m=!0,isTestable:p}){const f=(0,B.wW)(ta),h=W=>`${n}${W}`,{control:y,watch:T,register:R,trigger:L,formState:A,setValue:O}=(0,K.Gc)(),H=T(h("type"))??t.type,{loading:F}=(0,E._)(W=>W.testReceivers);(0,e.useEffect)(()=>{R(`${n}.__id`),R(`${n}.secureFields`)},[R,n]);const[j,q]=(0,e.useState)(d??{}),re=W=>{if(j[W]){const z={...d};delete z[W],q(z),O(`${n}.secureFields`,z)}},de=(0,e.useMemo)(()=>c.map(({name:W,type:z})=>({label:W,value:z})).sort((W,z)=>W.label.localeCompare(z.label)),[c]),I=async()=>{await L(),Object.keys(A.errors).length===0&&s&&s()},x=c.find(({type:W})=>W===H),v=x?.options.filter(W=>W.required),$=x?.options.filter(W=>!W.required),Q=`contact-point-type-${n}`;return e.createElement("div",{className:f.wrapper,"data-testid":"item-container"},e.createElement("div",{className:f.topRow},e.createElement("div",null,e.createElement(le.g,{label:"Integration",htmlFor:Q,"data-testid":`${n}type`},e.createElement(be.g,{name:h("type"),defaultValue:t.type,render:({field:{ref:W,onChange:z,...se}})=>e.createElement(rt.Ph,{disabled:!m,inputId:Q,...se,width:37,options:de,onChange:$e=>z($e?.value)}),control:y,rules:{required:!0}}))),e.createElement("div",{className:f.buttons},p&&s&&e.createElement(w.zx,{disabled:F,size:"xs",variant:"secondary",type:"button",onClick:()=>I(),icon:F?"fa fa-spinner":"message"},"Test"),m&&e.createElement(e.Fragment,null,e.createElement(w.zx,{size:"xs",variant:"secondary",type:"button",onClick:()=>a(),icon:"copy"},"Duplicate"),r&&e.createElement(w.zx,{"data-testid":`${n}delete-button`,size:"xs",variant:"secondary",type:"button",onClick:()=>r(),icon:"trash-alt"},"Delete")))),x&&e.createElement("div",{className:f.innerContent},e.createElement(ct,{defaultValues:t,selectedChannelOptions:v?.length?v:$,secureFields:j,errors:l,onResetSecureField:re,pathPrefix:n,readOnly:!m}),!!(v?.length&&$?.length)&&e.createElement(Ie,{label:`Optional ${x.name} settings`},x.info!==""&&e.createElement(C.b,{title:"",severity:"info"},x.info),e.createElement(ct,{defaultValues:t,selectedChannelOptions:$,secureFields:j,onResetSecureField:re,errors:l,pathPrefix:n,readOnly:!m})),e.createElement(Ie,{label:"Notification settings"},e.createElement(g,{pathPrefix:n,readOnly:!m}))))}const ta=t=>({buttons:(0,u.css)` & > * + * { margin-left: ${t.spacing(1)}; } `,innerContent:(0,u.css)` max-width: 536px; `,wrapper:(0,u.css)` margin: ${t.spacing(2,0)}; padding: ${t.spacing(1)}; border: solid 1px ${t.colors.border.medium}; border-radius: ${t.shape.borderRadius(1)}; max-width: ${t.breakpoints.values.xl}${t.breakpoints.unit}; `,topRow:(0,u.css)` display: flex; flex-direction: row; justify-content: space-between; `,channelSettingsHeader:(0,u.css)` margin-top: ${t.spacing(2)}; `});function na({pathPrefix:t}){const{register:n}=(0,K.Gc)();return(0,e.useEffect)(()=>{n(`${t}.__id`),n(`${t}.__deleted`)},[n,t]),e.createElement(e.Fragment,null)}function aa(t){if(t)return{...t,items:t.items.map(n=>({...n,settings:{...n.settings,http_config:n.settings?.http_config?ra(n.settings?.http_config):void 0}}))}}function ra(t){return sa(t)?t:{...(0,k.omit)(t,"authorization"),bearer_token:t.authorization?.credentials,bearer_token_file:t.authorization?.credentials_file}}function sa(t){return["bearer_token","bearer_token_file"].some(n=>n in t)}function dt({config:t,initialValues:n,defaultItem:a,notifiers:r,alertManagerSourceName:s,onSubmit:c,onTestChannel:l,takenReceiverNames:d,commonSettingsComponent:g,isEditable:m,isTestable:p}){const f=(0,Fn.iG)(),h=(0,B.wW)(oa),T=aa(n)??{name:"",items:[{...a,__id:String(Math.random())}]},R=(0,K.cI)({defaultValues:JSON.parse(JSON.stringify(T))});(0,xe.x)(v=>v.unifiedAlerting.saveAMConfig=Re.oq);const{loading:L}=(0,E._)(v=>v.saveAMConfig),{handleSubmit:A,register:O,formState:{errors:H},getValues:F}=R,{fields:j,append:q,remove:re}=at({name:"items",formAPI:R,softDelete:!0}),de=(0,e.useCallback)(v=>d.map($=>$.trim().toLowerCase()).includes(v.trim().toLowerCase())?"Another receiver with this name already exists.":!0,[d]),I=v=>{c({...v,items:v.items.filter($=>!$.__deleted)})},x=()=>{f.error("There are errors in the form. Please correct them and try again!")};return e.createElement(K.RV,{...R},!t.alertmanager_config.route&&e.createElement(C.b,{severity:"warning",title:"Attention"},"Because there is no default policy configured yet, this contact point will automatically be set as default."),e.createElement("form",{onSubmit:A(I,x)},e.createElement("h4",{className:h.heading},m?n?"Update contact point":"Create contact point":"Contact point"),e.createElement(le.g,{label:"Name",invalid:!!H.name,error:H.name&&H.name.message,required:!0},e.createElement(me.I,{readOnly:!m,id:"name",...O("name",{required:"Name is required",validate:{nameIsAvailable:de}}),width:39,placeholder:"Name"})),j.map((v,$)=>{const Q=`items.${$}.`;if(v.__deleted)return e.createElement(na,{key:v.__id,pathPrefix:Q});const W=n?.items.find(({__id:z})=>z===v.__id);return e.createElement(ea,{defaultValues:v,key:v.__id,onDuplicate:()=>{const z=F().items[$];q({...z,__id:String(Math.random())})},onTest:l?()=>{const z=F().items[$];l(z)}:void 0,onDelete:()=>re($),pathPrefix:Q,notifiers:r,secureFields:W?.secureFields,errors:H?.items?.[$],commonSettingsComponent:g,isEditable:m,isTestable:p})}),e.createElement(e.Fragment,null,m&&e.createElement(w.zx,{type:"button",icon:"plus",variant:"secondary",onClick:()=>q({...a,__id:String(Math.random())})},"Add contact point integration"),e.createElement("div",{className:h.buttons},m&&e.createElement(e.Fragment,null,L&&e.createElement(w.zx,{disabled:!0,icon:"fa fa-spinner",variant:"primary"},"Saving..."),!L&&e.createElement(w.zx,{type:"submit"},"Save contact point")),e.createElement(w.Qj,{disabled:L,variant:"secondary","data-testid":"cancel-button",href:(0,Z.eQ)("alerting/notifications",s)},"Cancel")))))}const oa=t=>({heading:(0,u.css)` margin: ${t.spacing(4,0)}; `,buttons:(0,u.css)` margin-top: ${t.spacing(4)}; & > * + * { margin-left: ${t.spacing(1)}; } `}),mt=Object.freeze({__id:"",sendResolved:!0,secureSettings:{},settings:{},secureFields:{},type:"email"}),ut=({existing:t,alertManagerSourceName:n,config:a})=>{const r=(0,S.useDispatch)(),s=(0,P.RY)(n),[c]=(0,e.useMemo)(()=>t?Dn(t,Xe):[void 0,{}],[t]),l=m=>{const p=$n(m,mt);r((0,D.mM)({newConfig:qe(a,p,t?.name),oldConfig:a,alertManagerSourceName:n,successMessage:t?"Contact point updated.":"Contact point created.",redirectPath:"/alerting/notifications"}))},d=(0,e.useMemo)(()=>a.alertmanager_config.receivers?.map(({name:m})=>m).filter(m=>m!==t?.name)??[],[a,t]),g=!(0,P.RY)(n);return e.createElement(e.Fragment,null,!s&&e.createElement(C.b,{title:"Info",severity:"info"},"Note that empty string values will be replaced with global defaults where appropriate."),e.createElement(dt,{isEditable:g,isTestable:g,config:a,onSubmit:l,initialValues:c,notifiers:Xe,alertManagerSourceName:n,defaultItem:mt,takenReceiverNames:d,commonSettingsComponent:Un}))},la=({pathPrefix:t,className:n,readOnly:a=!1})=>{const{register:r}=(0,K.Gc)();return e.createElement("div",{className:n},e.createElement(le.g,null,e.createElement(Oe.X,{...r(`${t}disableResolveMessage`),label:"Disable resolved message",description:"Disable the resolve message [OK] that is sent when alerting state returns to false",disabled:a})))};var ia=i(79978),ca=i(33555),pt=(t=>(t.predefined="Predefined",t.custom="Custom",t))(pt||{});const da=Object.values(pt).map(t=>({label:t,value:t})),ma={annotations:[...ca.eY],labels:[{key:"",value:""}]},ua=({isOpen:t,onDismiss:n,onTest:a})=>{const[r,s]=(0,e.useState)("Predefined"),c=(0,B.wW)(pa),l=(0,K.cI)({defaultValues:ma,mode:"onBlur"}),d=g=>{if(r==="Custom"){const m={annotations:g.annotations.filter(({key:p,value:f})=>!!p&&!!f).reduce((p,{key:f,value:h})=>({...p,[f]:h}),{}),labels:g.labels.filter(({key:p,value:f})=>!!p&&!!f).reduce((p,{key:f,value:h})=>({...p,[f]:h}),{})};a(m)}else a()};return e.createElement(ie.u,{onDismiss:n,isOpen:t,title:"Test contact point"},e.createElement("div",{className:c.section},e.createElement(ia._,null,"Notification message"),e.createElement(ze.S,{options:da,value:r,onChange:g=>s(g)})),e.createElement(K.RV,{...l},e.createElement("form",{onSubmit:l.handleSubmit(d)},r==="Predefined"&&e.createElement("div",{className:c.section},"You will send a test notification that uses a predefined alert. If you have defined a custom template or message, for better results switch to ",e.createElement("strong",null,"custom")," notification message, from above."),r==="Custom"&&e.createElement(e.Fragment,null,e.createElement("div",{className:c.section},"You will send a test notification that uses the annotations defined below. This is a good option if you use custom templates and messages."),e.createElement("div",{className:c.section},e.createElement(Ke.Z,null)),e.createElement("div",{className:c.section},e.createElement(_e.Z,null))),e.createElement(ie.u.ButtonRow,null,e.createElement(w.zx,{type:"submit"},"Send test notification")))))},pa=t=>({flexRow:(0,u.css)` display: flex; flex-direction: row; align-items: flex-start; margin-bottom: ${t.spacing(1)}; `,section:(0,u.css)` margin-bottom: ${t.spacing(2)}; `}),De=Object.freeze({__id:"",secureSettings:{},settings:{},secureFields:{},disableResolveMessage:!1,type:"email"}),gt=({existing:t,alertManagerSourceName:n,config:a})=>{const r=(0,E._)(A=>A.grafanaNotifiers),[s,c]=(0,e.useState)(),l=(0,S.useDispatch)();(0,e.useEffect)(()=>{r.result||r.loading||l((0,D.Vj)())},[r,l]);const[d,g]=(0,e.useMemo)(()=>!t||!r.result?[void 0,{}]:In(t,r.result),[t,r.result]),m=A=>{const O=Ln(A,g,De);l((0,D.mM)({newConfig:qe(a,O,t?.name),oldConfig:a,alertManagerSourceName:P.GC,successMessage:t?"Contact point updated.":"Contact point created",redirectPath:"/alerting/notifications"}))},p=A=>{c(A)},f=A=>{if(s){const O=g[s.__id],H=tt(s,De,"test",O),F={alertManagerSourceName:n,receivers:[{name:"test",grafana_managed_receiver_configs:[H]}],alert:A};l((0,D.D8)(F))}},h=(0,e.useMemo)(()=>a.alertmanager_config.receivers?.map(({name:A})=>A).filter(A=>A!==t?.name)??[],[a,t]),y=t?(t.grafana_managed_receiver_configs??[]).some(A=>!!A.provenance):!1,T=!(0,P.RY)(n),R=T&&!y,L=T||y;return r.result?e.createElement(e.Fragment,null,y&&e.createElement(ue.Xq,{resource:ue.Uv.ContactPoint}),e.createElement(dt,{isEditable:R,isTestable:L,config:a,onSubmit:m,initialValues:d,onTestChannel:p,notifiers:r.result,alertManagerSourceName:n,defaultItem:De,takenReceiverNames:h,commonSettingsComponent:la}),e.createElement(ua,{onDismiss:()=>c(void 0),isOpen:!!s,onTest:A=>f(A)})):e.createElement(M.u,{text:"Loading notifiers..."})},ga=({config:t,receiverName:n,alertManagerSourceName:a})=>{const r=t.alertmanager_config.receivers?.find(({name:s})=>s===n);return r?a===P.GC?e.createElement(gt,{config:t,alertManagerSourceName:a,existing:r}):e.createElement(ut,{config:t,alertManagerSourceName:a,existing:r}):e.createElement(C.b,{severity:"error",title:"Receiver not found"},"Sorry, this receiver does not seem to exist.")},fa=({config:t,templateName:n,alertManagerSourceName:a})=>{const r=t.template_files?.[n],s=t.template_file_provenances?.[n];return r?e.createElement(Pe,{alertManagerSourceName:a,config:t,existing:{name:n,content:r},provenance:s}):e.createElement(C.b,{severity:"error",title:"Template not found"},"Sorry, this template does not seem to exists.")};var ft=i(64022);const ht={smtp_require_tls:!0},ha=({config:t,alertManagerSourceName:n})=>{const a=(0,S.useDispatch)();(0,xe.x)(p=>p.unifiedAlerting.saveAMConfig=Re.oq);const{loading:r,error:s}=(0,E._)(p=>p.saveAMConfig),c=(0,P.RY)(n),l=(0,K.cI)({defaultValues:JSON.parse(JSON.stringify({...ht,...t.alertmanager_config.global??{}}))}),{handleSubmit:d,formState:{errors:g}}=l,m=p=>{a((0,D.mM)({newConfig:{...t,alertmanager_config:{...t.alertmanager_config,global:Ee(p)}},oldConfig:t,alertManagerSourceName:n,successMessage:"Global config updated.",redirectPath:(0,Z.eQ)("/alerting/notifications",n)}))};return e.createElement(K.RV,{...l},e.createElement("form",{onSubmit:d(m)},s&&e.createElement(C.b,{severity:"error",title:"Error saving receiver"},s.message||String(s)),On.map(p=>e.createElement(Ae,{readOnly:c,defaultValue:ht[p.propertyName],key:p.propertyName,option:p,error:g[p.propertyName],pathPrefix:""})),e.createElement("div",null,e.createElement(ft.Lh,null,!c&&e.createElement(e.Fragment,null,r&&e.createElement(w.zx,{disabled:!0,icon:"fa fa-spinner",variant:"primary"},"Saving..."),!r&&e.createElement(w.zx,{type:"submit"},"Save global config")),e.createElement(w.Qj,{disabled:r,fill:"outline",variant:"secondary",href:(0,Z.eQ)("alerting/notifications",n)},"Cancel")))))},Ea=({alertManagerSourceName:t,config:n})=>t===P.GC?e.createElement(gt,{alertManagerSourceName:t,config:n}):e.createElement(ut,{alertManagerSourceName:t,config:n}),ya=({config:t,alertManagerSourceName:n})=>e.createElement(Pe,{config:t,alertManagerSourceName:n});var ae=i(89439),va=i(6772),ba=i.n(va),Aa=i(99633),Ca=i(60956),Et=i(3613),Ce=i(91368),pe=i(309),Sa=i(98164),yt=i(38338),vt=i(2082),Ta=i(76658);const xa={pagerduty:"PagerDuty",pushover:"Pushover",slack:"Slack",opsgenie:"OpsGenie",webhook:"Webhook",victorops:"VictorOps",wechat:"WeChat",discord:"Discord",webex:"Cisco Webex Teams",sns:"Amazon SNS",telegram:"Telegram"};function Ra(t,n){return t.grafana_managed_receiver_configs?Pa(t.grafana_managed_receiver_configs??[],n):wa(t)}function wa(t){return Object.entries(t).filter(([n])=>n!=="grafana_managed_receiver_configs"&&n.endsWith("_configs")).filter(([n,a])=>Array.isArray(a)&&!!a.length).reduce((n,[a,r])=>{const s=a.replace("_configs",""),c=xa[s]??(0,k.capitalize)(s);return{...n,[c]:(n[c]??0)+(Array.isArray(r)?r.length:1)}},{})}function Pa(t,n){return t.map(a=>a.type).map(a=>n.find(r=>r.type===a)?.name??(0,k.capitalize)(a)).reduce((a,r)=>({...a,[r]:(a[r]??0)+1}),{})}var bt=i(59597),At=i(45986),Na=i(85014),Oa=i(89746),Ia=i(79655),Da=i(80434);const Ct=({className:t,title:n,description:a,addButtonLabel:r,addButtonTo:s,children:c,showButton:l=!0,exportLink:d})=>{const g=(0,B.wW)(La),m=!!d,p=e.createElement(Oa.v,null,d&&e.createElement(Ia.s,{url:d,label:"Export all",target:"_blank"}));return e.createElement(oe.K,{direction:"column",gap:2},e.createElement("div",{className:(0,u.cx)(g.heading,t)},e.createElement("div",null,e.createElement("h4",null,n),e.createElement("div",{className:g.description},a)),e.createElement(oe.K,{direction:"row",gap:.5},l&&e.createElement(Na.Link,{to:s},e.createElement(w.zx,{type:"button",icon:"plus"},r)),m&&e.createElement(Da.L,{overlay:p},e.createElement(w.zx,{variant:"secondary"},"More",e.createElement(ve.J,{name:"angle-down"}))))),c)},La=t=>({heading:(0,u.css)` display: flex; justify-content: space-between; align-items: flex-end; `,description:(0,u.css)` color: ${t.colors.text.secondary}; `});var Le=i(62401);const $a={[Le.W.OnCall]:"public/img/alerting/oncall_logo.svg",[Le.W.Incident]:"",[Le.W.MachineLearning]:""},Ma=({grafanaAppType:t})=>{const n=(0,B.wW)(ka);return e.createElement("div",{className:n.wrapper},e.createElement(ft.Lh,{align:"center",spacing:"xs"},e.createElement("img",{src:$a[t],alt:"",height:"12px"}),e.createElement("span",null,t)))},ka=t=>({wrapper:(0,u.css)` text-align: left; height: 22px; display: inline-flex; padding: 1px 4px; border-radius: ${t.shape.borderRadius()}; border: 1px solid rgba(245, 95, 62, 1); color: rgba(245, 95, 62, 1); font-weight: ${t.typography.fontWeightRegular}; `});var Wa=i(74023);function Ua(t){if(!t.receivers)return{contactPoints:{}};if(!t.route)return{contactPoints:Object.fromEntries(t.receivers.map(l=>[l.name,{matchingRoutes:0}]))};const n=t.receivers?.map(l=>l.name)??[],a=St(t.route),r=(0,k.countBy)(a),s={},c={contactPoints:s};return n.forEach(l=>{s[l]={matchingRoutes:r[l]??0}}),c}function St(t){const n=t.routes?.flatMap(a=>St(a))??[];return t.receiver?[t.receiver,...n]:n}function Fa({permissions:t,alertManagerName:n,receiverName:a,onClickDeleteReceiver:r}){return e.createElement(e.Fragment,null,e.createElement(ae.q,{actions:[t.update]},e.createElement(X.A,{"aria-label":"Edit","data-testid":"edit",to:(0,Z.eQ)(`/alerting/notifications/receivers/${encodeURIComponent(a)}/edit`,n),tooltip:"Edit contact point",icon:"pen"})),e.createElement(ae.q,{actions:[t.delete]},e.createElement(X.A,{onClick:()=>r(a),tooltip:"Delete contact point",icon:"trash-alt"})))}function Va({permissions:t,alertManagerName:n,receiverName:a}){return e.createElement(ae.q,{actions:[t.update]},e.createElement(X.A,{"data-testid":"view",to:(0,Z.eQ)(`/alerting/notifications/receivers/${encodeURIComponent(a)}/edit`,n),tooltip:"View contact point",icon:"file-alt"}))}function Ba({permissions:t,receiverName:n}){return e.createElement(ae.q,{actions:[t.provisioning.read],fallback:(0,pe.RN)()},e.createElement(X.A,{"data-testid":"export",to:(0,bt.u)("/api/v1/provisioning/contact-points/export/",{download:"true",format:"yaml",decrypt:(0,pe.RN)().toString(),name:n}),tooltip:(0,pe.RN)()?"Export contact point":"Export redacted contact point",icon:"download-alt",target:"_blank"}))}function Tt({errorCount:t,errorDetail:n,showErrorCount:a,tooltip:r}){const s=a?`${t} ${ba()("error",t)}`:"Error",c=r??n??"Error";return e.createElement(ge.C,{color:"red",icon:"exclamation-circle",text:s,tooltip:c})}function Ga({errorsByNotifier:t,errorDetail:n,lastNotify:a}){const r=t>0,s=Se(a);return r?e.createElement(Tt,{errorCount:t,errorDetail:n,showErrorCount:!1}):s?e.createElement(e.Fragment,null,"No attempts"):e.createElement(ge.C,{color:"green",text:"OK"})}function za({errorsByReceiver:t,someWithNoAttempt:n}){return t>0?e.createElement(Tt,{errorCount:t,showErrorCount:!0,tooltip:"Expand the contact point to see error details."}):n?e.createElement(e.Fragment,null,"No attempts"):e.createElement(ge.C,{color:"green",text:"OK"})}const Ka=t=>{const n=(0,Sa.V)(t),a=n?.receivers??{},r=Object.keys(a).length>0;return{contactPointsState:n,errorStateAvailable:r}},Se=t=>t==="0001-01-01T00:00:00.000Z";function _a({lastNotifyDate:t}){return Se(t)?e.createElement(e.Fragment,null,"-"):e.createElement(oe.K,{alignItems:"center"},e.createElement("div",null,`${(0,Aa.CQ)(t).locale("en").fromNow(!0)} ago`),e.createElement(ve.J,{name:"clock-nine"}),e.createElement("div",null,`${(0,Ca.dq)(t,{format:"YYYY-MM-DD HH:mm:ss"})}`))}const ja=["","0","0ms","0s","0m","0h","0d","0w","0y"],Ha=t=>ja.includes(t);function Ja({notifiersState:t}){function n(){return[{id:"health",label:"Health",renderCell:({data:{lastError:r,lastNotify:s}})=>e.createElement(Ga,{errorsByNotifier:r?1:0,errorDetail:r??void 0,lastNotify:s}),size:.5},{id:"name",label:"Name",renderCell:({data:{type:r},id:s})=>e.createElement(e.Fragment,null,`${r}[${s}]`),size:1},{id:"lastNotify",label:"Last delivery attempt",renderCell:({data:{lastNotify:r}})=>e.createElement(_a,{lastNotifyDate:r}),size:3},{id:"lastNotifyDuration",label:"Last duration",renderCell:({data:{lastNotify:r,lastNotifyDuration:s}})=>e.createElement(e.Fragment,null,Se(r)&&Ha(s)?"-":s),size:1},{id:"sendResolved",label:"Send resolved",renderCell:({data:{sendResolved:r}})=>e.createElement(e.Fragment,null,String(!!r)),size:1}]}const a=Object.entries(t).flatMap(r=>r[1].map((s,c)=>({id:c,data:{type:r[0],lastError:s.lastNotifyAttemptError,lastNotify:s.lastNotifyAttempt,lastNotifyDuration:s.lastNotifyAttemptDuration,sendResolved:s.sendResolved}})));return e.createElement(At.t,{items:a,cols:n()})}const Qa=({config:t,alertManagerName:n})=>{const a=(0,S.useDispatch)(),r=(0,P.RY)(n),s=(0,vt.Ko)(n),c=(0,E._)(F=>F.grafanaNotifiers),l=Ua(t.alertmanager_config),{contactPointsState:d,errorStateAvailable:g}=Ka(n),[m,p]=(0,e.useState)(),[f,h]=(0,e.useState)(!1),T=n===P.GC&&Ce.contextSrv.hasAccess(s.provisioning.read,(0,pe.RN)()),R=F=>{(0,Ta.nv)(F,t)?h(!0):p(F)},L=()=>{m&&a((0,D.X4)(m,n)),p(void 0)},A=(0,Wa.HU)(t.alertmanager_config.receivers??[]),O=(0,e.useMemo)(()=>A?.map(F=>({id:F.name,data:{name:F.name,types:Object.entries(Ra(F,c.result??[])).map(([j,q])=>q>1?`${j} (${q})`:j),grafanaAppReceiverType:F.grafanaAppReceiverType,provisioned:F.grafana_managed_receiver_configs?.some(j=>j.provenance)}}))??[],[c.result,A]),H=Xa(n,g,d,l,R,s,r);return e.createElement(Ct,{title:"Contact points",description:"Define where notifications are sent, for example, email or Slack.",showButton:!r&&Ce.contextSrv.hasPermission(s.create),addButtonLabel:"Add contact point",addButtonTo:(0,Z.eQ)("/alerting/notifications/receivers/new",n),exportLink:T?(0,bt.u)("/api/v1/provisioning/contact-points/export",{download:"true",format:"yaml",decrypt:(0,pe.RN)().toString()}):void 0},e.createElement(At.t,{items:O,cols:H,isExpandable:g,renderExpandedContent:g?({data:{name:F}})=>e.createElement(Ja,{notifiersState:d?.receivers[F]?.notifiers??{}}):void 0}),!!f&&e.createElement(ie.u,{isOpen:!0,title:"Cannot delete contact point",onDismiss:()=>h(!1)},e.createElement("p",null,"Contact point cannot be deleted because it is used in more policies. Please update or delete these policies first."),e.createElement(ie.u.ButtonRow,null,e.createElement(w.zx,{variant:"secondary",onClick:()=>h(!1),fill:"outline"},"Close"))),!!m&&e.createElement(Et.s,{isOpen:!0,title:"Delete contact point",body:`Are you sure you want to delete contact point "${m}"?`,confirmText:"Yes, delete",onConfirm:L,onDismiss:()=>p(void 0)}))},Ya=(t,n)=>t?.receivers[n]?.errorCount??0,Za=(t,n)=>{const a=Object.values(t?.receivers[n]?.notifiers??{});return a.length===0?!1:a.flat().some(s=>Se(s.lastNotifyAttempt))};function Xa(t,n,a,r,s,c,l){const d=(0,B.wW)(yt.D),g=n||Object.values(r.contactPoints).some(h=>h.matchingRoutes===0),m=t===P.GC,p=[{id:"name",label:"Contact point name",renderCell:({data:{name:h,provisioned:y}})=>e.createElement(e.Fragment,null,e.createElement("div",null,h),y&&e.createElement(ue.C0,null)),size:3,className:d.nameCell},{id:"type",label:"Type",renderCell:({data:{types:h,grafanaAppReceiverType:y}})=>e.createElement(e.Fragment,null,y?e.createElement(Ma,{grafanaAppType:y}):h.join(", ")),size:2}],f={id:"health",label:"Health",renderCell:({data:{name:h}})=>r.contactPoints[h]?.matchingRoutes===0?e.createElement(qa,null):a&&Object.entries(a.receivers).length>0&&e.createElement(za,{errorsByReceiver:Ya(a,h),someWithNoAttempt:Za(a,h)}),size:"160px"};return[...p,...g?[f]:[],{id:"actions",label:"Actions",renderCell:({data:{provisioned:h,name:y}})=>e.createElement(ae.q,{actions:[c.update,c.delete,c.provisioning.read],fallback:(0,pe.RN)()},e.createElement("div",{className:d.actionsCell},!l&&!h&&e.createElement(Fa,{permissions:c,alertManagerName:t,receiverName:y,onClickDeleteReceiver:s}),(l||h)&&e.createElement(Va,{permissions:c,alertManagerName:t,receiverName:y}),m&&e.createElement(Ba,{permissions:c,alertManagerName:t,receiverName:y}))),size:"100px"}]}function qa(){return e.createElement(ge.C,{text:"Unused",color:"orange",icon:"exclamation-triangle",tooltip:"This contact point is not used in any notification policy and it will not receive any alerts"})}var er=i(1333);const tr=({config:t,alertManagerName:n})=>{const a=(0,S.useDispatch)(),[r,s]=(0,e.useState)({}),c=(0,B.wW)(yt.D),l=(0,vt.Ko)(n),d=(0,e.useMemo)(()=>Object.entries(t.template_files).map(([h,y])=>({name:h,template:y,provenance:(t.template_file_provenances??{})[h]})),[t]),[g,m]=(0,e.useState)(),p=()=>{g&&a((0,D.S6)(g,n)),m(void 0)};return e.createElement(Ct,{title:"Notification templates",description:"Create notification templates to customize your notifications.",addButtonLabel:"Add template",addButtonTo:(0,Z.eQ)("/alerting/notifications/templates/new",n),showButton:Ce.contextSrv.hasPermission(l.create)},e.createElement("table",{className:c.table,"data-testid":"templates-table"},e.createElement("colgroup",null,e.createElement("col",{className:c.colExpand}),e.createElement("col",null),e.createElement("col",null)),e.createElement("thead",null,e.createElement("tr",null,e.createElement("th",null),e.createElement("th",null,"Template"),e.createElement(ae.q,{actions:[l.update,l.delete]},e.createElement("th",null,"Actions")))),e.createElement("tbody",null,!d.length&&e.createElement("tr",{className:c.evenRow},e.createElement("td",{colSpan:3},"No templates defined.")),d.map(({name:f,template:h,provenance:y},T)=>{const R=!!r[f];return e.createElement(e.Fragment,{key:f},e.createElement("tr",{key:f,className:T%2===0?c.evenRow:void 0},e.createElement("td",null,e.createElement(ot.U,{isCollapsed:!r[f],onToggle:()=>s({...r,[f]:!R})})),e.createElement("td",null,f," ",y&&e.createElement(ue.C0,null)),e.createElement("td",{className:c.actionsCell},y&&e.createElement(X.A,{to:(0,Z.eQ)(`/alerting/notifications/templates/${encodeURIComponent(f)}/edit`,n),tooltip:"view template",icon:"file-alt"}),!y&&e.createElement(ae.q,{actions:[l.update]},e.createElement(X.A,{to:(0,Z.eQ)(`/alerting/notifications/templates/${encodeURIComponent(f)}/edit`,n),tooltip:"edit template",icon:"pen"})),Ce.contextSrv.hasPermission(l.create)&&e.createElement(X.A,{to:(0,Z.eQ)(`/alerting/notifications/templates/${encodeURIComponent(f)}/duplicate`,n),tooltip:"Copy template",icon:"copy"}),!y&&e.createElement(ae.q,{actions:[l.delete]},e.createElement(X.A,{onClick:()=>m(f),tooltip:"delete template",icon:"trash-alt"})))),R&&e.createElement("tr",{className:T%2===0?c.evenRow:void 0},e.createElement("td",null),e.createElement("td",{colSpan:2},e.createElement(er.C,{label:"Description",horizontal:!0},e.createElement(Qe,{width:"auto",height:"auto",autoHeight:!0,value:h,showLineNumbers:!1,monacoOptions:{readOnly:!0,scrollBeyondLastLine:!1}})))))}))),!!g&&e.createElement(Et.s,{isOpen:!0,title:"Delete template",body:`Are you sure you want to delete template "${g}"?`,confirmText:"Yes, delete",onConfirm:p,onDismiss:()=>m(void 0)}))},nr=({config:t,alertManagerName:n})=>{const a=n!==P.GC,r=(0,P.RY)(n);return e.createElement(oe.K,{direction:"column",gap:4},e.createElement(Qa,{config:t,alertManagerName:n}),!r&&e.createElement(tr,{config:t,alertManagerName:n}),a&&e.createElement(ae.q,{actions:[S.AccessControlAction.AlertingNotificationsExternalWrite]},e.createElement(C.b,{severity:"info",title:"Global config for contact points"},e.createElement("p",null,"For each external Alertmanager you can define global settings, like server addresses, usernames and password, for all the supported contact points."),e.createElement(w.Qj,{href:(0,Z.eQ)("alerting/notifications/global-config",n),variant:"secondary"},r?"View global config":"Edit global config"))))},ar=()=>{const{selectedAlertmanager:t}=(0,V.Z)(),n=(0,S.useDispatch)(),{currentData:a,isLoading:r,error:s}=(0,N.W)(t),c=(0,E._)(l=>l.grafanaNotifiers);return(0,e.useEffect)(()=>{t===P.GC&&!(c.result||c.loading||c.error)&&n((0,D.Vj)())},[t,n,c]),t?e.createElement(e.Fragment,null,s&&!r&&e.createElement(C.b,{severity:"error",title:"Error loading Alertmanager config"},s.message||"Unknown error."),e.createElement(_.u,{currentAlertmanager:t}),r&&!a&&e.createElement(M.u,{text:"loading configuration..."}),a&&!s&&e.createElement(b.rs,null,e.createElement(b.AW,{exact:!0,path:"/alerting/notifications"},e.createElement(nr,{config:a,alertManagerName:t})),e.createElement(b.AW,{exact:!0,path:"/alerting/notifications/templates/new"},e.createElement(ya,{config:a,alertManagerSourceName:t})),e.createElement(b.AW,{exact:!0,path:"/alerting/notifications/templates/:name/duplicate"},({match:l})=>l?.params.name&&e.createElement(Pn,{alertManagerSourceName:t,config:a,templateName:decodeURIComponent(l?.params.name)})),e.createElement(b.AW,{exact:!0,path:"/alerting/notifications/templates/:name/edit"},({match:l})=>l?.params.name&&e.createElement(fa,{alertManagerSourceName:t,config:a,templateName:decodeURIComponent(l?.params.name)})),e.createElement(b.AW,{exact:!0,path:"/alerting/notifications/receivers/new"},e.createElement(Ea,{config:a,alertManagerSourceName:t})),e.createElement(b.AW,{exact:!0,path:"/alerting/notifications/receivers/:name/edit"},({match:l})=>l?.params.name&&e.createElement(ga,{alertManagerSourceName:t,config:a,receiverName:decodeURIComponent(l?.params.name)})),e.createElement(b.AW,{exact:!0,path:"/alerting/notifications/global-config"},e.createElement(ha,{config:a,alertManagerSourceName:t})))):null}},74023:(Y,U,i)=>{i.d(U,{Kt:()=>te,HU:()=>k});var e=i(78209),b=i(73289),C=i(16881);const M=C.C.injectEndpoints({endpoints:G=>({getOnCallIntegrations:G.query({queryFn:async()=>({data:await S()})})})});async function S(){try{return(await(0,e.n)((0,b.i)().fetch({url:"/api/plugin-proxy/grafana-oncall-app/api/internal/v1/alert_receive_channels/",showErrorAlert:!1,showSuccessAlert:!1}))).data.map(J=>J.integration_url)}catch{return[]}}const{useGetOnCallIntegrationsQuery:N}=M;var E=i(76393),V=i(62401);const D=(G,J)=>J.includes(G),P=(G,J)=>{if(!G.grafana_managed_receiver_configs)return!1;const u=G.grafana_managed_receiver_configs.length===1,ne=D(G.grafana_managed_receiver_configs[0]?.settings?.url??"",J);return u&&ne},_=()=>{const{installed:G}=(0,E.n)(V.W.OnCall),{data:J}=N(void 0,{skip:!G});return ne=>{if(G&&P(ne,J??[]))return V.W.OnCall}},te=G=>{const J=_(),u=ne=>({label:ne.name,value:ne.name,grafanaAppReceiverType:J(ne)});return G.map(u)},k=G=>{const J=_();return G.map(u=>({...u,grafanaAppReceiverType:J(u)}))}},51317:(Y,U,i)=>{i.d(U,{h:()=>E});var e=i(42844),b=i(27702),C=i(23852),M=i(66310),S=i(16532),N=i(73453);function E({contentText:D,externalLink:P,linkText:_,title:te}){const k=(0,M.wW)(V);return b.createElement(S.P,{content:b.createElement("div",{className:k.mutedText},D),title:b.createElement(C.K,{gap:1,direction:"row"},b.createElement(N.J,{name:"question-circle"}),te),footer:P?b.createElement("a",{href:P,target:"_blank",rel:"noreferrer"},b.createElement("div",{className:k.infoLink},_," ",b.createElement(N.J,{name:"external-link-alt"}))):void 0,closeButton:!0,placement:"bottom-start"},b.createElement("div",{className:k.helpInfo},b.createElement(N.J,{name:"question-circle"}),b.createElement("div",{className:k.helpInfoText},"Need help?")))}const V=D=>({mutedText:(0,e.css)` color: ${D.colors.text.secondary}; font-size: ${D.typography.size.sm}; `,helpInfo:(0,e.css)` display: flex; flex-direction: row; align-items: center; width: fit-content; font-weight: ${D.typography.fontWeightMedium}; margin-left: ${D.spacing(1)}; font-size: ${D.typography.size.sm}; cursor: pointer; color: ${D.colors.text.primary}; `,helpInfoText:(0,e.css)` margin-left: ${D.spacing(.5)}; text-decoration: underline; `,infoLink:(0,e.css)` color: ${D.colors.text.link}; `})},82669:(Y,U,i)=>{i.d(U,{z:()=>S});var e=i(42844),b=i(27702),C=i(66310),M=i(5229);const S=({title:E,stepNo:V,children:D,description:P})=>{const _=(0,C.wW)(N);return b.createElement("div",{className:_.parent},b.createElement("div",null,b.createElement("span",{className:_.stepNo},V)),b.createElement("div",{className:_.content},b.createElement(M.C,{label:E,className:_.fieldset},P&&b.createElement("div",{className:_.description},P),D)))},N=E=>({fieldset:(0,e.css)` legend { font-size: 16px; padding-top: ${E.spacing(.5)}; } `,parent:(0,e.css)` display: flex; flex-direction: row; max-width: ${E.breakpoints.values.xl}; & + & { margin-top: ${E.spacing(4)}; } `,description:(0,e.css)` margin-top: -${E.spacing(2)}; color: ${E.colors.text.secondary}; `,stepNo:(0,e.css)` display: inline-block; width: ${E.spacing(4)}; height: ${E.spacing(4)}; line-height: ${E.spacing(4)}; border-radius: ${E.shape.radius.circle}; text-align: center; color: ${E.colors.text.maxContrast}; background-color: ${E.colors.background.canvas}; font-size: ${E.typography.size.lg}; margin-right: ${E.spacing(2)}; `,content:(0,e.css)` flex: 1; `})},18686:(Y,U,i)=>{i.d(U,{A:()=>M});var e=i(27702),b=i(80011),C=i(66670);const M=({tooltip:S,icon:N,to:E,target:V,onClick:D,className:P,tooltipPlacement:_="top",...te})=>{const k=typeof S=="string"?S:void 0;return e.createElement(b.u,{content:S,placement:_},E?e.createElement(C.Qj,{variant:"secondary",fill:"text",icon:N,href:E,size:"sm",target:V,...te,"aria-label":k}):e.createElement(C.zx,{className:P,variant:"secondary",fill:"text",size:"sm",icon:N,type:"button",onClick:D,...te,"aria-label":k}))}},57117:(Y,U,i)=>{i.d(U,{r:()=>C,z:()=>M});var e=i(89949),b=i.n(e);function C(S,N){return S.filter(E=>!N.find(V=>JSON.stringify(V)===JSON.stringify(E)))}function M(S){const N=S.flatMap(V=>V);return(0,e.uniqBy)(N.filter(V=>N.filter(P=>(0,e.isEqual)(V,P)).length===Object.keys(S).length),V=>JSON.stringify(V))}},97529:(Y,U,i)=>{i.d(U,{W:()=>b});var e=i(52646);function b(C,M){const S=e.alertmanagerApi.endpoints.getAlertmanagerConfiguration.useQuery(C??"",{...M,skip:!C});return{...S,error:S.error}}},38338:(Y,U,i)=>{i.d(U,{D:()=>b});var e=i(42844);const b=C=>({table:(0,e.css)` width: 100%; border-radius: ${C.shape.borderRadius()}; border: solid 1px ${C.colors.border.weak}; background-color: ${C.colors.background.secondary}; th { padding: ${C.spacing(1)}; } td { padding: 0 ${C.spacing(1)}; } tr { height: 38px; } `,evenRow:(0,e.css)` background-color: ${C.colors.background.primary}; `,colExpand:(0,e.css)` width: 36px; `,nameCell:(0,e.css)` gap: ${C.spacing(1)}; `,actionsCell:(0,e.css)` text-align: right; width: 1%; white-space: nowrap; & > * + * { margin-left: ${C.spacing(.5)}; } `})}}]); //# sourceMappingURL=1518.faa2d2f9ab7416f28bc6.js.map