"use strict";(self.webpackChunkgrafana=self.webpackChunkgrafana||[]).push([[6618],{63634:(G,S,o)=>{o.r(S),o.d(S,{default:()=>M});var c=o(65237),C=o(98866),b=o(55041),e=o(48389),v=o(6741),T=o(76044),h=o(38992),R=o(63969),D=o(2570),I=o(91063);const M=()=>{const $=(0,D.q)("channels"),[P,L]=(0,c.useState)([]),z=async()=>await(0,b.i)().get("/api/alert-notifications"),[j,le]=(0,C.Z)(z);(0,c.useEffect)(()=>{le().then(B=>{L(B)})},[le]);const Z=B=>{R.h$.publish(new I.VJ({title:"Delete",text:"Do you want to delete this notification channel?",text2:"Deleting this notification channel will not delete from alerts any references to it",icon:"trash-alt",confirmText:"Delete",yesText:"Delete",onConfirm:async()=>{be(B)}}))},be=async B=>{await(0,b.i)().delete(`/api/alert-notifications/${B}`);const V=await le();L(V)};return c.createElement(h.T,{navModel:$},c.createElement(h.T.Contents,null,j.error&&c.createElement("p",null,j.error),!!P.length&&c.createElement(c.Fragment,null,c.createElement("div",{className:"page-action-bar"},c.createElement("div",{className:"page-action-bar__spacer"}),c.createElement(e.Qj,{icon:"channel-add",href:"alerting/notification/new"},"New channel")),c.createElement("table",{className:"filter-table filter-table--hover"},c.createElement("thead",null,c.createElement("tr",null,c.createElement("th",{style:{minWidth:"200px"}},c.createElement("strong",null,"Name")),c.createElement("th",{style:{minWidth:"100px"}},"Type"),c.createElement("th",{style:{width:"1%"}}))),c.createElement("tbody",null,P.map(B=>c.createElement("tr",{key:B.id},c.createElement("td",{className:"link-td"},c.createElement("a",{href:`alerting/notification/${B.id}/edit`},B.name)),c.createElement("td",{className:"link-td"},c.createElement("a",{href:`alerting/notification/${B.id}/edit`},B.type)),c.createElement("td",{className:"text-right"},c.createElement(v.Lh,{justify:"flex-end"},B.isDefault&&c.createElement(e.zx,{disabled:!0,variant:"secondary",size:"sm"},"default"),c.createElement(e.zx,{variant:"destructive",icon:"times",size:"sm",onClick:()=>{Z(B.id)}})))))))),!(P.length||j.loading)&&c.createElement(T.Z,{title:"There are no notification channels defined yet",buttonIcon:"channel-add",buttonLink:"alerting/notification/new",buttonTitle:"Add channel",proTip:"You can include images in your alert notifications.",proTipLink:"http://docs.grafana.org/alerting/notifications/",proTipLinkTitle:"Learn more",proTipTarget:"_blank"})))}},2792:(G,S,o)=>{o.r(S),o.d(S,{default:()=>fa});var c=o(60234),C=o(6772),b=o.n(C),e=o(65237),v=o(60894),T=o(66917),h=o(93048),R=o(6335),D=o(88347),I=o(16693),w=o(22193),M=o(3315),$=o(72400),P=o(70755),L=o(58866),z=o(8798),j=o(31222),le=o(97909),Z=o(89949);function be(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 B(t){const n=(a,r)=>`{{ define "${r}_NEW_${(0,Z.now)()}" }}`;return t.replace(/\{\{\s*define\s*\"(?<defineName>.*)\"\s*\}\}/g,n)}var V=o(89822),mt=o(55925),ut=o(37885),te=o(5263),ie=o(96682),O=o(48389),Ae=o(41090),ne=o(57811),ee=o(99997),Y=o(78442),fe=o(84078),ce=o(89745),Oe=o(3841);const pt=[{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."}],gt=[{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."}],ft=[{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"}],ht=`{
  "summary": "alert summary",
  "description": "alert description"
}
`;function Et(){const t=(0,h.wW)(yt),n=e.createElement(Ie,{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:gt});return e.createElement(T.Stack,{gap:2,flexGrow:1},e.createElement(Ie,{caption:e.createElement("h4",{className:t.header},"Template Data"),dataItems:pt,typeRenderer:a=>a==="[]Alert"?e.createElement(Oe.z,{content:n},e.createElement("div",{className:t.interactiveType},a)):a==="KeyValue"?e.createElement(Oe.z,{content:e.createElement(vt,null)},e.createElement("div",{className:t.interactiveType},a)):a}))}const yt=t=>({header:c.css`
    color: ${t.colors.text.primary};

    span {
      color: ${t.colors.text.secondary};
      font-size: ${t.typography.bodySmall.fontSize};
    }
  `,interactiveType:c.css`
    color: ${t.colors.text.link};
  `});function Ie({dataItems:t,caption:n,typeRenderer:a}){const r=(0,h.wW)(Ne);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:i,notes:d},u)=>e.createElement("tr",{key:u},e.createElement("td",null,s),e.createElement("td",null,a?a(i):i),e.createElement("td",null,d)))))}function vt(){const t=(0,h.wW)(Ne);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,ht)),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,ft.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 Ne=t=>({table:c.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 bt=o(73383),ae=o(39077);function At(t){const n=t.languages.CompletionItemKind.Function;return[{label:ae.AlertmanagerTemplateFunction.toUpper,detail:"function(s string)",kind:n},{label:ae.AlertmanagerTemplateFunction.toLower,detail:"function(s string)",kind:n},{label:ae.AlertmanagerTemplateFunction.title,documentation:"Capitalizes the first letter of each word",detail:"function(s string)",kind:n},{label:ae.AlertmanagerTemplateFunction.join,documentation:{value:"Joins an array of strings using the separator provided."},detail:"function(separator string, s []string)",kind:n},{label:ae.AlertmanagerTemplateFunction.match,detail:"function",kind:n},{label:ae.AlertmanagerTemplateFunction.safeHtml,detail:"function(pattern, repl, text)",kind:n},{label:ae.AlertmanagerTemplateFunction.reReplaceAll,detail:"function(pattern, repl, text)",kind:n},{label:ae.AlertmanagerTemplateFunction.stringSlice,detail:"function(s ...string)",kind:n}]}const Ct=`
{{ range .Alerts }}
  Status: {{ .Status }}
  Starts at: {{ .StartsAt }}
{{ end }}
`,Tt=`
[{{.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 }}
`,St=me("GroupLabels"),Pt=me("CommonLabels"),Rt=me("CommonAnnotations"),Dt=me("Labels"),xt=me("Annotations");function me(t){return`
{{ range .${t} }}
  {{ .Name }} = {{ .Value }}
{{ end }}`}function Mt(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 Lt(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 Ot(t){const n=t.languages.CompletionItemKind.Field;return[{label:"Firing",kind:n,detail:"Alert[]"},{label:"Resolved",kind:n,detail:"Alert[]"}]}function It(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 we={alerts:{label:"alertsloop",description:"Renders a loop through alerts",snippet:Ct},alertDetails:{label:"alertdetails",description:"Renders all information available about the alert",snippet:Tt},groupLabels:{label:"grouplabelsloop",description:"Renders a loop through group labels",snippet:St},commonLabels:{label:"commonlabelsloop",description:"Renders a loop through common labels",snippet:Pt},commonAnnotations:{label:"commonannotationsloop",description:"Renders a loop through common annotations",snippet:Rt},labels:{label:"labelsloop",description:"Renders a loop through labels",snippet:Dt},annotations:{label:"annotationsloop",description:"Renders a loop through annotations",snippet:xt}};function Nt(t){const n=t.languages.CompletionItemKind.Snippet,a=t.languages.CompletionItemInsertTextRule.InsertAsSnippet,{alerts:r,alertDetails:s,groupLabels:i,commonLabels:d,commonAnnotations:u,labels:f,annotations:m}=we;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:i.label,documentation:i.description,kind:n,insertText:i.snippet,insertTextRules:a},{label:d.label,documentation:d.description,kind:n,insertText:d.snippet,insertTextRules:a},{label:u.label,documentation:u.description,kind:n,insertText:u.snippet,insertTextRules:a},{label:{label:f.label,detail:"(Alert)"},documentation:f.description,kind:n,insertText:f.snippet,insertTextRules:a},{label:{label:m.label,detail:"(Alert)"},documentation:m.description,kind:n,insertText:m.snippet,insertTextRules:a}]}function wt(t){const n={triggerCharacters:["."],provideCompletionItems(a,r,s){const i=a.getWordUntilPosition(r),d={startLineNumber:r.lineNumber,endLineNumber:r.lineNumber,startColumn:i.startColumn,endColumn:i.endColumn},u=new _t(t,d);if(!$t(a,r))return u.getSnippetsSuggestions();if(s.triggerKind===t.languages.CompletionTriggerKind.Invoke&&!s.triggerCharacter)return u.getFunctionsSuggestions();const m=a.getWordUntilPosition({lineNumber:r.lineNumber,column:r.column-1});return u.getTemplateDataSuggestions(m.word)}};return t.languages.registerCompletionItemProvider("go-template",n)}function $t(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(i=>i.range.containsPosition(n))}class _t{constructor(n,a){this.monaco=n,this.range=a,this.getSnippetsSuggestions=()=>this.getCompletionsFromDefinitions(Nt(this.monaco)),this.getFunctionsSuggestions=()=>this.getCompletionsFromDefinitions(At(this.monaco)),this.getTemplateDataSuggestions=r=>{switch(r){case"":return this.getCompletionsFromDefinitions(Mt(this.monaco),Lt(this.monaco));case"Alerts":return this.getCompletionsFromDefinitions(Ot(this.monaco));case"GroupLabels":case"CommonLabels":case"CommonAnnotations":case"Labels":case"Annotations":return this.getCompletionsFromDefinitions(It(this.monaco));default:return{suggestions:[]}}},this.getCompletionsFromDefinitions=(...r)=>({suggestions:(0,Z.concat)(...r).map(i=>kt(i,this.range))})}}function kt({label:t,detail:n,documentation:a,kind:r,insertText:s},i){const d=typeof t=="string"?t:t.label,u=typeof t=="string"?{label:t,description:n}:{...t};return u.description??=n,{label:u,kind:r,insertText:s??d,range:i,documentation:a,detail:n}}const $e="go-template",Wt={id:$e,extensions:[],aliases:[],mimetypes:[],loader:()=>Promise.resolve().then(o.bind(o,39077))},Ut=(t,n)=>{const{id:a,loader:r}=n;t.languages.getLanguages().find(i=>i.id===a)||(t.languages.register({id:a}),r().then(i=>{t.languages.setMonarchTokensProvider(a,i.language),t.languages.setLanguageConfiguration(a,i.conf)}))},_e=t=>{const n=Boolean(t.autoHeight),a=(0,e.useRef)(null),r=s=>{if(n){const i=s.getContentHeight();try{s.layout({height:i,width:NaN})}catch{}}};return(0,e.useEffect)(()=>()=>{a.current?.dispose()},[]),e.createElement(bt.p,{showLineNumbers:!0,showMiniMap:!1,...t,onEditorDidMount:r,onBeforeEditorMount:s=>{Ut(s,Wt),a.current=wt(s)},language:$e})},Ft=Object.freeze({name:"",content:""}),ke=t=>t.pathname.endsWith("/duplicate"),Ce=({existing:t,alertManagerSourceName:n,config:a,provenance:r})=>{const s=(0,h.wW)(We),i=(0,M.useDispatch)();(0,Ae.x)(y=>y.unifiedAlerting.saveAMConfig=fe.oq);const{loading:d,error:u}=(0,ne._)(y=>y.saveAMConfig),f=(0,v.TH)(),m=ke(f),g=y=>{const W=be(y.name,y.content),U={...a.template_files,[y.name]:W};t&&t.name!==y.name&&delete U[t.name];const J=[...(a.alertmanager_config.templates??[]).filter(de=>de!==t?.name),y.name],_={template_files:U,alertmanager_config:{...a.alertmanager_config,templates:J}};i((0,ee.mM)({alertManagerSourceName:n,newConfig:_,oldConfig:a,successMessage:"Template saved.",redirectPath:"/alerting/notifications"}))},{handleSubmit:p,register:E,formState:{errors:A},getValues:x,setValue:N}=(0,V.cI)({mode:"onSubmit",defaultValues:t??Ft}),H=y=>!a.template_files[y]||t?.name===y?!0:"Another template with this name already exists.";return e.createElement("form",{onSubmit:p(g)},e.createElement("h4",null,t&&!m?"Edit notification template":"Create notification template"),u&&e.createElement(D.b,{severity:"error",title:"Error saving template"},u.message||u?.data?.message||String(u)),r&&e.createElement(ce.Xq,{resource:ce.Uv.Template}),e.createElement(ut.C,{disabled:Boolean(r)},e.createElement(te.g,{label:"Template name",error:A?.name?.message,invalid:!!A.name?.message,required:!0},e.createElement(ie.I,{...E("name",{required:{value:!0,message:"Required."},validate:{nameIsUnique:H}}),placeholder:"Give your template a name",width:42,autoFocus:!0})),e.createElement(Vt,null),e.createElement("div",{className:s.contentContainer},e.createElement("div",null,e.createElement(te.g,{label:"Content",error:A?.content?.message,invalid:!!A.content?.message,required:!0},e.createElement("div",{className:s.editWrapper},e.createElement(mt.Z,null,({width:y,height:W})=>e.createElement(_e,{value:x("content"),width:y,height:W,onBlur:U=>N("content",U)})))),e.createElement("div",{className:s.buttons},d&&e.createElement(O.zx,{disabled:!0,icon:"fa fa-spinner",variant:"primary"},"Saving..."),!d&&e.createElement(O.zx,{type:"submit",variant:"primary"},"Save template"),e.createElement(O.Qj,{disabled:d,href:(0,Y.eQ)("alerting/notifications",n),variant:"secondary",type:"button",fill:"outline"},"Cancel"))),e.createElement(Et,null))))};function Vt(){const t=(0,h.wW)(We);return e.createElement(D.b,{title:"Templating guideline",severity:"info"},e.createElement(T.Stack,{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(O.Qj,{href:"https://grafana.com/docs/grafana/latest/alerting/manage-notifications/template-notifications/",target:"_blank",icon:"external-link-alt"},"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(we).map(n=>n.label).join(", "))))}const We=t=>({contentContainer:c.css`
    display: flex;
    gap: ${t.spacing(2)};
    flex-direction: row;
    align-items: flex-start;
    flex-wrap: wrap;
    ${t.breakpoints.up("xxl")} {
      flex-wrap: nowrap;
    }
  `,snippets:c.css`
    margin-top: ${t.spacing(2)};
    font-size: ${t.typography.bodySmall.fontSize};
  `,code:c.css`
    color: ${t.colors.text.secondary};
    font-weight: ${t.typography.fontWeightBold};
  `,buttons:c.css`
    & > * + * {
      margin-left: ${t.spacing(1)};
    }
  `,textarea:c.css`
    max-width: 758px;
  `,editWrapper:c.css`
    display: block;
    position: relative;
    width: 640px;
    height: 320px;
  `}),Gt=({config:t,templateName:n,alertManagerSourceName:a})=>{const r=t.template_files?.[n];if(!r)return e.createElement(D.b,{severity:"error",title:"Template not found"},"Sorry, this template does not seem to exists.");const s=(0,le.G)(n,Object.keys(t.template_files));return e.createElement(Ce,{alertManagerSourceName:a,config:t,existing:{name:s,content:B(r)}})};var X=o(50328);function l(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 Bt=l("basic_auth","Basic auth","Sets the `Authorization` header with the configured username and password. Password and password_file are mutually exclusive.",{element:"subform",subformOptions:[l("username","Username",""),l("password","Password",""),l("password_file","Password file","")]}),Ue=l("tls_config","TLS config","Configures the TLS settings.",{element:"subform",subformOptions:[l("ca_file","CA file","CA certificate to validate the server certificate with."),l("cert_file","Cert file","Certificate for client cert authentication to the server."),l("key_file","Key file","Key file for client cert authentication to the server."),l("server_name","Server name","ServerName extension to indicate the name of the server."),l("insecure_skip_verify","Skip verify","Disable validation of the server certificate.",{element:"checkbox"})]}),re=l("http_config","HTTP Config","Note that `basic_auth`, `bearer_token` and `bearer_token_file` options are mutually exclusive.",{element:"subform",subformOptions:[l("bearer_token","Bearer token","Sets the `Authorization` header with the configured bearer token."),l("bearer_token_file","Bearer token file","Sets the `Authorization` header with the bearer token read from the configured file."),l("proxy_url","Proxy URL","Optional proxy URL."),Bt,Ue]}),Fe=[{name:"Email",description:"Send notification over SMTP",type:"email",info:"",heading:"Email settings",options:[l("to","To","The email address to send notifications to.",{required:!0}),l("from","From","The sender address."),l("smarthost","SMTP host","The SMTP host through which emails are sent."),l("hello","Hello","The hostname to identify to the SMTP server."),l("auth_username","Username","SMTP authentication information"),l("auth_password","Password","SMTP authentication information"),l("auth_secret","Secret","SMTP authentication information"),l("auth_identity","Identity","SMTP authentication information"),l("require_tls","Require TLS","The SMTP TLS requirement",{element:"checkbox"}),l("html","Email HTML body","The HTML body of the email notification.",{placeholder:'{{ template "email.default.html" . }}',element:"textarea"}),l("text","Email text body","The text body of the email notification.",{element:"textarea"}),l("headers","Headers","Further headers email header key/value pairs. Overrides any headers previously set by the notification implementation.",{element:"key_value_map"}),Ue]},{name:"PagerDuty",description:"Send notifications to PagerDuty",type:"pagerduty",info:"",heading:"PagerDuty settings",options:[l("routing_key","Routing key","The PagerDuty integration key (when using PagerDuty integration type `Events API v2`)"),l("service_key","Service key","The PagerDuty integration key (when using PagerDuty integration type `Prometheus`)."),l("url","URL","The URL to send API requests to"),l("client","Client","The client identification of the Alertmanager.",{placeholder:'{{ template "pagerduty.default.client" . }}'}),l("client_url","Client URL","A backlink to the sender of the notification.",{placeholder:'{{ template "pagerduty.default.clientURL" . }}'}),l("description","Description","A description of the incident.",{placeholder:'{{ template "pagerduty.default.description" .}}'}),l("severity","Severity","Severity of the incident.",{placeholder:"error"}),l("details","Details","A set of arbitrary key/value pairs that provide further detail about the incident.",{element:"key_value_map"}),l("images","Images","Images to attach to the incident.",{element:"subform_array",subformOptions:[l("href","URL","",{required:!0}),l("source","Source","",{required:!0}),l("alt","Alt","",{required:!0})]}),l("links","Links","Links to attach to the incident.",{element:"subform_array",subformOptions:[l("href","URL","",{required:!0}),l("text","Text","",{required:!0})]}),re]},{name:"Pushover",description:"Send notifications to Pushover",type:"pushover",info:"",heading:"Pushover settings",options:[l("user_key","User key","The recipient user\u2019s user key.",{required:!0}),l("token","Token","Your registered application\u2019s API token, see https://pushover.net/app",{required:!0}),l("title","Title","Notification title.",{placeholder:'{{ template "pushover.default.title" . }}'}),l("message","Message","Notification message.",{placeholder:'{{ template "pushover.default.message" . }}'}),l("url","URL","A supplementary URL shown alongside the message.",{placeholder:'{{ template "pushover.default.url" . }}'}),l("priority","Priority","Priority, see https://pushover.net/api#priority",{placeholder:'{{ if eq .Status "firing" }}2{{ else }}0{{ end }}'}),l("retry","Retry","How often the Pushover servers will send the same notification to the user. Must be at least 30 seconds.",{placeholder:"1m"}),l("expire","Expire","How long your notification will continue to be retried for, unless the user acknowledges the notification.",{placeholder:"1h"}),re]},{name:"Slack",description:"Send notifications to Slack",type:"slack",info:"",heading:"Slack settings",options:[l("api_url","Webhook URL","The Slack webhook URL."),l("channel","Channel","The #channel or @user to send notifications to.",{required:!0}),l("icon_emoji","Emoji icon",""),l("icon_url","Icon URL",""),l("link_names","Names link","",{element:"checkbox"}),l("username","Username","",{placeholder:'{{ template "slack.default.username" . }}'}),l("callback_id","Callback ID","",{placeholder:'{{ template "slack.default.callbackid" . }}'}),l("color","Color","",{placeholder:'{{ if eq .Status "firing" }}danger{{ else }}good{{ end }}'}),l("fallback","Fallback","",{placeholder:'{{ template "slack.default.fallback" . }}'}),l("footer","Footer","",{placeholder:'{{ template "slack.default.footer" . }}'}),l("mrkdwn_in","Mrkdwn fields","An array of field names that should be formatted by mrkdwn syntax.",{element:"string_array"}),l("pretext","Pre-text","",{placeholder:'{{ template "slack.default.pretext" . }}'}),l("short_fields","Short fields","",{element:"checkbox"}),l("text","Message body","",{element:"textarea",placeholder:'{{ template "slack.default.text" . }}'}),l("title","Title","",{placeholder:'{{ template "slack.default.title" . }}'}),l("title_link","Title link","",{placeholder:'{{ template "slack.default.titlelink" . }}'}),l("image_url","Image URL",""),l("thumb_url","Thumbnail URL",""),l("actions","Actions","",{element:"subform_array",subformOptions:[l("text","Text","",{required:!0}),l("type","Type","",{required:!0}),l("url","URL","Either url or name and value are mandatory."),l("name","Name",""),l("value","Value",""),l("confirm","Confirm","",{element:"subform",subformOptions:[l("text","Text","",{required:!0}),l("dismiss_text","Dismiss text",""),l("ok_text","OK text",""),l("title","Title","")]}),l("style","Style","")]}),l("fields","Fields","",{element:"subform_array",subformOptions:[l("title","Title","",{required:!0}),l("value","Value","",{required:!0}),l("short","Short","",{element:"checkbox"})]}),re]},{name:"OpsGenie",description:"Send notifications to OpsGenie",type:"opsgenie",info:"",heading:"OpsGenie settings",options:[l("api_key","API key","The API key to use when talking to the OpsGenie API."),l("api_url","API URL","The host to send OpsGenie API requests to."),l("message","Message","Alert text limited to 130 characters."),l("description","Description","A description of the incident.",{placeholder:'{{ template "opsgenie.default.description" . }}'}),l("source","Source","A backlink to the sender of the notification.",{placeholder:'{{ template "opsgenie.default.source" . }}'}),l("details","Details","A set of arbitrary key/value pairs that provide further detail about the incident.",{element:"key_value_map"}),l("tags","Tags","Comma separated list of tags attached to the notifications."),l("note","Note","Additional alert note."),l("priority","Priority","Priority level of alert. Possible values are P1, P2, P3, P4, and P5."),l("responders","Responders","List of responders responsible for notifications.",{element:"subform_array",subformOptions:[l("type","Type",'"team", "user", "escalation" or schedule".',{required:!0}),l("id","ID","Exactly one of these fields should be defined."),l("name","Name","Exactly one of these fields should be defined."),l("username","Username","Exactly one of these fields should be defined.")]}),re]},{name:"VictorOps",description:"Send notifications to VictorOps",type:"victorops",info:"",heading:"VictorOps settings",options:[l("api_key","API key","The API key to use when talking to the VictorOps API."),l("api_url","API URL","The VictorOps API URL."),l("routing_key","Routing key","A key used to map the alert to a team.",{required:!0}),l("message_type","Message type","Describes the behavior of the alert (CRITICAL, WARNING, INFO)."),l("entity_display_name","Entity display name","Contains summary of the alerted problem.",{placeholder:'{{ template "victorops.default.entity_display_name" . }}'}),l("state_message","State message","Contains long explanation of the alerted problem.",{placeholder:'{{ template "victorops.default.state_message" . }}'}),l("monitoring_tool","Monitoring tool","The monitoring tool the state message is from.",{placeholder:'{{ template "victorops.default.monitoring_tool" . }}'}),re]},{name:"Webhook",description:"Send notifications to a webhook",type:"webhook",info:"",heading:"Webhook settings",options:[l("url","URL","The endpoint to send HTTP POST requests to.",{required:!0}),l("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+$|^$)"}),re]},{name:"Discord",description:"Sends notifications to Discord",type:"discord",info:"",heading:"Discord settings",options:[l("title","Title","Templated title of the message",{placeholder:'{{ template "discord.default.title" . }}'}),l("message","Message Content","Mention a group using @ or a user using <@ID> when notifying in a channel",{placeholder:'{{ template "discord.default.message" . }}'}),l("webhook_url","Webhook URL","",{placeholder:"Discord webhook URL",required:!0}),re]}],Kt=[l("smtp_from","SMTP from","The default SMTP From header field."),l("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"),l("smtp_hello","SMTP hello","The default hostname to identify to the SMTP server.",{placeholder:"localhost"}),l("smtp_auth_username","SMTP auth username","SMTP Auth using CRAM-MD5, LOGIN and PLAIN. If empty, Alertmanager doesn't authenticate to the SMTP server."),l("smtp_auth_password","SMTP auth password","SMTP Auth using LOGIN and PLAIN."),l("smtp_auth_identity","SMTP auth identity","SMTP Auth using PLAIN."),l("smtp_auth_secret","SMTP auth secret","SMTP Auth using CRAM-MD5."),l("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"}),l("slack_api_url","Slack API URL",""),l("victorops_api_key","VictorOps API key",""),l("victorops_api_url","VictorOps API URL","",{placeholder:"https://alert.victorops.com/integrations/generic/20131114/alert/"}),l("pagerduty_url","PagerDuty URL","https://events.pagerduty.com/v2/enqueue"),l("opsgenie_api_key","OpsGenie API key",""),l("opsgenie_api_url","OpsGenie API URL","",{placeholder:"https://api.opsgenie.com/"}),l("wechat_api_url","WeChat API URL","",{placeholder:"https://qyapi.weixin.qq.com/cgi-bin/"}),l("wechat_api_secret","WeChat API secret",""),l("wechat_api_corp_id","WeChat API corp id",""),re,l("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 zt(t,n){const a={};let r=1;return[{name:t.name,items:t.grafana_managed_receiver_configs?.map(i=>{const d=String(r++);a[d]=i;const u=n.find(({type:f})=>f===i.type);return Jt(d,i,u)})??[]},a]}function jt(t,n){const a={};let r=1;const s=Object.entries(t).filter(([d])=>d.endsWith("_configs")&&d!=="grafana_managed_receiver_configs").map(([d,u])=>[d.replace("_configs",""),u]).map(([d,u])=>u.map(f=>{const m=String(r++);if(a[m]={type:d,config:f},!n.find(p=>p.type===d))throw new Error(`unknown cloud notifier: ${d}`);return Yt(m,d,f)})).flat();return[{name:t.name,items:s},a]}function Ht(t,n,a){return{name:t.name,grafana_managed_receiver_configs:(t.items??[]).map(r=>{const s=n[r.__id];return Be(r,a,t.name,s)})}}function Qt(t,n){const a={name:t.name};return t.items.forEach(({__id:r,type:s,settings:i,sendResolved:d})=>{const u=ue({...i,send_resolved:d??n.sendResolved}),f=`${s}_configs`;a[f]?a[f].push(u):a[f]=[u]}),a}function Ve(t,n,a){const r=t.alertmanager_config.receivers??[];if(n.name!==a&&r.find(({name:i})=>i===n.name))throw new Error(`Duplicate receiver name ${n.name}`);if(a&&!r.find(({name:i})=>i===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(i=>i.name===a?n:i):[...r,n]}};return s.alertmanager_config.route&&a&&n.name!==a&&(s.alertmanager_config.route=Ge(s.alertmanager_config.route,a,n.name)),s}function Ge(t,n,a){const r={...t};return r.receiver===n&&(r.receiver=a),r.routes&&(r.routes=r.routes.map(s=>Ge(s,n,a))),r}function Yt(t,n,a){return{__id:t,type:n,settings:{...a},secureFields:{},secureSettings:{},sendResolved:a.send_resolved}}function Jt(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 Be(t,n,a,r){const s={settings:ue({...r&&r.type===t.type?r.settings??{}:{},...t.settings??{}}),secureSettings:t.secureSettings??{},type:t.type,name:a,disableResolveMessage:t.disableResolveMessage??r?.disableResolveMessage??n.disableResolveMessage};return r&&(s.uid=r.uid),s}function ue(t){return(0,Z.isArray)(t)?t.forEach(ue):typeof t=="object"&&t!==null&&Object.entries(t).forEach(([n,a])=>{a===""||a===null||a===void 0?delete t[n]:ue(a)}),t}var Te=o(58190);const Zt=({pathPrefix:t,className:n,readOnly:a=!1})=>{const{register:r}=(0,V.Gc)();return e.createElement("div",{className:n},e.createElement(te.g,{disabled:a},e.createElement(Te.X,{...r(`${t}sendResolved`),label:"Send resolved",disabled:a,description:"Whether or not to notify about resolved alerts."})))};var Xt=o(93589);const qt=[];function Ke(t){const{name:n,formAPI:a,defaults:r,softDelete:s}=t,{watch:i,getValues:d,reset:u,setValue:f}=a,m=i(n)??r??qt,g=(0,e.useCallback)(p=>{const E=JSON.parse(JSON.stringify(d())),A=p(m??[]);u((0,Z.set)(E,n,A))},[d,n,u,m]);return{fields:m,append:(0,e.useCallback)(p=>g(E=>[...E,p]),[g]),remove:(0,e.useCallback)(p=>{s?f(`${n}.${p}.__deleted`,!0):g(E=>{const A=E.slice();return A.splice(p,1),A})},[g,n,f,s])}}var he=o(58102),ze=o(94795),en=o(15446),q=o(23719);const tn=({value:t,onChange:n,readOnly:a=!1})=>{const r=(0,h.wW)(nn),[s,i]=(0,e.useState)(je(t));(0,e.useEffect)(()=>i(je(t)),[t]);const d=m=>{n(an(m))},u=m=>{const g=s.slice(),p=g.splice(m,1)[0];i(g),p[0]&&d(g)},f=(m,g)=>{const p=s[g],E=s.map((A,x)=>x===g?m:A);i(E),(m[0]||p[0])&&d(E)};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,g],p)=>e.createElement("tr",{key:p},e.createElement("td",null,e.createElement(ie.I,{readOnly:a,value:m,onChange:E=>f([E.currentTarget.value,g],p)})),e.createElement("td",null,e.createElement(ie.I,{readOnly:a,value:g,onChange:E=>f([m,E.currentTarget.value],p)})),!a&&e.createElement("td",null,e.createElement(q.A,{icon:"trash-alt",tooltip:"delete",onClick:()=>u(p)})))))),!a&&e.createElement(O.zx,{className:r.addButton,type:"button",variant:"secondary",icon:"plus",size:"sm",onClick:()=>i([...s,["",""]])},"Add"))},nn=t=>({addButton:c.css`
    margin-top: ${t.spacing(1)};
  `,table:c.css`
    tbody td {
      padding: 0 ${t.spacing(1)} ${t.spacing(1)} 0;
    }
  `}),an=t=>{const n={};for(const[a,r]of t)a&&(n[a]=r);return n},je=t=>Object.entries(t??{}),rn=({value:t,onChange:n,readOnly:a=!1})=>{const r=(0,h.wW)(on),s=d=>{if(!t)return;const u=t.slice();u.splice(d,1),n(u)},i=(d,u)=>{t&&n(t.map((f,m)=>m===u?d:f))};return e.createElement("div",null,!!t?.length&&t.map((d,u)=>e.createElement("div",{key:u,className:r.row},e.createElement(ie.I,{readOnly:a,value:d,onChange:f=>i(f.currentTarget.value,u)}),!a&&e.createElement(q.A,{className:r.deleteIcon,icon:"trash-alt",tooltip:"delete",onClick:()=>s(u)}))),!a&&e.createElement(O.zx,{className:r.addButton,type:"button",variant:"secondary",icon:"plus",size:"sm",onClick:()=>n([...t??[],""])},"Add"))},on=t=>({row:c.css`
    display: flex;
    flex-direction: row;
    margin-bottom: ${t.spacing(1)};
    align-items: center;
  `,deleteIcon:c.css`
    margin-left: ${t.spacing(1)};
  `,addButton:c.css`
    margin-top: ${t.spacing(1)};
  `});var He=o(62567);const Se=({label:t,description:n,children:a,className:r,size:s="xl"})=>{const i=(0,h.wW)(sn),[d,u]=(0,e.useState)(!0),f=()=>u(!d);return e.createElement("div",{className:(0,c.cx)(i.wrapper,r)},e.createElement(He.U,{className:i.toggle,size:s,onToggle:f,isCollapsed:d,text:t}),n&&e.createElement("p",{className:i.description},n),e.createElement("div",{className:d?i.hidden:i.content},a))},sn=t=>({wrapper:c.css`
    margin-top: ${t.spacing(1)};
    padding-bottom: ${t.spacing(1)};
  `,toggle:c.css`
    margin: ${t.spacing(1,0)};
    padding: 0;
  `,hidden:c.css`
    display: none;
  `,description:c.css`
    color: ${t.colors.text.secondary};
    font-size: ${t.typography.size.sm};
    font-weight: ${t.typography.fontWeightRegular};
    margin: 0;
  `,content:c.css`
    padding-left: ${t.spacing(3)};
  `}),Qe=t=>({collapsibleSection:c.css`
    margin: 0;
    padding: 0;
  `,wrapper:c.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:c.css`
    color: ${t.colors.text.secondary};
    font-size: ${t.typography.size.sm};
    font-weight: ${t.typography.fontWeightRegular};
    margin: 0;
  `,deleteIcon:c.css`
    position: absolute;
    right: ${t.spacing(1)};
    top: ${t.spacing(1)};
  `,addButton:c.css`
    margin-top: ${t.spacing(1)};
  `}),ln=({option:t,pathPrefix:n,errors:a,defaultValues:r,readOnly:s=!1})=>{const i=(0,h.wW)(Qe),d=`${n}${t.propertyName}`,u=(0,V.Gc)(),{fields:f,append:m,remove:g}=Ke({name:d,formAPI:u,defaults:r});return e.createElement("div",{className:i.wrapper},e.createElement(Se,{className:i.collapsibleSection,label:`${t.label} (${f.length})`,description:t.description},(f??r??[]).map((p,E)=>e.createElement("div",{key:E,className:i.wrapper},!s&&e.createElement(q.A,{"data-testid":`${d}.${E}.delete-button`,icon:"trash-alt",tooltip:"delete",onClick:()=>g(E),className:i.deleteIcon}),t.subformOptions?.map(A=>e.createElement(Ee,{readOnly:s,defaultValue:p?.[A.propertyName],key:A.propertyName,option:A,pathPrefix:`${d}.${E}.`,error:a?.[E]?.[A.propertyName]})))),!s&&e.createElement(O.zx,{"data-testid":`${d}.add-button`,className:i.addButton,type:"button",variant:"secondary",icon:"plus",size:"sm",onClick:()=>m({__id:String(Math.random())})},"Add")))},cn=({option:t,pathPrefix:n,errors:a,defaultValue:r,readOnly:s=!1})=>{const i=(0,h.wW)(Qe),d=`${n}${t.propertyName}`,{watch:u}=(0,V.Gc)(),f=u(d),m=f===void 0?r:f,[g,p]=(0,e.useState)(!!m);return e.createElement("div",{className:i.wrapper,"data-testid":`${d}.container`},e.createElement("h6",null,t.label),t.description&&e.createElement("p",{className:i.description},t.description),g&&e.createElement(e.Fragment,null,!s&&e.createElement(q.A,{"data-testid":`${d}.delete-button`,icon:"trash-alt",tooltip:"delete",onClick:()=>p(!1),className:i.deleteIcon}),(t.subformOptions??[]).map(E=>e.createElement(Ee,{readOnly:s,defaultValue:r?.[E.propertyName],key:E.propertyName,option:E,pathPrefix:`${d}.`,error:a?.[E.propertyName]}))),!g&&!s&&e.createElement(O.zx,{className:i.addButton,type:"button",variant:"secondary",icon:"plus",size:"sm",onClick:()=>p(!0),"data-testid":`${d}.add-button`},"Add"))},Ee=({option:t,invalid:n,pathPrefix:a,pathSuffix:r="",error:s,defaultValue:i,readOnly:d=!1})=>{const u=`${a}${r}`;return t.element==="subform"?e.createElement(cn,{readOnly:d,defaultValue:i,option:t,errors:s,pathPrefix:u}):t.element==="subform_array"?e.createElement(ln,{readOnly:d,defaultValues:i,option:t,pathPrefix:u,errors:s}):e.createElement(te.g,{label:t.element!=="checkbox"?t.label:void 0,description:t.description||void 0,invalid:!!s,error:s?.message},e.createElement(dn,{id:`${u}${t.propertyName}`,defaultValue:i,option:t,invalid:n,pathPrefix:u,readOnly:d,pathIndex:a}))},dn=({option:t,invalid:n,id:a,pathPrefix:r="",pathIndex:s="",readOnly:i=!1})=>{const{control:d,register:u,unregister:f,getValues:m}=(0,V.Gc)(),g=`${r}${t.propertyName}`;switch((0,e.useEffect)(()=>()=>{f(g,{keepValue:!1})},[f,g]),t.element){case"checkbox":return e.createElement(Te.X,{id:a,readOnly:i,disabled:i,className:mn.checkbox,...u(g),label:t.label,description:t.description});case"input":return e.createElement(ie.I,{id:a,readOnly:i||pn(t,m,s),invalid:n,type:t.inputType,...u(g,{required:un(t,m,s),validate:p=>t.validationRule!==""?Ye(p,t.validationRule):!0}),placeholder:t.placeholder});case"select":return e.createElement(he.g,{render:({field:{onChange:p,ref:E,...A}})=>e.createElement(ze.Ph,{disabled:i,...A,options:t.selectOptions??void 0,invalid:n,onChange:x=>p(x.value)}),control:d,name:g});case"textarea":return e.createElement(en.K,{id:a,readOnly:i,invalid:n,placeholder:t.placeholder,...u(g,{required:t.required?"Required":!1,validate:p=>t.validationRule!==""?Ye(p,t.validationRule):!0})});case"string_array":return e.createElement(he.g,{render:({field:{value:p,onChange:E}})=>e.createElement(rn,{readOnly:i,value:p,onChange:E}),control:d,name:g});case"key_value_map":return e.createElement(he.g,{render:({field:{value:p,onChange:E}})=>e.createElement(tn,{readOnly:i,value:p,onChange:E}),control:d,name:g});default:return console.error("Element not supported",t.element),null}},mn={checkbox:c.css`
    height: auto; // native checkbox has fixed height which does not take into account description
  `},Ye=(t,n)=>RegExp(n).test(t)?!0:"Invalid format",un=(t,n,a)=>{if(!t.dependsOn)return t.required?"Required":!1;if((0,Z.isEmpty)(n(`${a}secureFields`))){const r=n(`${a}secureSettings.${t.dependsOn}`);return!Boolean(r)&&t.required?"Required":!1}else return!n(`${a}secureFields.${t.dependsOn}`)&&t.required?"Required":!1},pn=(t,n,a)=>t.dependsOn?(0,Z.isEmpty)(n(`${a}secureFields`))?n(`${a}secureSettings.${t.dependsOn}`):n(`${a}secureFields.${t.dependsOn}`):!1;function Je({defaultValues:t,selectedChannelOptions:n,onResetSecureField:a,secureFields:r,errors:s,pathPrefix:i="",readOnly:d=!1}){const{watch:u}=(0,V.Gc)(),f=u();return e.createElement(e.Fragment,null,n.map((m,g)=>{const p=`${m.label}-${g}`,E=i.split("."),A=E.length>=2?f.items[Number(E[1])].settings[m.showWhen.field]:void 0;if(m.showWhen.field&&A!==m.showWhen.is)return null;if(r&&r[m.propertyName])return e.createElement(te.g,{key:p,label:m.label,description:m.description||void 0},e.createElement(ie.I,{readOnly:!0,value:"Configured",suffix:d?null:e.createElement(O.zx,{onClick:()=>a(m.propertyName),fill:"text",type:"button",size:"sm"},"Clear")}));const x=(m.secure?s?.secureSettings:s?.settings)?.[m.propertyName],N=t?.settings?.[m.propertyName];return e.createElement(Ee,{defaultValue:N,readOnly:d,key:p,error:x,pathPrefix:i,pathSuffix:m.secure?"secureSettings.":"settings.",option:m})}))}function gn({defaultValues:t,pathPrefix:n,onDuplicate:a,onDelete:r,onTest:s,notifiers:i,errors:d,secureFields:u,commonSettingsComponent:f,isEditable:m=!0,isTestable:g}){const p=(0,h.wW)(fn),E=k=>`${n}${k}`,{control:A,watch:x,register:N,trigger:H,formState:y,setValue:W}=(0,V.Gc)(),U=x(E("type"))??t.type,{loading:J}=(0,ne._)(k=>k.testReceivers);(0,e.useEffect)(()=>{N(`${n}.__id`),N(`${n}.secureFields`)},[N,n]);const[_,de]=(0,e.useState)(u??{}),ve=k=>{if(_[k]){const K={...u};delete K[k],de(K),W(`${n}.secureFields`,K)}},Me=(0,e.useMemo)(()=>i.map(({name:k,type:K})=>({label:k,value:K})).sort((k,K)=>k.label.localeCompare(K.label)),[i]),Le=async()=>{await H(),Object.keys(y.errors).length===0&&s&&s()},se=i.find(({type:k})=>k===U),F=se?.options.filter(k=>k.required),Q=se?.options.filter(k=>!k.required),ge=`contact-point-type-${n}`;return e.createElement("div",{className:p.wrapper,"data-testid":"item-container"},e.createElement("div",{className:p.topRow},e.createElement("div",null,e.createElement(te.g,{label:"Integration",htmlFor:ge,"data-testid":`${n}type`},e.createElement(he.g,{name:E("type"),defaultValue:t.type,render:({field:{ref:k,onChange:K,...ha}})=>e.createElement(ze.Ph,{disabled:!m,inputId:ge,...ha,width:37,options:Me,onChange:Ea=>K(Ea?.value)}),control:A,rules:{required:!0}}))),e.createElement("div",{className:p.buttons},g&&s&&e.createElement(O.zx,{disabled:J,size:"xs",variant:"secondary",type:"button",onClick:()=>Le(),icon:J?"fa fa-spinner":"message"},"Test"),m&&e.createElement(e.Fragment,null,e.createElement(O.zx,{size:"xs",variant:"secondary",type:"button",onClick:()=>a(),icon:"copy"},"Duplicate"),r&&e.createElement(O.zx,{"data-testid":`${n}delete-button`,size:"xs",variant:"secondary",type:"button",onClick:()=>r(),icon:"trash-alt"},"Delete")))),se&&e.createElement("div",{className:p.innerContent},e.createElement(Je,{defaultValues:t,selectedChannelOptions:F?.length?F:Q,secureFields:_,errors:d,onResetSecureField:ve,pathPrefix:n,readOnly:!m}),!!(F?.length&&Q?.length)&&e.createElement(Se,{label:`Optional ${se.name} settings`},se.info!==""&&e.createElement(D.b,{title:"",severity:"info"},se.info),e.createElement(Je,{defaultValues:t,selectedChannelOptions:Q,secureFields:_,onResetSecureField:ve,errors:d,pathPrefix:n,readOnly:!m})),e.createElement(Se,{label:"Notification settings"},e.createElement(f,{pathPrefix:n,readOnly:!m}))))}const fn=t=>({buttons:c.css`
    & > * + * {
      margin-left: ${t.spacing(1)};
    }
  `,innerContent:c.css`
    max-width: 536px;
  `,wrapper:c.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:c.css`
    display: flex;
    flex-direction: row;
    justify-content: space-between;
  `,channelSettingsHeader:c.css`
    margin-top: ${t.spacing(2)};
  `});function hn({pathPrefix:t}){const{register:n}=(0,V.Gc)();return(0,e.useEffect)(()=>{n(`${t}.__id`),n(`${t}.__deleted`)},[n,t]),e.createElement(e.Fragment,null)}function En(t){if(t)return{...t,items:t.items.map(n=>({...n,settings:{...n.settings,http_config:n.settings?.http_config?yn(n.settings?.http_config):void 0}}))}}function yn(t){return vn(t)?t:{...(0,Z.omit)(t,"authorization"),bearer_token:t.authorization.credentials,bearer_token_file:t.authorization.credentials_file}}function vn(t){return["bearer_token","bearer_token_file"].some(n=>n in t)}function Ze({config:t,initialValues:n,defaultItem:a,notifiers:r,alertManagerSourceName:s,onSubmit:i,onTestChannel:d,takenReceiverNames:u,commonSettingsComponent:f,isEditable:m,isTestable:g}){const p=(0,Xt.iG)(),E=(0,h.wW)(bn),x=En(n)??{name:"",items:[{...a,__id:String(Math.random())}]},N=(0,V.cI)({defaultValues:JSON.parse(JSON.stringify(x))});(0,Ae.x)(F=>F.unifiedAlerting.saveAMConfig=fe.oq);const{loading:H}=(0,ne._)(F=>F.saveAMConfig),{handleSubmit:y,register:W,formState:{errors:U},getValues:J}=N,{fields:_,append:de,remove:ve}=Ke({name:"items",formAPI:N,softDelete:!0}),Me=(0,e.useCallback)(F=>u.map(Q=>Q.trim().toLowerCase()).includes(F.trim().toLowerCase())?"Another receiver with this name already exists.":!0,[u]),Le=F=>{i({...F,items:F.items.filter(Q=>!Q.__deleted)})},se=()=>{p.error("There are errors in the form. Please correct them and try again!")};return e.createElement(V.RV,{...N},!t.alertmanager_config.route&&e.createElement(D.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:y(Le,se)},e.createElement("h4",{className:E.heading},m?n?"Update contact point":"Create contact point":"Contact point"),e.createElement(te.g,{label:"Name",invalid:!!U.name,error:U.name&&U.name.message,required:!0},e.createElement(ie.I,{readOnly:!m,id:"name",...W("name",{required:"Name is required",validate:{nameIsAvailable:Me}}),width:39,placeholder:"Name"})),_.map((F,Q)=>{const ge=`items.${Q}.`;if(F.__deleted)return e.createElement(hn,{key:F.__id,pathPrefix:ge});const k=n?.items.find(({__id:K})=>K===F.__id);return e.createElement(gn,{defaultValues:F,key:F.__id,onDuplicate:()=>{const K=J().items[Q];de({...K,__id:String(Math.random())})},onTest:d?()=>{const K=J().items[Q];d(K)}:void 0,onDelete:()=>ve(Q),pathPrefix:ge,notifiers:r,secureFields:k?.secureFields,errors:U?.items?.[Q],commonSettingsComponent:f,isEditable:m,isTestable:g})}),e.createElement(e.Fragment,null,m&&e.createElement(O.zx,{type:"button",icon:"plus",variant:"secondary",onClick:()=>de({...a,__id:String(Math.random())})},"Add contact point integration"),e.createElement("div",{className:E.buttons},m&&e.createElement(e.Fragment,null,H&&e.createElement(O.zx,{disabled:!0,icon:"fa fa-spinner",variant:"primary"},"Saving..."),!H&&e.createElement(O.zx,{type:"submit"},"Save contact point")),e.createElement(O.Qj,{disabled:H,fill:"outline",variant:"secondary","data-testid":"cancel-button",href:(0,Y.eQ)("alerting/notifications",s)},"Cancel")))))}const bn=t=>({heading:c.css`
    margin: ${t.spacing(4,0)};
  `,buttons:c.css`
    margin-top: ${t.spacing(4)};

    & > * + * {
      margin-left: ${t.spacing(1)};
    }
  `}),Xe=Object.freeze({__id:"",sendResolved:!0,secureSettings:{},settings:{},secureFields:{},type:"email"}),qe=({existing:t,alertManagerSourceName:n,config:a})=>{const r=(0,M.useDispatch)(),s=(0,X.RY)(n),[i]=(0,e.useMemo)(()=>t?jt(t,Fe):[void 0,{}],[t]),d=m=>{const g=Qt(m,Xe);r((0,ee.mM)({newConfig:Ve(a,g,t?.name),oldConfig:a,alertManagerSourceName:n,successMessage:t?"Contact point updated.":"Contact point created.",redirectPath:"/alerting/notifications"}))},u=(0,e.useMemo)(()=>a.alertmanager_config.receivers?.map(({name:m})=>m).filter(m=>m!==t?.name)??[],[a,t]),f=!(0,X.RY)(n);return e.createElement(e.Fragment,null,!s&&e.createElement(D.b,{title:"Info",severity:"info"},"Note that empty string values will be replaced with global defaults where appropriate."),e.createElement(Ze,{isEditable:f,isTestable:f,config:a,onSubmit:d,initialValues:i,notifiers:Fe,alertManagerSourceName:n,defaultItem:Xe,takenReceiverNames:u,commonSettingsComponent:Zt}))},An=({pathPrefix:t,className:n,readOnly:a=!1})=>{const{register:r}=(0,V.Gc)();return e.createElement("div",{className:n},e.createElement(te.g,null,e.createElement(Te.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 ye=o(90931),Cn=o(42505),Tn=o(12007),Sn=o(27052),Pn=o(29389),et=(t=>(t.predefined="Predefined",t.custom="Custom",t))(et||{});const Rn=Object.values(et).map(t=>({label:t,value:t})),Dn={annotations:[{key:"",value:""}],labels:[{key:"",value:""}]},xn=({isOpen:t,onDismiss:n,onTest:a})=>{const[r,s]=(0,e.useState)("Predefined"),i=(0,h.wW)(Mn),d=(0,V.cI)({defaultValues:Dn,mode:"onBlur"}),u=f=>{if(r==="Custom"){const m={annotations:f.annotations.filter(({key:g,value:p})=>!!g&&!!p).reduce((g,{key:p,value:E})=>({...g,[p]:E}),{}),labels:f.labels.filter(({key:g,value:p})=>!!g&&!!p).reduce((g,{key:p,value:E})=>({...g,[p]:E}),{})};a(m)}else a()};return e.createElement(ye.u,{onDismiss:n,isOpen:t,title:"Test contact point"},e.createElement("div",{className:i.section},e.createElement(Cn._,null,"Notification message"),e.createElement(Tn.S,{options:Rn,value:r,onChange:f=>s(f)})),e.createElement(V.RV,{...d},e.createElement("form",{onSubmit:d.handleSubmit(u)},r==="Predefined"&&e.createElement("div",{className:i.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:i.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:i.section},e.createElement(Sn.Z,null)),e.createElement("div",{className:i.section},e.createElement(Pn.Z,null))),e.createElement(ye.u.ButtonRow,null,e.createElement(O.zx,{type:"submit"},"Send test notification")))))},Mn=t=>({flexRow:c.css`
    display: flex;
    flex-direction: row;
    align-items: flex-start;
    margin-bottom: ${t.spacing(1)};
  `,section:c.css`
    margin-bottom: ${t.spacing(2)};
  `}),Pe=Object.freeze({__id:"",secureSettings:{},settings:{},secureFields:{},disableResolveMessage:!1,type:"email"}),tt=({existing:t,alertManagerSourceName:n,config:a})=>{const r=(0,ne._)(y=>y.grafanaNotifiers),[s,i]=(0,e.useState)(),d=(0,M.useDispatch)();(0,e.useEffect)(()=>{r.result||r.loading||d((0,ee.Vj)())},[r,d]);const[u,f]=(0,e.useMemo)(()=>!t||!r.result?[void 0,{}]:zt(t,r.result),[t,r.result]),m=y=>{const W=Ht(y,f,Pe);d((0,ee.mM)({newConfig:Ve(a,W,t?.name),oldConfig:a,alertManagerSourceName:X.GC,successMessage:t?"Contact point updated.":"Contact point created",redirectPath:"/alerting/notifications"}))},g=y=>{i(y)},p=y=>{if(s){const W=f[s.__id],U=Be(s,Pe,"test",W),J={alertManagerSourceName:n,receivers:[{name:"test",grafana_managed_receiver_configs:[U]}],alert:y};d((0,ee.D8)(J))}},E=(0,e.useMemo)(()=>a.alertmanager_config.receivers?.map(({name:y})=>y).filter(y=>y!==t?.name)??[],[a,t]),A=t?(t.grafana_managed_receiver_configs??[]).some(y=>Boolean(y.provenance)):!1,x=!(0,X.RY)(n),N=x&&!A,H=x||A;return r.result?e.createElement(e.Fragment,null,A&&e.createElement(ce.Xq,{resource:ce.Uv.ContactPoint}),e.createElement(Ze,{isEditable:N,isTestable:H,config:a,onSubmit:m,initialValues:u,onTestChannel:g,notifiers:r.result,alertManagerSourceName:n,defaultItem:Pe,takenReceiverNames:E,commonSettingsComponent:An}),e.createElement(xn,{onDismiss:()=>i(void 0),isOpen:!!s,onTest:y=>p(y)})):e.createElement(I.u,{text:"Loading notifiers..."})},Ln=({config:t,receiverName:n,alertManagerSourceName:a})=>{const r=t.alertmanager_config.receivers?.find(({name:s})=>s===n);return r?a===X.GC?e.createElement(tt,{config:t,alertManagerSourceName:a,existing:r}):e.createElement(qe,{config:t,alertManagerSourceName:a,existing:r}):e.createElement(D.b,{severity:"error",title:"Receiver not found"},"Sorry, this receiver does not seem to exist.")},On=({config:t,templateName:n,alertManagerSourceName:a})=>{const r=t.template_files?.[n],s=t.template_file_provenances?.[n];return r?e.createElement(Ce,{alertManagerSourceName:a,config:t,existing:{name:n,content:r},provenance:s}):e.createElement(D.b,{severity:"error",title:"Template not found"},"Sorry, this template does not seem to exists.")};var nt=o(6741);const at={smtp_require_tls:!0},In=({config:t,alertManagerSourceName:n})=>{const a=(0,M.useDispatch)();(0,Ae.x)(g=>g.unifiedAlerting.saveAMConfig=fe.oq);const{loading:r,error:s}=(0,ne._)(g=>g.saveAMConfig),i=(0,X.RY)(n),d=(0,V.cI)({defaultValues:JSON.parse(JSON.stringify({...at,...t.alertmanager_config.global??{}}))}),{handleSubmit:u,formState:{errors:f}}=d,m=g=>{a((0,ee.mM)({newConfig:{...t,alertmanager_config:{...t.alertmanager_config,global:ue(g)}},oldConfig:t,alertManagerSourceName:n,successMessage:"Global config updated.",redirectPath:(0,Y.eQ)("/alerting/notifications",n)}))};return e.createElement(V.RV,{...d},e.createElement("form",{onSubmit:u(m)},s&&e.createElement(D.b,{severity:"error",title:"Error saving receiver"},s.message||String(s)),Kt.map(g=>e.createElement(Ee,{readOnly:i,defaultValue:at[g.propertyName],key:g.propertyName,option:g,error:f[g.propertyName],pathPrefix:""})),e.createElement("div",null,e.createElement(nt.Lh,null,!i&&e.createElement(e.Fragment,null,r&&e.createElement(O.zx,{disabled:!0,icon:"fa fa-spinner",variant:"primary"},"Saving..."),!r&&e.createElement(O.zx,{type:"submit"},"Save global config")),e.createElement(O.Qj,{disabled:r,fill:"outline",variant:"secondary",href:(0,Y.eQ)("alerting/notifications",n)},"Cancel")))))},Nn=({alertManagerSourceName:t,config:n})=>t===X.GC?e.createElement(tt,{alertManagerSourceName:t,config:n}):e.createElement(qe,{alertManagerSourceName:t,config:n}),wn=({config:t,alertManagerSourceName:n})=>e.createElement(Ce,{config:t,alertManagerSourceName:n});var oe=o(35467),$n=o(79432),_n=o(25641),Re=o(66434),rt=o(22324),De=o(96237),ot=o(42111),st=o(87824),kn=o(25312);const Wn={pagerduty:"PagerDuty",pushover:"Pushover",slack:"Slack",opsgenie:"OpsGenie",webhook:"Webhook",victorops:"VictorOps",wechat:"WeChat"};function Un(t,n){return t.grafana_managed_receiver_configs?Vn(t.grafana_managed_receiver_configs??[],n):Fn(t)}function Fn(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",""),i=Wn[s]??(0,Z.capitalize)(s);return{...n,[i]:(n[i]??0)+(Array.isArray(r)?r.length:1)}},{})}function Vn(t,n){return t.map(a=>a.type).map(a=>n.find(r=>r.type===a)?.name??(0,Z.capitalize)(a)).reduce((a,r)=>({...a,[r]:(a[r]??0)+1}),{})}var lt=o(98709),Gn=o(44579);const it=({className:t,title:n,description:a,addButtonLabel:r,addButtonTo:s,children:i,showButton:d=!0})=>{const u=(0,h.wW)(Bn);return e.createElement(T.Stack,{direction:"column",gap:2},e.createElement("div",{className:(0,c.cx)(u.heading,t)},e.createElement("div",null,e.createElement("h4",null,n),e.createElement("div",{className:u.description},a)),d&&e.createElement(Gn.Link,{to:s},e.createElement(O.zx,{type:"button",icon:"plus"},r))),i)},Bn=t=>({heading:c.css`
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
  `,description:c.css`
    color: ${t.colors.text.secondary};
  `});var xe=o(29125);const Kn={[xe.W.OnCall]:"public/img/alerting/oncall_logo.svg",[xe.W.Incident]:"",[xe.W.MachineLearning]:""},zn=({grafanaAppType:t})=>{const n=(0,h.wW)(jn);return e.createElement("div",{className:n.wrapper},e.createElement(nt.Lh,{align:"center",spacing:"xs"},e.createElement("img",{src:Kn[t],alt:"",height:"12px"}),e.createElement("span",null,t)))},jn=t=>({wrapper:c.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 Hn=o(60294);function Qn({permissions:t,alertManagerName:n,receiverName:a,onClickDeleteReceiver:r}){return e.createElement(e.Fragment,null,e.createElement(oe.q,{actions:[t.update]},e.createElement(q.A,{"aria-label":"Edit","data-testid":"edit",to:(0,Y.eQ)(`/alerting/notifications/receivers/${encodeURIComponent(a)}/edit`,n),tooltip:"Edit contact point",icon:"pen"})),e.createElement(oe.q,{actions:[t.delete]},e.createElement(q.A,{onClick:()=>r(a),tooltip:"Delete contact point",icon:"trash-alt"})))}function Yn({permissions:t,alertManagerName:n,receiverName:a}){return e.createElement(oe.q,{actions:[t.update]},e.createElement(q.A,{"data-testid":"view",to:(0,Y.eQ)(`/alerting/notifications/receivers/${encodeURIComponent(a)}/edit`,n),tooltip:"View contact point",icon:"file-alt"}))}function ct({errorCount:t,errorDetail:n,showErrorCount:a}){const r=a?`${t} ${b()("error",t)}`:"Error";return e.createElement(Re.C,{color:"orange",icon:"exclamation-triangle",text:r,tooltip:n??"Error"})}function Jn({errorsByNotifier:t,errorDetail:n,lastNotify:a}){const r=pe(a)?"orange":"green",s=pe(a)?"No attempts":"OK";return t>0?e.createElement(ct,{errorCount:t,errorDetail:n,showErrorCount:!1}):e.createElement(Re.C,{color:r,text:s,tooltip:""})}function Zn({errorsByReceiver:t,someWithNoAttempt:n}){const a=n?"orange":"green",r=n?"No attempts":"OK";return t>0?e.createElement(ct,{errorCount:t,showErrorCount:!0}):e.createElement(Re.C,{color:a,text:r,tooltip:""})}const Xn=t=>{const n=(0,$.V)(t),a=n?.receivers??{},r=Object.keys(a).length>0;return{contactPointsState:n,errorStateAvailable:r}},pe=t=>t==="0001-01-01T00:00:00.000Z";function qn({lastNotifyDate:t}){return pe(t)?e.createElement(e.Fragment,null,"-"):e.createElement(T.Stack,{alignItems:"center"},e.createElement("div",null,`${(0,$n.CQ)(t).locale("en").fromNow(!0)} ago`),e.createElement(R.J,{name:"clock-nine"}),e.createElement("div",null,`${(0,_n.dq)(t,{format:"YYYY-MM-DD HH:mm:ss"})}`))}const ea=["","0","0ms","0s","0m","0h","0d","0w","0y"],ta=t=>ea.includes(t);function na({notifiersState:t}){function n(){return[{id:"health",label:"Health",renderCell:({data:{lastError:r,lastNotify:s}})=>e.createElement(Jn,{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(qn,{lastNotifyDate:r}),size:3},{id:"lastNotifyDuration",label:"Last duration",renderCell:({data:{lastNotify:r,lastNotifyDuration:s}})=>e.createElement(e.Fragment,null,pe(r)&&ta(s)?"-":s),size:1},{id:"sendResolved",label:"Send resolved",renderCell:({data:{sendResolved:r}})=>e.createElement(e.Fragment,null,String(Boolean(r))),size:1}]}const a=Object.entries(t).flatMap(r=>r[1].map((s,i)=>({id:i,data:{type:r[0],lastError:s.lastNotifyAttemptError,lastNotify:s.lastNotifyAttempt,lastNotifyDuration:s.lastNotifyAttemptDuration,sendResolved:s.sendResolved}})));return e.createElement(lt.t,{items:a,cols:n()})}const aa=({config:t,alertManagerName:n})=>{const a=(0,M.useDispatch)(),r=(0,X.RY)(n),s=(0,st.Ko)(n),i=(0,ne._)(y=>y.grafanaNotifiers),{contactPointsState:d,errorStateAvailable:u}=Xn(n),[f,m]=(0,e.useState)(),[g,p]=(0,e.useState)(!1),E=y=>{(0,kn.nv)(y,t)?p(!0):m(y)},A=()=>{f&&a((0,ee.X4)(f,n)),m(void 0)},x=(0,Hn.HU)(t.alertmanager_config.receivers??[]),N=(0,e.useMemo)(()=>x?.map(y=>({id:y.name,data:{name:y.name,types:Object.entries(Un(y,i.result??[])).map(([W,U])=>U>1?`${W} (${U})`:W),grafanaAppReceiverType:y.grafanaAppReceiverType,provisioned:y.grafana_managed_receiver_configs?.some(W=>W.provenance)}}))??[],[i.result,x]),H=sa(n,u,d,E,s,r);return e.createElement(it,{title:"Contact points",description:"Define where notifications are sent, for example, email or Slack.",showButton:!r&&De.Vt.hasPermission(s.create),addButtonLabel:"Add contact point",addButtonTo:(0,Y.eQ)("/alerting/notifications/receivers/new",n)},e.createElement(lt.t,{items:N,cols:H,isExpandable:u,renderExpandedContent:u?({data:{name:y}})=>e.createElement(na,{notifiersState:d?.receivers[y]?.notifiers??{}}):void 0}),!!g&&e.createElement(ye.u,{isOpen:!0,title:"Cannot delete contact point",onDismiss:()=>p(!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(ye.u.ButtonRow,null,e.createElement(O.zx,{variant:"secondary",onClick:()=>p(!1),fill:"outline"},"Close"))),!!f&&e.createElement(rt.s,{isOpen:!0,title:"Delete contact point",body:`Are you sure you want to delete contact point "${f}"?`,confirmText:"Yes, delete",onConfirm:A,onDismiss:()=>m(void 0)}))},ra=(t,n)=>t?.receivers[n]?.errorCount??0,oa=(t,n)=>{const a=Object.values(t?.receivers[n]?.notifiers??{});return a.length===0||a.flat().some(s=>pe(s.lastNotifyAttempt))};function sa(t,n,a,r,s,i){const d=(0,h.wW)(ot.D),u=[{id:"name",label:"Contact point name",renderCell:({data:{name:m,provisioned:g}})=>e.createElement(T.Stack,{alignItems:"center"},e.createElement("div",null,m),g&&e.createElement(ce.C0,null)),size:1},{id:"type",label:"Type",renderCell:({data:{types:m,grafanaAppReceiverType:g}})=>e.createElement(e.Fragment,null,g?e.createElement(zn,{grafanaAppType:g}):m.join(", ")),size:1}],f={id:"health",label:"Health",renderCell:({data:{name:m}})=>a&&e.createElement(Zn,{errorsByReceiver:ra(a,m),someWithNoAttempt:oa(a,m)}),size:1};return[...u,...n?[f]:[],{id:"actions",label:"Actions",renderCell:({data:{provisioned:m,name:g}})=>e.createElement(oe.q,{actions:[s.update,s.delete]},e.createElement("div",{className:d.actionsCell},!i&&!m&&e.createElement(Qn,{permissions:s,alertManagerName:t,receiverName:g,onClickDeleteReceiver:r}),(i||m)&&e.createElement(Yn,{permissions:s,alertManagerName:t,receiverName:g}))),size:"100px"}]}var la=o(45201);const ia=({config:t,alertManagerName:n})=>{const a=(0,M.useDispatch)(),[r,s]=(0,e.useState)({}),i=(0,h.wW)(ot.D),d=(0,st.Ko)(n),u=(0,e.useMemo)(()=>Object.entries(t.template_files).map(([E,A])=>({name:E,template:A,provenance:(t.template_file_provenances??{})[E]})),[t]),[f,m]=(0,e.useState)(),g=()=>{f&&a((0,ee.S6)(f,n)),m(void 0)};return e.createElement(it,{title:"Notification templates",description:"Create notification templates to customize your notifications.",addButtonLabel:"Add template",addButtonTo:(0,Y.eQ)("/alerting/notifications/templates/new",n),showButton:De.Vt.hasPermission(d.create)},e.createElement("table",{className:i.table,"data-testid":"templates-table"},e.createElement("colgroup",null,e.createElement("col",{className:i.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(oe.q,{actions:[d.update,d.delete]},e.createElement("th",null,"Actions")))),e.createElement("tbody",null,!u.length&&e.createElement("tr",{className:i.evenRow},e.createElement("td",{colSpan:3},"No templates defined.")),u.map(({name:p,template:E,provenance:A},x)=>{const N=!!r[p];return e.createElement(e.Fragment,{key:p},e.createElement("tr",{key:p,className:x%2===0?i.evenRow:void 0},e.createElement("td",null,e.createElement(He.U,{isCollapsed:!r[p],onToggle:()=>s({...r,[p]:!N})})),e.createElement("td",null,p," ",A&&e.createElement(ce.C0,null)),e.createElement("td",{className:i.actionsCell},A&&e.createElement(q.A,{to:(0,Y.eQ)(`/alerting/notifications/templates/${encodeURIComponent(p)}/edit`,n),tooltip:"view template",icon:"file-alt"}),!A&&e.createElement(oe.q,{actions:[d.update]},e.createElement(q.A,{to:(0,Y.eQ)(`/alerting/notifications/templates/${encodeURIComponent(p)}/edit`,n),tooltip:"edit template",icon:"pen"})),De.Vt.hasPermission(d.create)&&e.createElement(q.A,{to:(0,Y.eQ)(`/alerting/notifications/templates/${encodeURIComponent(p)}/duplicate`,n),tooltip:"Copy template",icon:"copy"}),!A&&e.createElement(oe.q,{actions:[d.delete]},e.createElement(q.A,{onClick:()=>m(p),tooltip:"delete template",icon:"trash-alt"})))),N&&e.createElement("tr",{className:x%2===0?i.evenRow:void 0},e.createElement("td",null),e.createElement("td",{colSpan:2},e.createElement(la.C,{label:"Description",horizontal:!0},e.createElement(_e,{width:"auto",height:"auto",autoHeight:!0,value:E,showLineNumbers:!1,monacoOptions:{readOnly:!0,scrollBeyondLastLine:!1}})))))}))),!!f&&e.createElement(rt.s,{isOpen:!0,title:"Delete template",body:`Are you sure you want to delete template "${f}"?`,confirmText:"Yes, delete",onConfirm:g,onDismiss:()=>m(void 0)}))},ca=({config:t,alertManagerName:n})=>{const a=n!==X.GC,r=(0,X.RY)(n);return e.createElement(T.Stack,{direction:"column",gap:4},e.createElement(aa,{config:t,alertManagerName:n}),!r&&e.createElement(ia,{config:t,alertManagerName:n}),a&&e.createElement(oe.q,{actions:[M.AccessControlAction.AlertingNotificationsExternalWrite]},e.createElement(D.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(O.Qj,{href:(0,Y.eQ)("alerting/notifications/global-config",n),variant:"secondary"},r?"View global config":"Edit global config"))))};var da=o(14014),ma=o(13697);function ua({errorCount:t}){const n=(0,h.wW)(dt);return e.createElement("div",{className:n.warning,"data-testid":"receivers-notification-error"},e.createElement(T.Stack,{alignItems:"flex-end",direction:"column"},e.createElement(T.Stack,{alignItems:"center"},e.createElement(R.J,{name:"exclamation-triangle"}),e.createElement("div",{className:n.countMessage},`${t} ${b()("error",t)} with contact points`)),e.createElement("div",null,"Some alert notifications might not be delivered")))}const pa=()=>{const t=(0,ma.k)("notification"),[n,a]=(0,da.k)(t),r=(0,M.useDispatch)(),s=(0,h.wW)(dt),{id:i,type:d}=(0,v.UO)(),u=(0,v.TH)(),f=u.pathname.endsWith("/alerting/notifications"),m=ke(u),g=(0,ne._)(_=>_.amConfigs),{result:p,loading:E,error:A}=n&&g[n]||fe.oq,x=(0,ne._)(_=>_.grafanaNotifiers),N=f||!p,H=f;(0,e.useEffect)(()=>{n&&N&&r((0,ee.Yh)(n))},[n,r,N]),(0,e.useEffect)(()=>{n===X.GC&&!(x.result||x.loading||x.error)&&r((0,ee.Vj)())},[n,r,x]);const W=(0,$.V)(n??"")?.errorCount??0,U=!f;let J=ga(d,i?decodeURIComponent(i):void 0,m);return n?e.createElement(L.J,{pageId:"receivers",pageNav:J},e.createElement("div",{className:s.headingContainer},e.createElement(P.P,{current:n,disabled:U,onChange:a,dataSources:t}),H&&W>0&&e.createElement(ua,{errorCount:W})),A&&!E&&e.createElement(D.b,{severity:"error",title:"Error loading Alertmanager config"},A.message||"Unknown error."),e.createElement(z.u,{currentAlertmanager:n}),E&&!p&&e.createElement(I.u,{text:"loading configuration..."}),p&&!A&&e.createElement(v.rs,null,e.createElement(v.AW,{exact:!0,path:"/alerting/notifications"},e.createElement(ca,{config:p,alertManagerName:n})),e.createElement(v.AW,{exact:!0,path:"/alerting/notifications/templates/new"},e.createElement(wn,{config:p,alertManagerSourceName:n})),e.createElement(v.AW,{exact:!0,path:"/alerting/notifications/templates/:name/duplicate"},({match:_})=>_?.params.name&&e.createElement(Gt,{alertManagerSourceName:n,config:p,templateName:decodeURIComponent(_?.params.name)})),e.createElement(v.AW,{exact:!0,path:"/alerting/notifications/templates/:name/edit"},({match:_})=>_?.params.name&&e.createElement(On,{alertManagerSourceName:n,config:p,templateName:decodeURIComponent(_?.params.name)})),e.createElement(v.AW,{exact:!0,path:"/alerting/notifications/receivers/new"},e.createElement(Nn,{config:p,alertManagerSourceName:n})),e.createElement(v.AW,{exact:!0,path:"/alerting/notifications/receivers/:name/edit"},({match:_})=>_?.params.name&&e.createElement(Ln,{alertManagerSourceName:n,config:p,receiverName:decodeURIComponent(_?.params.name)})),e.createElement(v.AW,{exact:!0,path:"/alerting/notifications/global-config"},e.createElement(In,{config:p,alertManagerSourceName:n})))):f?e.createElement(L.J,{pageId:"receivers",pageNav:J},e.createElement(j.I,{availableAlertManagers:t})):e.createElement(v.l_,{to:"/alerting/notifications"})};function ga(t,n,a){let r;if(a)return{text:"New template",subTitle:"Create a new template for your notifications"};if(t==="receivers"||t==="templates"){const s=t==="receivers"?"contact point":"notification template";n?r={text:n,subTitle:`Edit the settings for a specific ${s}`}:r={text:`New ${s}`,subTitle:`Create a new ${s} for your notifications`}}else t==="global-config"&&(r={text:"Global config",subTitle:"Manage your global configuration"});return r}const fa=(0,w.Pf)(pa,{style:"page"}),dt=t=>({warning:c.css`
    color: ${t.colors.warning.text};
  `,countMessage:c.css`
    padding-left: 10px;
  `,headingContainer:c.css`
    display: flex;
    justify-content: space-between;
  `})},73312:(G,S,o)=>{o.d(S,{h:()=>C});var c=o(9002);const C=c.C.injectEndpoints({endpoints:b=>({getAlertmanagerChoiceStatus:b.query({query:()=>({url:"/api/v1/ngalert"}),providesTags:["AlertmanagerChoice"]}),getExternalAlertmanagerConfig:b.query({query:()=>({url:"/api/v1/ngalert/admin_config"}),providesTags:["AlertmanagerChoice"]}),getExternalAlertmanagers:b.query({query:()=>({url:"/api/v1/ngalert/alertmanagers"}),transformResponse:e=>e.data}),saveExternalAlertmanagersConfig:b.mutation({query:e=>({url:"/api/v1/ngalert/admin_config",method:"POST",data:e}),invalidatesTags:["AlertmanagerChoice"]})})})},72400:(G,S,o)=>{o.d(S,{V:()=>v});var c=o(98401),C=o(9002),b=o(18966);const e=C.C.injectEndpoints({endpoints:T=>({contactPointsState:T.query({queryFn:async({amSourceName:h})=>{try{return{data:await(0,b.QE)(h)}}catch(R){return{error:R}}}})})}),v=T=>{const h={receivers:{},errorCount:0},{currentData:R}=e.useContactPointsStateQuery({amSourceName:T??""},{skip:!T,pollingInterval:c.m4});return R??h}},35467:(G,S,o)=>{o.d(S,{q:()=>b});var c=o(65237),C=o(96237);const b=({actions:e,children:v,fallback:T=!0})=>e.some(h=>C.Vt.hasAccess(h,T))?c.createElement(c.Fragment,null,v):null},8798:(G,S,o)=>{o.d(S,{u:()=>R});var c=o(60234),C=o(65237),b=o(93048),e=o(88347),v=o(40285),T=o(73312),h=o(50328);function R({currentAlertmanager:I}){const w=(0,b.wW)(D),{useGetAlertmanagerChoiceStatusQuery:M}=T.h,{currentData:$}=M(),P=I===h.GC;if(!($?.alertmanagersChoice&&[v.TE.External,v.TE.All].includes($?.alertmanagersChoice))||!P)return null;const z=$.numExternalAlertmanagers>0;return $.alertmanagersChoice===v.TE.External?C.createElement(e.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.",C.createElement("div",{className:w.adminHint},"To change your Alertmanager setup, go to the Alerting Admin page. If you do not have access, contact your Administrator.")):$.alertmanagersChoice===v.TE.All&&z?C.createElement(e.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.",C.createElement("div",{className:w.adminHint},"To change your Alertmanager setup, go to the Alerting Admin page. If you do not have access, contact your Administrator.")):null}const D=I=>({adminHint:c.css`
    font-size: ${I.typography.bodySmall.fontSize};
    font-weight: ${I.typography.bodySmall.fontWeight};
  `})},31222:(G,S,o)=>{o.d(S,{I:()=>h});var c=o(65237),C=o(88347),b=o(14014),e=o(70755);const v=()=>c.createElement(C.b,{title:"No Alertmanager found",severity:"warning"},"We could not find any external Alertmanagers and you may not have access to the built-in Grafana Alertmanager."),T=()=>c.createElement(C.b,{title:"Selected Alertmanager not found. Select a different Alertmanager.",severity:"warning"},"Selected Alertmanager no longer exists or you may not have permission to access it."),h=({availableAlertManagers:R})=>{const[D,I]=(0,b.k)(R),w=R.length>0;return c.createElement("div",null,w?c.createElement(c.Fragment,null,c.createElement(e.P,{onChange:I,dataSources:R}),c.createElement(T,null)):c.createElement(v,null))}},89745:(G,S,o)=>{o.d(S,{C0:()=>T,Uv:()=>e,Xq:()=>v});var c=o(65237),C=o(88347),b=o(66434),e=(h=>(h.ContactPoint="contact point",h.Template="template",h.MuteTiming="mute timing",h.AlertRule="alert rule",h.RootNotificationPolicy="root notification policy",h))(e||{});const v=({resource:h})=>c.createElement(C.b,{title:`This ${h} cannot be edited through the UI`,severity:"info"},"This ",h," has been provisioned, that means it was created by config. Please contact your server admin to update this ",h,"."),T=()=>c.createElement(b.C,{text:"Provisioned",color:"purple"})},60294:(G,S,o)=>{o.d(S,{Kt:()=>M,HU:()=>$});var c=o(78209),C=o(55041),b=o(9002);const e=b.C.injectEndpoints({endpoints:P=>({getOnCallIntegrations:P.query({queryFn:async()=>({data:await v()}),providesTags:["AlertmanagerChoice"]})})});async function v(){try{return(await(0,c.n)((0,C.i)().fetch({url:"/api/plugin-proxy/grafana-oncall-app/api/internal/v1/alert_receive_channels/",showErrorAlert:!1,showSuccessAlert:!1}))).data.map(L=>L.integration_url)}catch{return[]}}const{useGetOnCallIntegrationsQuery:T}=e;var h=o(13002),R=o(29125);const D=(P,L)=>L.includes(P),I=(P,L)=>{if(!P.grafana_managed_receiver_configs)return!1;const z=P.grafana_managed_receiver_configs.length===1,j=D(P.grafana_managed_receiver_configs[0]?.settings?.url??"",L);return z&&j},w=()=>{const{installed:P}=(0,h.n)(R.W.OnCall),{data:L}=T(void 0,{skip:!P});return j=>{if(P&&I(j,L??[]))return R.W.OnCall}},M=P=>{const L=w(),z=j=>({label:j.name,value:j.name,grafanaAppReceiverType:L(j)});return P.map(z)},$=P=>{const L=w();return P.map(z=>({...z,grafanaAppReceiverType:L(z)}))}},23719:(G,S,o)=>{o.d(S,{A:()=>e});var c=o(65237),C=o(89050),b=o(48389);const e=({tooltip:v,icon:T,to:h,target:R,onClick:D,className:I,tooltipPlacement:w="top",...M})=>{const $=typeof v=="string"?v:void 0;return c.createElement(C.u,{content:v,placement:w},h?c.createElement(b.Qj,{variant:"secondary",fill:"text",icon:T,href:h,size:"sm",target:R,...M,"aria-label":$}):c.createElement(b.zx,{className:I,variant:"secondary",fill:"text",size:"sm",icon:T,type:"button",onClick:D,...M,"aria-label":$}))}},14014:(G,S,o)=>{o.d(S,{k:()=>h});var c=o(65237),C=o(68532),b=o(81453),e=o(98401),v=o(50328);function T(R){return(0,c.useCallback)(D=>R.map(w=>w.name).includes(D),[R])}function h(R){const[D,I]=(0,C.K)(),w=T(R),M=(0,c.useCallback)(L=>{w(L)&&(L===v.GC?(b.Z.delete(e.de),I({[e.c4]:null})):(b.Z.set(e.de,L),I({[e.c4]:L})))},[I,w]),$=D[e.c4];if($&&typeof $=="string")return w($)?[$,M]:[void 0,M];const P=b.Z.get(e.de);return P&&typeof P=="string"&&w(P)?(M(P),[P,M]):w(v.GC)?[v.GC,M]:[void 0,M]}},13697:(G,S,o)=>{o.d(S,{k:()=>b});var c=o(65237),C=o(50328);function b(e){return(0,c.useMemo)(()=>(0,C.LE)(e),[e])}},13002:(G,S,o)=>{o.d(S,{n:()=>b});var c=o(15804),C=o(157);function b(e){const{loading:v,error:T,value:h}=(0,c.Z)(()=>(0,C.a)(e,{showErrorAlert:!1})),R=h&&!T&&!v,D=h?.enabled;return v&&!h?{loading:!0}:!R||!D?{loading:!1,installed:!1}:{loading:v,installed:!0,settings:h}}},42111:(G,S,o)=>{o.d(S,{D:()=>C});var c=o(60234);const C=b=>({table:c.css`
    width: 100%;
    border-radius: ${b.shape.borderRadius()};
    border: solid 1px ${b.colors.border.weak};
    background-color: ${b.colors.background.secondary};

    th {
      padding: ${b.spacing(1)};
    }

    td {
      padding: 0 ${b.spacing(1)};
    }

    tr {
      height: 38px;
    }
  `,evenRow:c.css`
    background-color: ${b.colors.background.primary};
  `,colExpand:c.css`
    width: 36px;
  `,actionsCell:c.css`
    text-align: right;
    width: 1%;
    white-space: nowrap;

    & > * + * {
      margin-left: ${b.spacing(.5)};
    }
  `})},29125:(G,S,o)=>{o.d(S,{W:()=>c});var c=(C=>(C.Incident="grafana-incident-app",C.OnCall="grafana-oncall-app",C.MachineLearning="grafana-ml-app",C))(c||{})},97909:(G,S,o)=>{o.d(S,{G:()=>c});function c(C,b){const e=C.replace(/\(copy( [0-9]+)?\)$/,"").trim();let v=`${e} (copy)`;for(let T=2;b.includes(v);T++)v=`${e} (copy ${T})`;return v}}}]);

//# sourceMappingURL=NotificationsListPage.bab1953032b67cf0bbab.js.map