text: "use strict";(self.webpackChunkgrafana=self.webpackChunkgrafana||[]).push([[8831,335],{"./public/app/plugins/datasource/cloudwatch/metric-math/language.ts":(e,t,r)=>{r.r(t),r.d(t,{METRIC_MATH_FNS:()=>n,METRIC_MATH_KEYWORDS:()=>i,METRIC_MATH_OPERATORS:()=>a,METRIC_MATH_PERIODS:()=>o,METRIC_MATH_STATISTIC_KEYWORD_STRINGS:()=>s,conf:()=>u,language:()=>l});const n=["ABS","ANOMALY_DETECTION_BAND","AVG","CEIL","DATAPOINT_COUNT","DIFF","DIFF_TIME","FILL","FIRST","LAST","FLOOR","IF","INSIGHT_RULE_METRIC","LOG","LOG10","MAX","METRIC_COUNT","METRICS","MIN","MINUTE","HOUR","DAY","DATE","MONTH","YEAR","EPOCH","PERIOD","RATE","REMOVE_EMPTY","RUNNING_SUM","SEARCH","SERVICE_QUOTA","SLICE","SORT","STDDEV","SUM","TIME_SERIES"],s=["Average","Maximum","Minimum","Sum","SampleCount"],i=["REPEAT","LINEAR","ASC","DSC"],a=["+","-","*","/","^","==","!=","<=",">=","<",">","AND","&&","OR","||"],o=[10,60,300,900,3e3,21600,86400],l={id:"metricMath",ignoreCase:!1,brackets:[{open:"[",close:"]",token:"delimiter.square"},{open:"(",close:")",token:"delimiter.parenthesis"},{open:"{",close:"}",token:"delimiter.curly"}],tokenizer:{root:[{include:"@nonNestableStates"},{include:"@strings"}],nonNestableStates:[{include:"@variables"},{include:"@whitespace"},{include:"@numbers"},{include:"@assignment"},{include:"@keywords"},{include:"@operators"},{include:"@builtInFunctions"},[/[;,.]/,"delimiter"],[/[(){}\[\]]/,"@brackets"]],keywords:[[i.map(c).join("|"),"keyword"]],operators:[[a.map(c).join("|"),"operator"]],builtInFunctions:[[n.map(c).join("|"),"predefined"]],variables:[[/\$[a-zA-Z0-9-_]+/,"variable"]],whitespace:[[/\s+/,"white"]],assignment:[[/=/,"tag"]],numbers:[[/0[xX][0-9a-fA-F]*/,"number"],[/[$][+-]*\d*(\.\d*)?/,"number"],[/((\d+(\.\d*)?)|(\.\d+))([eE][\-+]?\d+)?/,"number"]],strings:[[/'/,{token:"string",next:"@string"}],[/"/,{token:"type",next:"@string_double"}]],string:[[/{/,{token:"delimiter.curly",next:"@nestedCurly"}],[/\(/,{token:"delimiter.parenthesis",next:"@nestedParens"}],[/"/,{token:"type",next:"@string_double"}],[/'/,{token:"string",next:"@pop"}],{include:"@nonNestableStates"},[/[^']/,"string"]],string_double:[[/[^"]/,"type"],[/"/,{token:"type",next:"@pop"}]],nestedCurly:[[/}/,{token:"delimiter.curly",next:"@pop"}],[/'/,{token:"string",next:"@string"}],[/"/,{token:"type",next:"@string_double"}]],nestedParens:[[/\)/,{token:"delimiter.parenthesis",next:"@pop"}],[/'/,{token:"string",next:"@string"}],[/"/,{token:"type",next:"@string_double"}]]}},u={brackets:[["{","}"],["[","]"],["(",")"]],autoClosingPairs:[{open:"{",close:"}"},{open:"[",close:"]"},{open:"(",close:")"},{open:'"',close:'"'},{open:"'",close:"'"}],surroundingPairs:[{open:"{",close:"}"},{open:"[",close:"]"},{open:"(",close:")"},{open:'"',close:'"'},{open:"'",close:"'"}]};function c(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}},"./public/app/plugins/datasource/cloudwatch/module.tsx":(e,t,r)=>{r.r(t),r.d(t,{plugin:()=>wt});var n,s,i,a=r("./packages/grafana-data/src/index.ts"),o=r("../../opt/drone/yarncache/lodash-npm-4.17.21-6382451519-eb835a2e51.zip/node_modules/lodash/lodash.js");class l{constructor(e){this.annotation=e.ctrl.annotation,(0,o.defaultsDeep)(this.annotation,{namespace:"",metricName:"",expression:"",dimensions:{},region:"default",id:"",alias:"",statistic:"Average",matchExact:!0,prefixMatching:!1,actionPrefix:"",alarmNamePrefix:""}),this.onChange=this.onChange.bind(this)}onChange(e){Object.assign(this.annotation,e)}}l.$inject=["$scope"],i="partials/annotations.editor.html",(s="templateUrl")in(n=l)?Object.defineProperty(n,s,{value:i,enumerable:!0,configurable:!0,writable:!0}):n[s]=i;var u,c,d=r("../../opt/drone/yarncache/react-npm-17.0.2-99ba37d931-b254cc17ce.zip/node_modules/react/index.js"),p=r("./.yarn/__virtual__/react-use-virtual-00326e70ba/3/opt/drone/yarncache/react-use-npm-17.3.2-a032cbeb01-7379460f51.zip/node_modules/react-use/esm/useDebounce.js"),m=r("../../opt/drone/yarncache/@grafana-aws-sdk-npm-0.0.35-2945fc38a2-c286e5ccaa.zip/node_modules/@grafana/aws-sdk/index.js"),h=r("./packages/grafana-ui/src/index.ts"),g=r("./public/app/core/actions/index.ts"),f=r("./public/app/core/copy/appNotification.ts"),v=r("./public/app/features/plugins/datasource_srv.ts"),y=r("./public/app/store/store.ts"),b=r("./.yarn/__virtual__/@emotion-css-virtual-72c314ddb1/3/opt/drone/yarncache/@emotion-css-npm-11.7.1-25ff8755a7-ac1f56656f.zip/node_modules/@emotion/css/dist/emotion-css.esm.js"),x=r("./packages/grafana-runtime/src/index.ts"),S=r("../../opt/drone/yarncache/react-npm-17.0.2-99ba37d931-b254cc17ce.zip/node_modules/react/jsx-runtime.js");const w=e=>({infoText:b.css`
      padding-bottom: ${e.spacing(2)};
      color: ${e.colors.text.secondary};
    `}),T="grafana-x-ray-datasource";function A(e){let{datasourceUid:t,onChange:r}=e;const n=Boolean((0,v.ak)().getList({pluginId:T}).length),s=(0,h.useStyles2)(w);return(0,S.jsxs)(S.Fragment,{children:[u||(u=(0,S.jsx)("h3",{className:"page-heading",children:"X-ray trace link"})),(0,S.jsx)("div",{className:s.infoText,children:"Grafana will automatically create a link to a trace in X-ray data source if logs contain @xrayTraceId field"}),!n&&(c||(c=(0,S.jsx)(h.Alert,{title:"There is no X-ray datasource to link to. First add an X-ray data source and then link it to Cloud Watch. ",severity:"info"}))),(0,S.jsx)("div",{className:"gf-form-group",children:(0,S.jsx)(h.InlineField,{htmlFor:"data-source-picker",label:"Data source",labelWidth:28,tooltip:"X-ray data source containing traces",children:(0,S.jsx)(x.DataSourcePicker,{pluginId:T,onChange:e=>r(e.uid),current:t,noDefault:!0})})})]})}var R;var C,j,I=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),F=(C=["",""],j=["",""],Object.freeze(Object.defineProperties(C,{raw:{value:Object.freeze(j)}})));function M(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var E=function(){function e(){for(var t=this,r=arguments.length,n=Array(r),s=0;s<r;s++)n[s]=arguments[s];return M(this,e),this.tag=function(e){for(var r=arguments.length,n=Array(r>1?r-1:0),s=1;s<r;s++)n[s-1]=arguments[s];return"function"==typeof e?t.interimTag.bind(t,e):"string"==typeof e?t.transformEndResult(e):(e=e.map(t.transformString.bind(t)),t.transformEndResult(e.reduce(t.processSubstitutions.bind(t,n))))},n.length>0&&Array.isArray(n[0])&&(n=n[0]),this.transformers=n.map((function(e){return"function"==typeof e?e():e})),this.tag}return I(e,[{key:"interimTag",value:function(e,t){for(var r=arguments.length,n=Array(r>2?r-2:0),s=2;s<r;s++)n[s-2]=arguments[s];return this.tag(F,e.apply(void 0,[t].concat(n)))}},{key:"processSubstitutions",value:function(e,t,r){var n=this.transformSubstitution(e.shift(),t);return"".concat(t,n,r)}},{key:"transformString",value:function(e){return this.transformers.reduce((function(e,t){return t.onString?t.onString(e):e}),e)}},{key:"transformSubstitution",value:function(e,t){return this.transformers.reduce((function(e,r){return r.onSubstitution?r.onSubstitution(e,t):e}),e)}},{key:"transformEndResult",value:function(e){return this.transformers.reduce((function(e,t){return t.onEndResult?t.onEndResult(e):e}),e)}}]),e}();const O=E;var k={separator:"",conjunction:"",serial:!1};const N=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:k;return{onSubstitution:function(t,r){if(Array.isArray(t)){var n=t.length,s=e.separator,i=e.conjunction,a=e.serial,o=r.match(/(\n?[^\S\n]+)$/);if(t=o?t.join(s+o[1]):t.join(s+" "),i&&n>1){var l=t.lastIndexOf(s);t=t.slice(0,l)+(a?s:"")+" "+i+t.slice(l+1)}}return t}}};function K(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t<e.length;t++)r[t]=e[t];return r}return Array.from(e)}const D=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"initial";return{onEndResult:function(t){if("initial"===e){var r=t.match(/^[^\S\n]*(?=\S)/gm),n=r&&Math.min.apply(Math,K(r.map((function(e){return e.length}))));if(n){var s=new RegExp("^.{"+n+"}","gm");return t.replace(s,"")}return t}if("all"===e)return t.replace(/^[^\S\n]+/gm,"");throw new Error("Unknown type: "+e)}}};const P=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";return{onEndResult:function(t){if(""===e)return t.trim();if("start"===(e=e.toLowerCase())||"left"===e)return t.replace(/^\s*/,"");if("end"===e||"right"===e)return t.replace(/\s*$/,"");throw new Error("Side not supported: "+e)}}};new O(N({separator:","}),D,P);new O(N({separator:",",conjunction:"and"}),D,P);new O(N({separator:",",conjunction:"or"}),D,P);const q=function(e){return{onSubstitution:function(t,r){if(null==e||"string"!=typeof e)throw new Error("You need to specify a string character to split by.");return"string"==typeof t&&t.includes(e)&&(t=t.split(e)),t}}};var L=function(e){return null!=e&&!Number.isNaN(e)&&"boolean"!=typeof e};const _=function(){return{onSubstitution:function(e){return Array.isArray(e)?e.filter(L):L(e)?e:""}}};new O(q("\n"),_,N,D,P);const V=function(e,t){return{onSubstitution:function(r,n){if(null==e||null==t)throw new Error("replaceSubstitutionTransformer requires at least 2 arguments.");return null==r?r:r.toString().replace(e,t)}}};new O(q("\n"),N,D,P,V(/&/g,"&amp;"),V(/</g,"&lt;"),V(/>/g,"&gt;"),V(/"/g,"&quot;"),V(/'/g,"&#x27;"),V(/`/g,"&#x60;"));const W=function(e,t){return{onEndResult:function(r){if(null==e||null==t)throw new Error("replaceResultTransformer requires at least 2 arguments.");return r.replace(e,t)}}};new O(W(/(?:\n(?:\s*))+/g," "),P);new O(W(/(?:\n\s*)/g,""),P);new O(N({separator:","}),W(/(?:\s+)/g," "),P);new O(N({separator:",",conjunction:"or"}),W(/(?:\s+)/g," "),P);new O(N({separator:",",conjunction:"and"}),W(/(?:\s+)/g," "),P);new O(N,D,P);new O(N,W(/(?:\s+)/g," "),P);const Q=new O(D,P);const B=new O(D("all"),P);var $,U,G=r("../../opt/drone/yarncache/prismjs-npm-1.27.0-ca4e1667c6-85c7f4a3e9.zip/node_modules/prismjs/prism.js"),z=r.n(G),H=r("./packages/grafana-ui/src/slate-plugins/slate-prism/index.ts"),X=r("./public/app/plugins/datasource/cloudwatch/syntax.ts");const Y=[{category:"Lambda",examples:[{title:"View latency statistics for 5-minute intervals",expr:B`filter @type = "REPORT" |
                             stats avg(@duration), max(@duration), min(@duration) by bin(5m)`},{title:"Determine the amount of overprovisioned memory",expr:Q`
          filter @type = "REPORT" |
          stats max(@memorySize / 1024 / 1024) as provisonedMemoryMB,
                min(@maxMemoryUsed / 1024 / 1024) as smallestMemoryRequestMB,
                avg(@maxMemoryUsed / 1024 / 1024) as avgMemoryUsedMB,
                max(@maxMemoryUsed / 1024 / 1024) as maxMemoryUsedMB,
                provisonedMemoryMB - maxMemoryUsedMB as overProvisionedMB`},{title:"Find the most expensive requests",expr:B`filter @type = "REPORT" |
                             fields @requestId, @billedDuration |
                             sort by @billedDuration desc`}]},{category:"VPC Flow Logs",examples:[{title:"Average, min, and max byte transfers by source and destination IP addresses",expr:"stats avg(bytes), min(bytes), max(bytes) by srcAddr, dstAddr"},{title:"IP addresses using UDP transfer protocol",expr:"filter protocol=17 | stats count(*) by srcAddr"},{title:"Top 10 byte transfers by source and destination IP addresses",expr:B`stats sum(bytes) as bytesTransferred by srcAddr, dstAddr |
                             sort bytesTransferred desc |
                             limit 10`},{title:"Top 20 source IP addresses with highest number of rejected requests",expr:B`filter action="REJECT" |
                             stats count(*) as numRejections by srcAddr |
                             sort numRejections desc |
                             limit 20`}]},{category:"CloudTrail",examples:[{title:"Number of log entries by service, event type, and region",expr:"stats count(*) by eventSource, eventName, awsRegion"},{title:"Number of log entries by region and EC2 event type",expr:B`filter eventSource="ec2.amazonaws.com" |
                             stats count(*) as eventCount by eventName, awsRegion |
                             sort eventCount desc`},{title:"Regions, usernames, and ARNs of newly created IAM users",expr:B`filter eventName="CreateUser" |
                             fields awsRegion, requestParameters.userName, responseElements.user.arn`}]},{category:"Common Queries",examples:[{title:"25 most recently added log events",expr:B`fields @timestamp, @message |
                             sort @timestamp desc |
                             limit 25`},{title:"Number of exceptions logged every 5 minutes",expr:B`filter @message like /Exception/ |
                             stats count(*) as exceptionCount by bin(5m) |
                             sort exceptionCount desc`},{title:"List of log events that are not exceptions",expr:"fields @message | filter @message not like /Exception/"}]},{category:"Route 53",examples:[{title:"Number of requests received every 10  minutes by edge location",expr:"stats count(*) by queryType, bin(10m)"},{title:"Number of unsuccessful requests by domain",expr:'filter responseCode="SERVFAIL" | stats count(*) by queryName'},{title:"Number of requests received every 10  minutes by edge location",expr:"stats count(*) as numRequests by resolverIp | sort numRequests desc | limit 10"}]},{category:"AWS AppSync",examples:[{title:"Number of unique HTTP status codes",expr:B`fields ispresent(graphQLAPIId) as isApi |
                             filter isApi |
                             filter logType = "RequestSummary" |
                             stats count() as statusCount by statusCode |
                             sort statusCount desc`},{title:"Top 10 resolvers with maximum latency",expr:B`fields resolverArn, duration |
                             filter logType = "Tracing" |
                             sort duration desc |
                             limit 10`},{title:"Most frequently invoked resolvers",expr:B`fields ispresent(resolverArn) as isRes |
                             stats count() as invocationCount by resolverArn |
                             filter isRes |
                             filter logType = "Tracing" |
                             sort invocationCount desc |
                             limit 10`},{title:"Resolvers with most errors in mapping templates",expr:B`fields ispresent(resolverArn) as isRes |
                             stats count() as errorCount by resolverArn, logType |
                             filter isRes and (logType = "RequestMapping" or logType = "ResponseMapping") and fieldInError |
                             sort errorCount desc |
                             limit 10`},{title:"Field latency statistics",expr:B`fields requestId, latency |
                             filter logType = "RequestSummary" |
                             sort latency desc |
                             limit 10`},{title:"Resolver latency statistics",expr:B`fields ispresent(resolverArn) as isRes |
                             filter isRes |
                             filter logType = "Tracing" |
                             stats min(duration), max(duration), avg(duration) as avgDur by resolverArn |
                             sort avgDur desc |
                             limit 10`},{title:"Top 10 requests with maximum latency",expr:B`fields requestId, latency |
                             filter logType = "RequestSummary" |
                             sort latency desc |
                             limit 10`}]}];function J(e,t){const r=X.ZP,n=(0,H.a)(z().tokenize(e,r)).filter((e=>"string"!=typeof e)).map(((e,r)=>(0,S.jsx)("span",{className:`prism-token token ${e.types.join(" ")} ${e.aliases.join(" ")}`,children:e.content},`${t}-token-${r}`)));return(0,S.jsx)("div",{className:"slate-query-field",children:n})}const Z=b.css`
    margin-top: 5px;
  `;class ee extends d.PureComponent{onClickExample(e){this.props.onClickExample(e)}renderExpression(e,t){return(0,S.jsx)("div",{className:"cheat-sheet-item__example",onClick:()=>{var t,r;return this.onClickExample({refId:null!==(t=this.props.query.refId)&&void 0!==t?t:"A",expression:e,queryMode:"Logs",region:this.props.query.region,id:null!==(r=this.props.query.refId)&&void 0!==r?r:"A",logGroupNames:"logGroupNames"in this.props.query?this.props.query.logGroupNames:[]})},children:(0,S.jsx)("pre",{children:J(e,t)})},e)}renderLogsCheatSheet(){return(0,S.jsxs)("div",{children:[$||($=(0,S.jsx)("h2",{children:"CloudWatch Logs Cheat Sheet"})),Y.map(((e,t)=>(0,S.jsxs)("div",{children:[(0,S.jsx)("div",{className:`cheat-sheet-item__title ${(0,b.cx)(Z)}`,children:e.category}),e.examples.map(((e,t)=>(0,S.jsxs)("div",{className:"cheat-sheet-item",children:[(0,S.jsx)("h4",{children:e.title}),this.renderExpression(e.expr,`item-${t}`)]},`item-${t}`)))]},`${e.category}-${t}`)))]})}render(){return(0,S.jsxs)("div",{children:[U||(U=(0,S.jsx)("h3",{children:"CloudWatch Logs cheat sheet"})),Y.map(((e,t)=>(0,S.jsxs)("div",{children:[(0,S.jsx)("div",{className:`cheat-sheet-item__title ${(0,b.cx)(Z)}`,children:e.category}),e.examples.map(((e,t)=>(0,S.jsxs)("div",{className:"cheat-sheet-item",children:[(0,S.jsx)("h4",{children:e.title}),this.renderExpression(e.expr,`item-${t}`)]},`item-${t}`)))]},`cat-${t}`)))]})}}var te,re=r("./public/app/plugins/datasource/cloudwatch/components/LogsQueryEditor.tsx");var ne=r("./public/app/plugins/datasource/cloudwatch/components/PanelQueryEditor.tsx"),se=r("../../opt/drone/yarncache/rxjs-npm-7.5.5-d0546b1ccb-e034f60805.zip/node_modules/rxjs/dist/esm5/internal/observable/of.js"),ie=r("../../opt/drone/yarncache/rxjs-npm-7.5.5-d0546b1ccb-e034f60805.zip/node_modules/rxjs/dist/esm5/internal/observable/from.js"),ae=r("../../opt/drone/yarncache/rxjs-npm-7.5.5-d0546b1ccb-e034f60805.zip/node_modules/rxjs/dist/esm5/internal/lastValueFrom.js"),oe=r("../../opt/drone/yarncache/rxjs-npm-7.5.5-d0546b1ccb-e034f60805.zip/node_modules/rxjs/dist/esm5/internal/observable/merge.js"),le=r("../../opt/drone/yarncache/rxjs-npm-7.5.5-d0546b1ccb-e034f60805.zip/node_modules/rxjs/dist/esm5/internal/observable/zip.js"),ue=r("../../opt/drone/yarncache/rxjs-npm-7.5.5-d0546b1ccb-e034f60805.zip/node_modules/rxjs/dist/esm5/internal/observable/throwError.js"),ce=r("../../opt/drone/yarncache/rxjs-npm-7.5.5-d0546b1ccb-e034f60805.zip/node_modules/rxjs/dist/esm5/internal/Observable.js"),de=r("../../opt/drone/yarncache/rxjs-npm-7.5.5-d0546b1ccb-e034f60805.zip/node_modules/rxjs/dist/esm5/internal/operators/mergeMap.js"),pe=r("../../opt/drone/yarncache/rxjs-npm-7.5.5-d0546b1ccb-e034f60805.zip/node_modules/rxjs/dist/esm5/internal/operators/map.js"),me=r("../../opt/drone/yarncache/rxjs-npm-7.5.5-d0546b1ccb-e034f60805.zip/node_modules/rxjs/dist/esm5/internal/operators/concatMap.js"),he=r("../../opt/drone/yarncache/rxjs-npm-7.5.5-d0546b1ccb-e034f60805.zip/node_modules/rxjs/dist/esm5/internal/operators/repeat.js"),ge=r("../../opt/drone/yarncache/rxjs-npm-7.5.5-d0546b1ccb-e034f60805.zip/node_modules/rxjs/dist/esm5/internal/operators/share.js"),fe=r("../../opt/drone/yarncache/rxjs-npm-7.5.5-d0546b1ccb-e034f60805.zip/node_modules/rxjs/dist/esm5/internal/operators/scan.js"),ve=r("../../opt/drone/yarncache/rxjs-npm-7.5.5-d0546b1ccb-e034f60805.zip/node_modules/rxjs/dist/esm5/internal/operators/tap.js"),ye=r("../../opt/drone/yarncache/rxjs-npm-7.5.5-d0546b1ccb-e034f60805.zip/node_modules/rxjs/dist/esm5/internal/operators/takeWhile.js"),be=r("../../opt/drone/yarncache/rxjs-npm-7.5.5-d0546b1ccb-e034f60805.zip/node_modules/rxjs/dist/esm5/internal/operators/finalize.js"),xe=r("../../opt/drone/yarncache/rxjs-npm-7.5.5-d0546b1ccb-e034f60805.zip/node_modules/rxjs/dist/esm5/internal/operators/catchError.js"),Se=r("./public/app/features/dashboard/services/TimeSrv.ts"),we=r("./public/app/features/templating/template_srv.ts"),Te=r("./public/app/types/index.ts");class Ae{constructor(e,t,r,n,s,i){this.type=e,this.value=t,this.range=r,this.previous=n,this.next=s,this.tokenTypes=i,this.type=e,this.value=t,this.range=r,this.previous=n,this.next=s,this.tokenTypes=i}isKeyword(){return this.type===this.tokenTypes.Keyword}isWhiteSpace(){return this.type===this.tokenTypes.Whitespace}isParenthesis(){return this.type===this.tokenTypes.Parenthesis}isIdentifier(){return this.type===this.tokenTypes.Identifier}isString(){return this.type===this.tokenTypes.String}isDoubleQuotedString(){return this.type===this.tokenTypes.Type}isVariable(){return this.type===this.tokenTypes.Variable}isFunction(){return this.type===this.tokenTypes.Function}isNumber(){return this.type===this.tokenTypes.Number}is(e,t){const r=this.type===e;return void 0!==t?r&&this.value===t:r}endsWith(e){return this.value===e||this.value[this.value.length-1]===e}getPreviousNonWhiteSpaceToken(){let e=this.previous;for(;null!=e;){if(!e.isWhiteSpace())return e;e=e.previous}return null}getPreviousOfType(e,t){let r=this.previous;for(;null!=r;){const n=r.type===e;if(void 0!==t?n&&r.value===t:n)return r;r=r.previous}return null}getPreviousUntil(e,t,r){let n=[],s=this.previous;for(;null!=s;){if(t.some((e=>{var t;return e===(null===(t=s)||void 0===t?void 0:t.type)}))){s=s.previous;continue}const i=s.type===e;if(void 0!==r?i&&s.value===r:i)return n;s.isWhiteSpace()||n.push(s),s=s.previous}return n}getNextUntil(e,t,r){let n=[],s=this.next;for(;null!=s;){if(t.some((e=>{var t;return e===(null===(t=s)||void 0===t?void 0:t.type)}))){s=s.next;continue}const i=s.type===e;if(void 0!==r?i&&s.value===r:i)return n;s.isWhiteSpace()||n.push(s),s=s.next}return n}getPreviousKeyword(){let e=this.previous;for(;null!=e;){if(e.isKeyword())return e;e=e.previous}return null}getNextNonWhiteSpaceToken(){let e=this.next;for(;null!=e;){if(!e.isWhiteSpace())return e;e=e.next}return null}getNextOfType(e,t){let r=this.next;for(;null!=r;){const n=r.type===e;if(void 0!==t?n&&r.value===t:n)return r;r=r.next}return null}}let Re,Ce,je;function Ie(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}!function(e){e[e.Unknown=0]="Unknown",e[e.SelectKeyword=1]="SelectKeyword",e[e.AfterSelectKeyword=2]="AfterSelectKeyword",e[e.AfterSelectFuncFirstArgument=3]="AfterSelectFuncFirstArgument",e[e.AfterFromKeyword=4]="AfterFromKeyword",e[e.SchemaFuncFirstArgument=5]="SchemaFuncFirstArgument",e[e.SchemaFuncExtraArgument=6]="SchemaFuncExtraArgument",e[e.FromKeyword=7]="FromKeyword",e[e.AfterFrom=8]="AfterFrom",e[e.WhereKey=9]="WhereKey",e[e.WhereComparisonOperator=10]="WhereComparisonOperator",e[e.WhereValue=11]="WhereValue",e[e.AfterWhereValue=12]="AfterWhereValue",e[e.AfterGroupByKeywords=13]="AfterGroupByKeywords",e[e.AfterGroupBy=14]="AfterGroupBy",e[e.AfterOrderByKeywords=15]="AfterOrderByKeywords",e[e.AfterOrderByFunction=16]="AfterOrderByFunction",e[e.AfterOrderByDirection=17]="AfterOrderByDirection",e[e.PredefinedFunction=18]="PredefinedFunction",e[e.SearchFuncSecondArg=19]="SearchFuncSecondArg",e[e.SearchFuncThirdArg=20]="SearchFuncThirdArg",e[e.PredefinedFuncSecondArg=21]="PredefinedFuncSecondArg",e[e.AfterFunction=22]="AfterFunction",e[e.WithinString=23]="WithinString"}(Re||(Re={})),function(e){e[e.SelectKeyword=0]="SelectKeyword",e[e.FunctionsWithArguments=1]="FunctionsWithArguments",e[e.Metrics=2]="Metrics",e[e.FromKeyword=3]="FromKeyword",e[e.SchemaKeyword=4]="SchemaKeyword",e[e.Namespaces=5]="Namespaces",e[e.LabelKeys=6]="LabelKeys",e[e.WhereKeyword=7]="WhereKeyword",e[e.GroupByKeywords=8]="GroupByKeywords",e[e.OrderByKeywords=9]="OrderByKeywords",e[e.FunctionsWithoutArguments=10]="FunctionsWithoutArguments",e[e.LimitKeyword=11]="LimitKeyword",e[e.SortOrderDirectionKeyword=12]="SortOrderDirectionKeyword",e[e.ComparisonOperators=13]="ComparisonOperators",e[e.LabelValues=14]="LabelValues",e[e.LogicalOperators=15]="LogicalOperators",e[e.KeywordArguments=16]="KeywordArguments",e[e.Operators=17]="Operators",e[e.Statistic=18]="Statistic",e[e.Period=19]="Period"}(Ce||(Ce={})),function(e){e.High="a",e.MediumHigh="d",e.Medium="g",e.MediumLow="k",e.Low="q"}(je||(je={}));class Fe{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:(0,x.getTemplateSrv)();Ie(this,"templateVariables",void 0),Ie(this,"datasource",void 0),Ie(this,"templateSrv",void 0),Ie(this,"tokenTypes",void 0),this.datasource=e,this.templateSrv=t,this.templateVariables=this.datasource.getVariables(),this.templateSrv=t,this.tokenTypes={Parenthesis:"delimiter.parenthesis",Whitespace:"white",Keyword:"keyword",Delimiter:"delimiter",Operator:"operator",Identifier:"identifier",Type:"type",Function:"predefined",Number:"number",String:"string",Variable:"variable"}}getStatementPosition(e){return Re.Unknown}getSuggestionKinds(e){return[]}getSuggestions(e,t,r,n,s){return Promise.reject([])}getCompletionProvider(e,t){return{triggerCharacters:[" ","$",",","(","'"],provideCompletionItems:async(r,n)=>{const s=function(e,t,r,n,s){var i;let a=null,o=null;const l=e.editor.tokenize(null!==(i=r.getValue())&&void 0!==i?i:"",t.id);for(let i=0;i<l.length;i++){const u=l[i];if(!u.length&&o){const e={offset:0,type:s.Whitespace,language:t.id,_tokenBrand:void 0};u.push(e)}for(let t=0;t<u.length;t++){const l=u[t];let c=u.length>t+1?u[t+1].offset+1:r.getLineLength(i+1)+1;const d={startLineNumber:i+1,startColumn:0===l.offset?0:l.offset+1,endLineNumber:i+1,endColumn:c},p=r.getValueInRange(d),m=new Ae(l.type,p,d,o,null,s);e.Range.containsPosition(d,n)&&(a=m),o&&(o.next=m),o=m}}return a}(e,t,r,n,this.tokenTypes),i=this.getStatementPosition(s),a=this.getSuggestionKinds(i);return{suggestions:await this.getSuggestions(e,s,a,i,n)}}}}}var Me=r("./public/app/plugins/datasource/cloudwatch/monarch/commands.ts"),Ee=r("./public/app/plugins/datasource/cloudwatch/cloudwatch-sql/language.ts");const Oe={Parenthesis:"delimiter.parenthesis.sql",Whitespace:"white.sql",Keyword:"keyword.sql",Delimiter:"delimiter.sql",Operator:"operator.sql",Identifier:"identifier.sql",Type:"type.sql",Function:"predefined.sql",Number:"number.sql",String:"string.sql",Variable:"variable.sql"};function ke(e){var t,r,n,s,i,a;const o=null==e?void 0:e.getPreviousNonWhiteSpaceToken(),l=null==e?void 0:e.getPreviousKeyword(),u=null==e||null===(t=e.getPreviousNonWhiteSpaceToken())||void 0===t?void 0:t.is(Oe.Operator,"/");return null===e||e.isWhiteSpace()&&null===e.previous||e.is(Oe.Keyword,Ee.SELECT)&&null===e.previous||u||e.isIdentifier()&&(u||null===(null==e?void 0:e.previous))?Re.SelectKeyword:(null==o?void 0:o.value)===Ee.SELECT?Re.AfterSelectKeyword:(null!=o&&o.is(Oe.Parenthesis,"(")||null!=e&&e.is(Oe.Parenthesis,"()"))&&(null==l?void 0:l.value)===Ee.SELECT?Re.AfterSelectFuncFirstArgument:(null==l?void 0:l.value)===Ee.SELECT&&null!=o&&o.isParenthesis()?Re.FromKeyword:(null==o?void 0:o.value)===Ee.FROM?Re.AfterFromKeyword:(null!=o&&o.is(Oe.Parenthesis,"(")||null!=e&&e.is(Oe.Parenthesis,"()"))&&(null==l?void 0:l.value)===Ee.SCHEMA?Re.SchemaFuncFirstArgument:(null==l?void 0:l.value)===Ee.SCHEMA&&null!=o&&o.is(Oe.Delimiter,",")?Re.SchemaFuncExtraArgument:(null==l?void 0:l.value)===Ee.FROM&&null!=o&&o.isDoubleQuotedString()||(null==l?void 0:l.value)===Ee.FROM&&null!=o&&o.isVariable()||(null==l?void 0:l.value)===Ee.SCHEMA&&null!=o&&o.is(Oe.Parenthesis,")")?Re.AfterFrom:(null==l?void 0:l.value)===Ee.WHERE&&(null!=o&&o.isKeyword()||null!=o&&o.is(Oe.Parenthesis,"(")||null!=o&&o.is(Oe.Operator,Ee.AND))?Re.WhereKey:(null==l?void 0:l.value)===Ee.WHERE&&(null!=o&&o.isIdentifier()||null!=o&&o.isDoubleQuotedString())?Re.WhereComparisonOperator:(null==l?void 0:l.value)===Ee.WHERE&&(null!=o&&o.is(Oe.Operator,Ee.EQUALS)||null!=o&&o.is(Oe.Operator,Ee.NOT_EQUALS))?Re.WhereValue:(null==l?void 0:l.value)===Ee.WHERE&&(null!=o&&o.isString()||null!=o&&o.is(Oe.Parenthesis,")"))?Re.AfterWhereValue:null!=l&&l.is(Oe.Keyword,Ee.BY)&&null!=l&&null!==(r=l.getPreviousKeyword())&&void 0!==r&&r.is(Oe.Keyword,Ee.GROUP)&&(null!=o&&o.is(Oe.Keyword,Ee.BY)||null!=o&&o.is(Oe.Delimiter,","))?Re.AfterGroupByKeywords:null!=l&&l.is(Oe.Keyword,Ee.BY)&&null!=l&&null!==(n=l.getPreviousKeyword())&&void 0!==n&&n.is(Oe.Keyword,Ee.GROUP)&&(null!=o&&o.isIdentifier()||null!=o&&o.isDoubleQuotedString())?Re.AfterGroupBy:null!=o&&o.is(Oe.Keyword,Ee.BY)&&null!=o&&null!==(s=o.getPreviousKeyword())&&void 0!==s&&s.is(Oe.Keyword,Ee.ORDER)?Re.AfterOrderByKeywords:null!=l&&l.is(Oe.Keyword,Ee.BY)&&null!=l&&null!==(i=l.getPreviousKeyword())&&void 0!==i&&i.is(Oe.Keyword,Ee.ORDER)&&null!=o&&o.is(Oe.Parenthesis)&&null!=o&&null!==(a=o.getPreviousNonWhiteSpaceToken())&&void 0!==a&&a.is(Oe.Function)?Re.AfterOrderByFunction:null!=l&&l.is(Oe.Keyword,Ee.DESC)||null!=l&&l.is(Oe.Keyword,Ee.ASC)?Re.AfterOrderByDirection:Re.Unknown}function Ne(e){switch(e){case Re.SelectKeyword:return[Ce.SelectKeyword];case Re.AfterSelectKeyword:return[Ce.FunctionsWithArguments];case Re.AfterSelectFuncFirstArgument:return[Ce.Metrics];case Re.AfterFromKeyword:return[Ce.Namespaces,Ce.SchemaKeyword];case Re.SchemaFuncFirstArgument:return[Ce.Namespaces];case Re.SchemaFuncExtraArgument:return[Ce.LabelKeys];case Re.FromKeyword:return[Ce.FromKeyword];case Re.AfterFrom:return[Ce.WhereKeyword,Ce.GroupByKeywords,Ce.OrderByKeywords,Ce.LimitKeyword];case Re.WhereKey:return[Ce.LabelKeys];case Re.WhereComparisonOperator:return[Ce.ComparisonOperators];case Re.WhereValue:return[Ce.LabelValues];case Re.AfterWhereValue:return[Ce.LogicalOperators,Ce.GroupByKeywords,Ce.OrderByKeywords,Ce.LimitKeyword];case Re.AfterGroupByKeywords:return[Ce.LabelKeys];case Re.AfterGroupBy:return[Ce.OrderByKeywords,Ce.LimitKeyword];case Re.AfterOrderByKeywords:return[Ce.FunctionsWithoutArguments];case Re.AfterOrderByFunction:return[Ce.SortOrderDirectionKeyword,Ce.LimitKeyword];case Re.AfterOrderByDirection:return[Ce.LimitKeyword]}return[]}const Ke=e=>{var t;return null!==(t=null==e?void 0:e.getPreviousOfType(Oe.Keyword,Ee.SELECT))&&void 0!==t?t:null},De=e=>{var t,r;const n=null===(t=(e=>{var t;const r=null===(t=Ke(e))||void 0===t?void 0:t.getNextNonWhiteSpaceToken();return null!=r&&r.isVariable()||null!=r&&r.isFunction()?r:null})(e))||void 0===t||null===(r=t.next)||void 0===r?void 0:r.next;return null!=n&&n.isVariable()||null!=n&&n.isIdentifier()?n:null},Pe=e=>{var t;const r=(e=>{const t=Ke(e);return null==t?void 0:t.getNextOfType(Oe.Keyword,Ee.FROM)})(e),n=null==r?void 0:r.getNextNonWhiteSpaceToken();if(null!=n&&n.isDoubleQuotedString()||null!=n&&n.isVariable()&&(null==n?void 0:n.value.toUpperCase())!==Ee.SCHEMA)return n;if(null!=n&&n.isKeyword()&&null!==(t=n.next)&&void 0!==t&&t.is(Oe.Parenthesis,"(")){var s;const e=null===(s=n.next)||void 0===s?void 0:s.next;if(null!=e&&e.isDoubleQuotedString()||null!=e&&e.isVariable())return e}return null};class qe extends Fe{constructor(e){super(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:(0,x.getTemplateSrv)()),function(e,t,r){t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r}(this,"region",void 0),this.region=e.getActualRegion(),this.getStatementPosition=ke,this.getSuggestionKinds=Ne,this.tokenTypes=Oe}setRegion(e){this.region=e}async getSuggestions(e,t,r,n,s){let i=[];const a=(null==t?void 0:t.isWhiteSpace())||(null==t?void 0:t.isParenthesis())||null==t||!t.range?e.Range.fromPositions(s):null==t?void 0:t.range,l=function(t){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const n=Object.assign({label:t,insertText:t,kind:e.languages.CompletionItemKind.Field,range:a,sortText:je.Medium},r);return n};function u(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};i=[...i,l(e,t)]}for(const s of r)switch(s){case Ce.SelectKeyword:u(Ee.SELECT,{insertText:`${Ee.SELECT} $0`,insertTextRules:e.languages.CompletionItemInsertTextRule.InsertAsSnippet,kind:e.languages.CompletionItemKind.Keyword,command:Me.w});break;case Ce.FunctionsWithArguments:Ee.STATISTICS.map((t=>u(t,{insertText:`${t}($0)`,insertTextRules:e.languages.CompletionItemInsertTextRule.InsertAsSnippet,command:Me.w,kind:e.languages.CompletionItemKind.Function})));break;case Ce.FunctionsWithoutArguments:Ee.STATISTICS.map((t=>u(t,{insertText:`${t}() `,insertTextRules:e.languages.CompletionItemInsertTextRule.InsertAsSnippet,command:Me.w,kind:e.languages.CompletionItemKind.Function})));break;case Ce.Metrics:{const e=Pe(t);if(null!=e&&e.value){(await this.datasource.getMetrics(this.templateSrv.replace(null==e?void 0:e.value.replace(/\"/g,"")),this.templateSrv.replace(this.region))).map((e=>u(e.value)))}else{const e=await this.datasource.getAllMetrics(this.templateSrv.replace(this.region));(0,o.uniq)(e.map((e=>e.metricName))).map((e=>u(e,{insertText:e})))}}break;case Ce.FromKeyword:u(Ee.FROM,{insertText:`${Ee.FROM} `,command:Me.w});break;case Ce.SchemaKeyword:u(Ee.SCHEMA,{sortText:je.High,insertText:`${Ee.SCHEMA}($0)`,insertTextRules:e.languages.CompletionItemInsertTextRule.InsertAsSnippet,command:Me.w,kind:e.languages.CompletionItemKind.Function});break;case Ce.Namespaces:const r=De(t);let s=[];if(null!=r&&r.value){const e=await this.datasource.getAllMetrics(this.region),t=this.templateSrv.replace(r.value);s=e.filter((e=>e.metricName===t)).map((e=>e.namespace))}else{s=(await this.datasource.getNamespaces()).map((e=>e.value))}s.map((e=>u(`"${e}"`,{insertText:`"${e}"`})));break;case Ce.LabelKeys:{const e=De(t),r=Pe(t);if(null!=r&&r.value){var c;let s,i={};n===Re.SchemaFuncExtraArgument?s=null==r?void 0:r.getNextUntil(this.tokenTypes.Parenthesis,[this.tokenTypes.Delimiter,this.tokenTypes.Whitespace]):n===Re.AfterGroupByKeywords&&(s=null==t?void 0:t.getPreviousUntil(this.tokenTypes.Keyword,[this.tokenTypes.Delimiter,this.tokenTypes.Whitespace])),i=(s||[]).reduce(((e,t)=>Object.assign({},e,{[t.value]:null})),{});(await this.datasource.getDimensionKeys(this.templateSrv.replace(r.value.replace(/\"/g,"")),this.templateSrv.replace(this.region),i,null!==(c=null==e?void 0:e.value)&&void 0!==c?c:"")).map((e=>{u(/[\s\.-]/.test(e.value)?`"${e.value}"`:e.value)}))}}break;case Ce.LabelValues:{var d;const e=Pe(t),r=De(t),n=null==t||null===(d=t.getPreviousNonWhiteSpaceToken())||void 0===d?void 0:d.getPreviousNonWhiteSpaceToken();if(null!=e&&e.value&&null!=n&&n.value&&null!=r&&r.value){(await this.datasource.getDimensionValues(this.templateSrv.replace(this.region),this.templateSrv.replace(e.value.replace(/\"/g,"")),this.templateSrv.replace(r.value),this.templateSrv.replace(n.value),{})).map((e=>u(`'${e.value}'`,{insertText:`'${e.value}' `,command:Me.w})))}}break;case Ce.LogicalOperators:Ee.LOGICAL_OPERATORS.map((e=>u(`${e}`,{insertText:`${e} `,command:Me.w,sortText:je.MediumHigh})));break;case Ce.WhereKeyword:u(`${Ee.WHERE}`,{insertText:`${Ee.WHERE} `,command:Me.w,sortText:je.High});break;case Ce.ComparisonOperators:Ee.COMPARISON_OPERATORS.map((e=>u(`${e}`,{insertText:`${e} `,command:Me.w})));break;case Ce.GroupByKeywords:u(`${Ee.GROUP} ${Ee.BY}`,{insertText:`${Ee.GROUP} ${Ee.BY} `,command:Me.w,sortText:je.MediumHigh});break;case Ce.OrderByKeywords:u(`${Ee.ORDER} ${Ee.BY}`,{insertText:`${Ee.ORDER} ${Ee.BY} `,command:Me.w,sortText:je.Medium});break;case Ce.LimitKeyword:u(Ee.LIMIT,{insertText:`${Ee.LIMIT} `,sortText:je.MediumLow});break;case Ce.SortOrderDirectionKeyword:[Ee.ASC,Ee.DESC].map((e=>u(e,{insertText:`${e} `,command:Me.w})))}return this.templateVariables.map((t=>{u(t,{range:a,label:t,insertText:t,kind:e.languages.CompletionItemKind.Variable,sortText:je.Low})})),i}}var Le;const _e=e=>{let{region:t}=e;return(0,S.jsxs)("p",{children:["Please visit the ",(0,S.jsx)("a",{target:"_blank",rel:"noreferrer",className:"text-link",href:`https://${t}.console.aws.amazon.com/servicequotas/home?region=${t}#!/services/monitoring/quotas/L-5E141212`,children:"AWS Service Quotas console"})," to request a quota increase or see our ",Le||(Le=(0,S.jsx)("a",{target:"_blank",rel:"noreferrer",className:"text-link",href:"https://grafana.com/docs/grafana/latest/datasources/cloudwatch/#service-quotas",children:"documentation"}))," to learn more."]})};function Ve(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}class We extends a.LanguageProvider{constructor(e,t){super(),Ve(this,"started",!1),Ve(this,"datasource",void 0),Ve(this,"cleanText",(e=>e.replace(/[()]/g,"").trim())),Ve(this,"request",((e,t)=>(0,ae.n)(this.datasource.awsRequest(e,t)))),Ve(this,"start",(()=>(this.startTask||(this.startTask=Promise.resolve().then((()=>(this.started=!0,[])))),this.startTask))),Ve(this,"fetchedFieldsCache",void 0),Ve(this,"fetchFields",(async(e,t)=>{if(this.fetchedFieldsCache&&Date.now()-this.fetchedFieldsCache.time<3e4&&(0,o.sortedUniq)(this.fetchedFieldsCache.logGroups).join("|")===(0,o.sortedUniq)(e).join("|"))return this.fetchedFieldsCache.fields;const r=await Promise.all(e.map((e=>this.datasource.getLogGroupFields({logGroupName:e,region:t})))),n=[...new Set(r.reduce(((e,t)=>{var r;return e.concat(null===(r=t.logGroupFields)||void 0===r?void 0:r.map((e=>e.name)))}),[])).values()];return this.fetchedFieldsCache={time:Date.now(),logGroups:e,fields:n},n})),Ve(this,"handleKeyword",(async e=>{var t;const r=await this.getFieldCompletionItems(null!==(t=null==e?void 0:e.logGroupNames)&&void 0!==t?t:[],(null==e?void 0:e.region)||"default"),n=[{searchFunctionType:h.SearchFunctionType.Prefix,label:"Functions",items:X.Bn.concat(X.ae,X.Ie)}];return r.suggestions.push(...n),r})),Ve(this,"handleCommand",(async(e,t,r)=>{var n;const s=e.content.toLowerCase(),i=Qe(t),a=i===e;if("sort"===s)return this.handleSortCommand(a,t,r);var o;if("parse"===s&&a)return await this.getFieldCompletionItems(null!==(o=null==r?void 0:r.logGroupNames)&&void 0!==o?o:[],(null==r?void 0:r.region)||"default");const l=$e(e.next,"whitespace")&&!(null!==(n=e.next)&&void 0!==n&&n.next),u=l||function(e){let t=e;for(;t.next;){if(!t.next.types.includes("whitespace"))return t.next;t=t.next}return null}(e)===t,c=$e(t,"punctuation",","),d=c||$e(i,"punctuation",",");if(!u&&!d)return{suggestions:[]};if(["display","fields"].includes(s)){var p;const e=await this.getFieldCompletionItems(null!==(p=null==r?void 0:r.logGroupNames)&&void 0!==p?p:[],(null==r?void 0:r.region)||"default");return e.suggestions.push(...this.getFieldAndFilterFunctionCompletionItems().suggestions),e}if("stats"===s){const e=this.getStatsAggCompletionItems();return(c||l)&&(null==e||e.suggestions.forEach((e=>{e.skipFilter=!0}))),e}if("filter"===s&&a){var m;const e=await this.getFieldCompletionItems(null!==(m=null==r?void 0:r.logGroupNames)&&void 0!==m?m:[],(null==r?void 0:r.region)||"default"),t=this.getBoolFuncCompletionItems();return e.suggestions.push(...t.suggestions),e}return{suggestions:[]}})),Ve(this,"handleComparison",(async e=>{var t;const r=await this.getFieldCompletionItems(null!==(t=null==e?void 0:e.logGroupNames)&&void 0!==t?t:[],(null==e?void 0:e.region)||"default"),n=this.getComparisonCompletionItems();return r.suggestions.push(...n.suggestions),r})),Ve(this,"getCommandCompletionItems",(()=>({suggestions:[{searchFunctionType:h.SearchFunctionType.Prefix,label:"Commands",items:X.lD}]}))),Ve(this,"getFieldAndFilterFunctionCompletionItems",(()=>({suggestions:[{searchFunctionType:h.SearchFunctionType.Prefix,label:"Functions",items:X.Ak}]}))),Ve(this,"getStatsAggCompletionItems",(()=>({suggestions:[{searchFunctionType:h.SearchFunctionType.Prefix,label:"Functions",items:X.QZ}]}))),Ve(this,"getBoolFuncCompletionItems",(()=>({suggestions:[{searchFunctionType:h.SearchFunctionType.Prefix,label:"Functions",items:X.aH}]}))),Ve(this,"getComparisonCompletionItems",(()=>({suggestions:[{searchFunctionType:h.SearchFunctionType.Prefix,label:"Functions",items:X.OV.concat(X.aH)}]}))),Ve(this,"getFieldCompletionItems",(async(e,t)=>({suggestions:[{label:"Fields",items:(await this.fetchFields(e,t)).map((e=>({label:e,insertText:e.match(/@?[_a-zA-Z]+[_.0-9a-zA-Z]*/)?void 0:`\`${e}\``})))}]}))),this.datasource=e,Object.assign(this,t)}getSyntax(){return X.ZP}isStatsQuery(e){var t;const r=this.getSyntax();return!!(null!==(t=z().tokenize(e,r))&&void 0!==t?t:[]).find((e=>"string"!=typeof e&&"stats"===e.content.toString().toLowerCase()&&"query-command"===e.type))}async provideCompletionItems(e,t){const{value:r}=e,n=null==r?void 0:r.data.get("tokens");if(!n||!n.length)return{suggestions:[]};const s=n.filter((e=>{var t,n,s,i;return e.offsets.start<=(null===(t=r.selection)||void 0===t||null===(n=t.start)||void 0===n?void 0:n.offset)&&e.offsets.end>=(null===(s=r.selection)||void 0===s||null===(i=s.start)||void 0===i?void 0:i.offset)}))[0],i=!s.prev,a=Qe(s);if(i||!i&&(null==a?void 0:a.types.includes("command-separator")))return this.getCommandCompletionItems();var o;if(function(e){const t=Qe(e);if(!t)return!1;const r="("===e.content?e:"("===t.content?t:void 0;if(r){const e=Qe(r);if(e)return Be.includes(e.content.toLowerCase())&&e.types.includes("function")}return!1}(s))return await this.getFieldCompletionItems(null!==(o=null==t?void 0:t.logGroupNames)&&void 0!==o?o:[],(null==t?void 0:t.region)||"default");if(function(e,t){const r=Ue(t,["whitespace","function","punctuation","field-name","number"]);if($e(r,"keyword","by")){const e=Ue(t,["whitespace"]);if(e===r||$e(e,"punctuation",","))return!0}return!1}(0,s))return this.handleKeyword(t);if(null!=a&&a.types.includes("comparison-operator"))return this.handleComparison(t);const l=function(e){let t=e;for(;t.prev;)if(t=t.prev,t.types.includes("query-command")&&(!t.prev||$e(Qe(t),"command-separator")))return t;return null}(s);return l?await this.handleCommand(l,s,t):{suggestions:[]}}async handleSortCommand(e,t,r){var n;return e?await this.getFieldCompletionItems(null!==(n=null==r?void 0:r.logGroupNames)&&void 0!==n?n:[],(null==r?void 0:r.region)||"default"):$e(Qe(t),"field-name")?{suggestions:[{searchFunctionType:h.SearchFunctionType.Prefix,label:"Sort Order",items:[{label:"asc"},{label:"desc"}]}]}:{suggestions:[]}}}function Qe(e){let t=e;for(;t.prev;){if(!$e(t.prev,"whitespace"))return t.prev;t=t.prev}return null}const Be=["avg","count","count_distinct","earliest","latest","sortsFirst","sortsLast","max","min","pct","stddev","ispresent","fromMillis","toMillis","isempty","isblank","isValidIp","isValidIpV4","isValidIpV6","isIpInSubnet","isIpv4InSubnet","isIpv6InSubnet"].map((e=>e.toLowerCase()));function $e(e,t,r){return!(null==e||!e.types.includes(t))&&(!r||(null==e?void 0:e.content.toLowerCase())===r)}function Ue(e,t){let r=e.prev;e:for(;r;){for(const e of t)if("string"==typeof e){if(r.types.includes(e)){r=r.prev;continue e}}else if(r.types.includes(e.type)&&r.content.toLowerCase()===e.value){r=r.prev;continue e}break}return r}const Ge=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:7e3;const r=(0,o.memoize)((function(){return(0,o.debounce)(e,t,{leading:!0})}),(function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return JSON.stringify(t)}));return function(){return r(...arguments)(...arguments)}};var ze=r("./public/app/plugins/datasource/cloudwatch/metric-math/language.ts");const He={Parenthesis:"delimiter.parenthesis.cloudwatch-MetricMath",Whitespace:"white.cloudwatch-MetricMath",Keyword:"keyword.cloudwatch-MetricMath",Delimiter:"delimiter.cloudwatch-MetricMath",Operator:"operator.cloudwatch-MetricMath",Identifier:"identifier.cloudwatch-MetricMath",Type:"type.cloudwatch-MetricMath",Function:"predefined.cloudwatch-MetricMath",Number:"number.cloudwatch-MetricMath",String:"string.cloudwatch-MetricMath",Variable:"variable.cloudwatch-MetricMath"};function Xe(e){const t=null==e?void 0:e.getPreviousNonWhiteSpaceToken();if(e&&e.isString())return Re.WithinString;if(e&&t){const r=e.getPreviousOfType(He.Function),n=t.is(He.Delimiter,","),s=r&&"SEARCH"===r.value,i=e.getPreviousUntil(He.Function,[],"SEARCH")||[];if(s){if(1===i.filter((e=>{let{value:t}=e;return"'"===t})).length)return Re.WithinString;const e=t.getPreviousOfType(He.Delimiter,",");if(e){if(e.range.startColumn>r.range.startColumn&&e.range.startLineNumber>=r.range.startLineNumber)return Re.SearchFuncThirdArg}return Re.SearchFuncSecondArg}if(!s&&n)return Re.PredefinedFuncSecondArg}return null!=t&&t.endsWith(")")?Re.AfterFunction:e&&e.isString()?Re.Unknown:Re.PredefinedFunction}function Ye(e){switch(e){case Re.PredefinedFunction:return[Ce.FunctionsWithArguments];case Re.PredefinedFuncSecondArg:return[Ce.FunctionsWithArguments,Ce.KeywordArguments];case Re.AfterFunction:return[Ce.Operators];case Re.SearchFuncSecondArg:return[Ce.Statistic];case Re.SearchFuncThirdArg:return[Ce.Period]}return[]}class Je extends Fe{constructor(e){super(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:(0,x.getTemplateSrv)()),this.getStatementPosition=Xe,this.getSuggestionKinds=Ye,this.tokenTypes=He}async getSuggestions(e,t,r,n,s){let i=[];const a=(null==t?void 0:t.isWhiteSpace())||(null==t?void 0:t.isParenthesis())||null==t||!t.range?e.Range.fromPositions(s):null==t?void 0:t.range,o=function(t){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const n=Object.assign({label:t,insertText:t,kind:e.languages.CompletionItemKind.Field,range:a,sortText:je.Medium},r);return n};function l(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};i=[...i,o(e,t)]}for(const t of r)switch(t){case Ce.FunctionsWithArguments:ze.METRIC_MATH_FNS.map((t=>l(t,{insertText:"SEARCH"===t?`${t}('$0')`:`${t}($0)`,insertTextRules:e.languages.CompletionItemInsertTextRule.InsertAsSnippet,command:Me.w,kind:e.languages.CompletionItemKind.Function})));break;case Ce.KeywordArguments:ze.METRIC_MATH_KEYWORDS.map((t=>l(t,{insertText:t,command:Me.w,kind:e.languages.CompletionItemKind.Keyword,sortText:je.MediumHigh})));break;case Ce.Statistic:ze.METRIC_MATH_STATISTIC_KEYWORD_STRINGS.map((e=>l(e,{insertText:`'${e}', `,command:Me.w})));break;case Ce.Operators:ze.METRIC_MATH_OPERATORS.map((e=>l(e,{insertText:`${e} `,command:Me.w})));break;case Ce.Period:ze.METRIC_MATH_PERIODS.map(((t,r)=>l(t.toString(),{kind:e.languages.CompletionItemKind.Value,sortText:String.fromCharCode(97+r)})))}return this.templateVariables.map((t=>{l(t,{range:a,label:t,insertText:t,kind:e.languages.CompletionItemKind.Variable,sortText:je.Low})})),i}}var Ze=r("./public/app/plugins/datasource/cloudwatch/types.ts"),et=r("./public/app/plugins/datasource/cloudwatch/aws_url.ts");async function tt(e,t){let r;try{r=await(0,x.getDataSourceSrv)().get(e)}catch(e){return void console.error("Could not load linked xray data source, it was probably deleted after it was linked",e)}return{title:r.name,url:"",internal:{query:{query:"${__value.raw}",queryType:"getTrace",region:t},datasourceUid:e,datasourceName:r.name}}}function rt(e,t,r,n){var s,i;const a=e.expression?n(e.expression):"",o=null!==(s=null===(i=e.logGroupNames)||void 0===i?void 0:i.map((e=>n(e,"log groups"))))&&void 0!==s?s:[],l={end:t.to.toISOString(),start:t.from.toISOString(),timeType:"ABSOLUTE",tz:"UTC",editorString:a,isLiveTail:!1,source:o};return{url:(0,et.M)(l,r),title:"View in CloudWatch console",targetBlank:!0}}function nt(e,t,r){const n=new Date;let s,i,a=0,o={};return new ce.y((l=>(function t(u){i=e(u).subscribe({next(e){const t=(0,x.toDataQueryResponse)({data:{results:o}}).data||[];l.next({frames:[...t,...e]}),l.complete()},error(e){if("string"==typeof e)return void l.error(e);const i=function(e){var t;const r=null===(t=e.data)||void 0===t?void 0:t.results;if(!r)return;return Object.keys(r).reduce(((t,n)=>{var s;return null!==(s=r[n].error)&&void 0!==s&&s.startsWith("LimitExceededException")?(t.errorMessage=r[n].error,t.errors.push(e.config.data.queries.find((e=>e.refId===n)))):t.good[n]=r[n],t}),{errors:[],good:{},errorMessage:""})}(e);var u;if(i)if(i.errors.length)if(r(a,n.valueOf()))if(Object.keys(o).length||Object.keys(i.good).length){var c,d,p;const e=(0,x.toDataQueryResponse)({data:{results:Object.assign({},null!==(c=i.good)&&void 0!==c?c:{},null!==(d=o)&&void 0!==d?d:{})}});e.error=Object.assign({},null!==(p=e.error)&&void 0!==p?p:{},{message:`Some queries timed out: ${i.errorMessage}`}),l.next({error:e.error,frames:e.data}),l.complete()}else{var m,h;const t=(0,x.toDataQueryResponse)({data:{results:null!==(m=null===(h=e.data)||void 0===h?void 0:h.results)&&void 0!==m?m:{}}});l.error(t.error)}else o=Object.assign({},o,i.good),s=setTimeout((()=>{a++,t(i.errors)}),(u=a+1,1e3*Math.pow(2,u)+100*Math.random()));else l.error(e);else l.error(e)}})}(t),()=>{clearTimeout(s),i.unsubscribe()})))}var st=r("../../opt/drone/yarncache/rxjs-npm-7.5.5-d0546b1ccb-e034f60805.zip/node_modules/rxjs/dist/esm5/internal/scheduler/async.js");function it(e){if(!e)return;const{subscriber:t,counter:r,period:n,step:s,endPeriod:i}=e;t.next(r);const a=Math.min(n+s,i);this.schedule({subscriber:t,counter:r+1,period:a,step:s,endPeriod:i},a)}var at=r("./public/app/plugins/datasource/cloudwatch/hooks.ts"),ot=r("./public/app/plugins/datasource/cloudwatch/migrations.ts");const lt=e=>{let{label:t,onChange:r,value:n,options:s,allowCustomValue:i=!1,isLoading:a=!1}=e;return(0,S.jsx)(h.InlineField,{label:t,labelWidth:20,htmlFor:"inline-field",children:(0,S.jsx)(h.Select,{menuShouldPortal:!0,"aria-label":t,width:25,allowCustomValue:i,value:n,onChange:e=>{let{value:t}=e;return r(t)},options:s,isLoading:a,inputId:"inline-field"})})},ut=e=>{let{label:t,onBlur:r,placeholder:n,value:s,tooltip:i}=e;const[a,o]=(0,d.useState)(s);return(0,S.jsx)(h.InlineField,{label:t,labelWidth:20,tooltip:i,children:(0,S.jsx)(h.Input,{"aria-label":t,placeholder:n,value:a,onChange:e=>o(e.currentTarget.value),onBlur:()=>r(a),width:100})})},ct=[{value:Ze.wf.Regions,label:"Regions"},{value:Ze.wf.Namespaces,label:"Namespaces"},{value:Ze.wf.Metrics,label:"Metrics"},{value:Ze.wf.DimensionKeys,label:"Dimension Keys"},{value:Ze.wf.DimensionValues,label:"Dimension Values"},{value:Ze.wf.EBSVolumeIDs,label:"EBS Volume IDs"},{value:Ze.wf.EC2InstanceAttributes,label:"EC2 Instance Attributes"},{value:Ze.wf.ResourceArns,label:"Resource ARNs"},{value:Ze.wf.Statistics,label:"Statistics"}],dt=e=>{let{query:t,datasource:r,onChange:n}=e;const s=(0,ot.nC)(t),{region:i,namespace:a,metricName:o,dimensionKey:l}=s,[u,c]=(0,at.eH)(r),d=(0,at.JR)(r),p=(0,at.Bf)(r,i,a),m=(0,at.$K)(r,i,a,o),h=e=>{n(Object.assign({},e,{refId:"CloudWatchVariableQueryEditor-VariableQuery"}))},g=async e=>{let{metricName:t,dimensionKey:n,dimensionFilters:s,namespace:i,region:a}=e;return t&&await r.getMetrics(i,a).then((e=>{e.find((e=>e.value===t))||(t="",s="")})),n&&await r.getDimensionKeys(i,a).then((e=>{e.find((e=>e.value===n))||(n="",s="")})),Object.assign({},e,{metricName:t,dimensionKey:n,dimensionFilters:s})},f=[Ze.wf.Metrics,Ze.wf.DimensionKeys,Ze.wf.DimensionValues,Ze.wf.EBSVolumeIDs,Ze.wf.EC2InstanceAttributes,Ze.wf.ResourceArns].includes(s.queryType),v=[Ze.wf.Metrics,Ze.wf.DimensionKeys,Ze.wf.DimensionValues].includes(s.queryType);return(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(lt,{value:s.queryType,options:ct,onChange:e=>h(Object.assign({},s,{queryType:e})),label:"Query Type"}),f&&(0,S.jsx)(lt,{value:i,options:u,onChange:e=>(async e=>{const t=await g(Object.assign({},s,{region:e}));h(t)})(e),label:"Region",isLoading:c}),v&&(0,S.jsx)(lt,{value:a,options:d,onChange:e=>(async e=>{const t=await g(Object.assign({},s,{namespace:e}));h(t)})(e),label:"Namespace"}),s.queryType===Ze.wf.DimensionValues&&(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(lt,{value:o||null,options:p,onChange:e=>h(Object.assign({},s,{metricName:e})),label:"Metric"}),(0,S.jsx)(lt,{value:l||null,options:m,onChange:e=>h(Object.assign({},s,{dimensionKey:e})),label:"Dimension Key"}),(0,S.jsx)(ut,{value:t.dimensionFilters,tooltip:'A JSON object representing dimensions and the values to filter on. Ex. { "filter_name1": [ "filter_value1" ], "filter_name2": [ "*" ] }',placeholder:'{"key":["value"]}',onBlur:e=>h(Object.assign({},s,{dimensionFilters:e})),label:"Filters"})]}),s.queryType===Ze.wf.EBSVolumeIDs&&(0,S.jsx)(ut,{value:t.instanceID,placeholder:"i-XXXXXXXXXXXXXXXXX",onBlur:e=>h(Object.assign({},s,{instanceID:e})),label:"Instance ID"}),s.queryType===Ze.wf.EC2InstanceAttributes&&(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(ut,{value:s.attributeName,placeholder:"attribute name",onBlur:e=>h(Object.assign({},s,{attributeName:e})),label:"Attribute Name"}),(0,S.jsx)(ut,{value:s.ec2Filters,tooltip:'A JSON object representing dimensions/tags and the values to filter on. Ex. { "filter_name": [ "filter_value" ], "tag:name": [ "*" ] }',placeholder:'{"key":["value"]}',onBlur:e=>h(Object.assign({},s,{ec2Filters:e})),label:"Filters"})]}),s.queryType===Ze.wf.ResourceArns&&(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(ut,{value:s.resourceType,placeholder:"resource type",onBlur:e=>h(Object.assign({},s,{resourceType:e})),label:"Resource Type"}),(0,S.jsx)(ut,{value:s.tags,placeholder:'{"tag":["value"]}',onBlur:e=>h(Object.assign({},s,{tags:e})),label:"Tags"})]})]})};function pt(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}class mt extends a.CustomVariableSupport{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:(0,x.getTemplateSrv)();super(),pt(this,"datasource",void 0),pt(this,"templateSrv",void 0),pt(this,"editor",dt),this.datasource=e,this.templateSrv=t,this.query=this.query.bind(this)}query(e){const t=(0,ot.nC)(e.targets[0]);return(0,ie.D)(this.execute(t)).pipe((0,pe.U)((e=>({data:e}))))}async execute(e){try{switch(e.queryType){case Ze.wf.Regions:return this.handleRegionsQuery();case Ze.wf.Namespaces:return this.handleNamespacesQuery();case Ze.wf.Metrics:return this.handleMetricsQuery(e);case Ze.wf.DimensionKeys:return this.handleDimensionKeysQuery(e);case Ze.wf.DimensionValues:return this.handleDimensionValuesQuery(e);case Ze.wf.EBSVolumeIDs:return this.handleEbsVolumeIdsQuery(e);case Ze.wf.EC2InstanceAttributes:return this.handleEc2InstanceAttributeQuery(e);case Ze.wf.ResourceArns:return this.handleResourceARNsQuery(e);case Ze.wf.Statistics:return this.handleStatisticsQuery()}}catch(t){return console.error(`Could not run CloudWatchMetricFindQuery ${e}`,t),[]}}async handleRegionsQuery(){return(await this.datasource.getRegions()).map((e=>({text:e.label,value:e.value,expandable:!0})))}async handleNamespacesQuery(){return(await this.datasource.getNamespaces()).map((e=>({text:e.label,value:e.value,expandable:!0})))}async handleMetricsQuery(e){let{namespace:t,region:r}=e;return(await this.datasource.getMetrics(t,r)).map((e=>({text:e.label,value:e.value,expandable:!0})))}async handleDimensionKeysQuery(e){let{namespace:t,region:r}=e;return(await this.datasource.getDimensionKeys(t,r)).map((e=>({text:e.label,value:e.value,expandable:!0})))}async handleDimensionValuesQuery(e){let{namespace:t,region:r,dimensionKey:n,metricName:s,dimensionFilters:i}=e;if(!n||!s)return[];var a={};i&&(a=JSON.parse(i));return(await this.datasource.getDimensionValues(r,t,s,n,a)).map((e=>({text:e.label,value:e.value,expandable:!0})))}async handleEbsVolumeIdsQuery(e){let{region:t,instanceID:r}=e;if(!r)return[];return(await this.datasource.getEbsVolumeIds(t,r)).map((e=>({text:e.label,value:e.value,expandable:!0})))}async handleEc2InstanceAttributeQuery(e){let{region:t,attributeName:r,ec2Filters:n}=e;if(!r)return[];var s={};n&&(s=JSON.parse(this.templateSrv.replace(n)));return(await this.datasource.getEc2InstanceAttribute(t,r,s)).map((e=>({text:e.label,value:e.value,expandable:!0})))}async handleResourceARNsQuery(e){let{region:t,resourceType:r,tags:n}=e;if(!r)return[];var s={};n&&(s=JSON.parse(this.templateSrv.replace(n)));return(await this.datasource.getResourceARNs(t,r,s)).map((e=>({text:e.label,value:e.value,expandable:!0})))}async handleStatisticsQuery(){return this.datasource.standardStatistics.map((e=>({text:e,value:e,expandable:!0})))}}function ht(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}const gt="/api/ds/query",ft="__log__grafana_internal__",vt="__logstream__grafana_internal__",yt=(e,t)=>y.h.dispatch((0,g.$l)((0,f.t_)(`CloudWatch request limit reached in ${t} for data source ${e}`,"",void 0,d.createElement(_e,{region:t},null)))),bt=(e,t)=>y.h.dispatch((0,g.$l)((0,f.t_)(e,t)));class xt extends x.DataSourceWithBackend{constructor(e){var t;let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:(0,we.J)(),n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:(0,Se.$t)();super(e),t=this,ht(this,"proxyUrl",void 0),ht(this,"defaultRegion",void 0),ht(this,"datasourceName",void 0),ht(this,"languageProvider",void 0),ht(this,"sqlCompletionItemProvider",void 0),ht(this,"metricMathCompletionItemProvider",void 0),ht(this,"tracingDataSourceUid",void 0),ht(this,"logsTimeout",void 0),ht(this,"type","cloudwatch"),ht(this,"standardStatistics",["Average","Maximum","Minimum","Sum","SampleCount"]),ht(this,"debouncedAlert",Ge(yt,Te.bd.Error)),ht(this,"debouncedCustomAlert",Ge(bt,Te.bd.Error)),ht(this,"logQueries",{}),ht(this,"handleLogQueries",((e,t)=>{const r=e.filter((e=>{var t;return null===(t=e.logGroupNames)||void 0===t?void 0:t.length}));if(e.length>r.length)return(0,se.of)({data:[],error:{message:"Log group is required"}});if((0,o.isEmpty)(r))return(0,se.of)({data:[],state:a.LoadingState.Done});const n=e.map((e=>({queryString:e.expression||"",refId:e.refId,logGroupNames:e.logGroupNames,region:this.replace(this.getActualRegion(e.region),t.scopedVars,!0,"region")}))),s=new Date,i=()=>Date.now()>=s.valueOf()+a.rangeUtil.intervalToMs(this.logsTimeout);return nt((e=>this.makeLogActionRequest("StartQuery",e,{makeReplacements:!0,scopedVars:t.scopedVars,skipCache:!0})),n,i).pipe((0,de.z)((t=>{let{frames:r,error:n}=t;return this.logsQuery(r.map((t=>{var r,n,s;return{queryId:t.fields[0].values.get(0),region:null!==(r=null===(n=t.meta)||void 0===n||null===(s=n.custom)||void 0===s?void 0:s.Region)&&void 0!==r?r:"default",refId:t.refId,statsGroups:e.find((e=>e.refId===t.refId)).statsGroups}})),i).pipe((0,pe.U)((e=>(!e.error&&n&&(e.error=n),e))))})),(0,de.z)((e=>(0,ie.D)((async()=>(await async function(e,t,r,n,s,i){const a=(e,r)=>n(e,t.scopedVars,!0,r);for(const n of e.data){var o;const e=t.targets.find((e=>e.refId===n.refId)),u=s(a(null!==(o=e.region)&&void 0!==o?o:"","region"));for(const t of n.fields)if("@xrayTraceId"===t.name&&i){var l;s(a(null!==(l=e.region)&&void 0!==l?l:"","region"));const r=await tt(i,u);r&&(t.config.links=[r])}else t.config.links=[rt(e,r,u,a)]}}(e,t,this.timeSrv.timeRange(),this.replace.bind(this),this.getActualRegion.bind(this),this.tracingDataSourceUid),e))()))))})),ht(this,"handleMetricQueries",((e,t)=>{var r,n;const s=e.filter(this.filterQuery).map((e=>{var r;return e.region=this.templateSrv.replace(this.getActualRegion(e.region),t.scopedVars),e.namespace=this.replace(e.namespace,t.scopedVars,!0,"namespace"),e.metricName=this.replace(e.metricName,t.scopedVars,!0,"metric name"),e.dimensions=this.convertDimensionFormat(null!==(r=e.dimensions)&&void 0!==r?r:{},t.scopedVars),e.statistic=this.templateSrv.replace(e.statistic,t.scopedVars),e.period=String(this.getPeriod(e,t)),e.id=this.templateSrv.replace(e.id,t.scopedVars),e.expression=this.templateSrv.replace(e.expression,t.scopedVars),e.sqlExpression=this.templateSrv.replace(e.sqlExpression,t.scopedVars,"raw"),Object.assign({intervalMs:t.intervalMs,maxDataPoints:t.maxDataPoints},e,{type:"timeSeriesQuery",datasource:this.getRef()})}));if((0,o.isEmpty)(s))return(0,se.of)({data:[]});const i={from:null==t||null===(r=t.range)||void 0===r?void 0:r.from.valueOf().toString(),to:null==t||null===(n=t.range)||void 0===n?void 0:n.to.valueOf().toString(),queries:s};return this.performTimeSeriesQuery(i,t.range)})),ht(this,"getLogRowContext",(async function(e){let{limit:r=10,direction:n="BACKWARD"}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},s=null,i=null;for(const t of e.dataFrame.fields)if(t.name===vt){if(s=t,null!==i)break}else if(t.name===ft&&(i=t,null!==s))break;const a={limit:r,startFromHead:"BACKWARD"!==n,logGroupName:St(i.values.get(e.rowIndex)),logStreamName:s.values.get(e.rowIndex)};"BACKWARD"===n?a.endTime=e.timeEpochMs:a.startTime=e.timeEpochMs;const o=await(0,ae.n)(t.makeLogActionRequest("GetLogEvents",[a]));return{data:o}})),ht(this,"getTargetsByQueryMode",(e=>{const t=[],r=[];return e.forEach((e=>{var n;"Logs"===(null!==(n=e.queryMode)&&void 0!==n?n:"Metrics")?t.push(e):r.push(e)})),{logQueries:t,metricsQueries:r}})),this.templateSrv=r,this.timeSrv=n,this.templateSrv=r,this.timeSrv=n,this.proxyUrl=e.url,this.defaultRegion=e.jsonData.defaultRegion,this.datasourceName=e.name,this.languageProvider=new We(this),this.tracingDataSourceUid=e.jsonData.tracingDatasourceUid,this.logsTimeout=e.jsonData.logsTimeout||"15m",this.sqlCompletionItemProvider=new qe(this,this.templateSrv),this.metricMathCompletionItemProvider=new Je(this,this.templateSrv),this.variables=new mt(this,this.templateSrv)}query(e){let t=(e=(0,o.cloneDeep)(e)).targets.filter((e=>""!==e.id||!0!==e.hide));const{logQueries:r,metricsQueries:n}=this.getTargetsByQueryMode(t),s=[];return r.length>0&&s.push(this.handleLogQueries(r,e)),n.length>0&&s.push(this.handleMetricQueries(n,e)),(0,o.isEmpty)(s)?(0,se.of)({data:[],state:a.LoadingState.Done}):(0,oe.T)(...s)}filterQuery(e){var t;if("Logs"===e.queryMode)return!(null===(t=e.logGroupNames)||void 0===t||!t.length);const{region:r,metricQueryType:n,metricEditorMode:s,expression:i,metricName:a,namespace:o,sqlExpression:l,statistic:u}=e;if(!r)return!1;if(n===Ze.$5.Search&&s===Ze.MQ.Builder)return!!o&&!!a&&!!u;if(n===Ze.$5.Search&&s===Ze.MQ.Code)return!!i;if(n===Ze.$5.Query)return!!l;throw new Error("invalid metric editor mode")}logsQuery(e,t){this.logQueries={},e.forEach((e=>{var t,r,n;this.logQueries[e.refId]={id:e.queryId,region:e.region,statsQuery:null!==(t=(null!==(r=null===(n=e.statsGroups)||void 0===n?void 0:n.length)&&void 0!==r?r:0)>0)&&void 0!==t&&t}}));const r=function(e){let{startPeriod:t=0,endPeriod:r=5e3,step:n=1e3}=e,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.z;return new ce.y((e=>{const i={subscriber:e,counter:0,period:t,step:n,endPeriod:r};return e.add(s.schedule(it,t,i)),e}))}({startPeriod:100,endPeriod:1e3,step:300}).pipe((0,me.b)((t=>this.makeLogActionRequest("GetQueryResults",e,{skipCache:!0}))),(0,he.r)(),(0,ge.B)()),n=r.pipe((0,fe.R)(((e,t)=>{let{failures:r,prevRecordsMatched:n}=e;r++;for(const e of t){var s,i,a,o;const t=null===(s=e.meta)||void 0===s||null===(i=s.stats)||void 0===i||null===(a=i.find((e=>"Records scanned"===e.displayName)))||void 0===a?void 0:a.value;t>(null!==(o=n[e.refId])&&void 0!==o?o:0)&&(r=0),n[e.refId]=t}return{failures:r,prevRecordsMatched:n}}),{failures:0,prevRecordsMatched:{}}),(0,pe.U)((e=>{let{failures:t}=e;return t})),(0,ge.B)()),s=(0,le.$)(r,n).pipe((0,ve.b)((e=>{let[t]=e;for(const e of t){var r,n;[Ze.KB.Complete,Ze.KB.Cancelled,Ze.KB.Failed].includes(null===(r=e.meta)||void 0===r||null===(n=r.custom)||void 0===n?void 0:n.Status)&&this.logQueries.hasOwnProperty(e.refId)&&delete this.logQueries[e.refId]}})),(0,pe.U)((e=>{let[r,n]=e;if(t())for(const e of r)(0,o.set)(e,"meta.custom.Status",Ze.KB.Cancelled);return{data:r,key:"test-key",state:r.every((e=>{var t,r;return[Ze.KB.Complete,Ze.KB.Cancelled,Ze.KB.Failed].includes(null===(t=e.meta)||void 0===t||null===(r=t.custom)||void 0===r?void 0:r.Status)}))?a.LoadingState.Done:a.LoadingState.Loading,error:t()?{message:`error: query timed out after ${n} attempts`,type:a.DataQueryErrorType.Timeout}:void 0}})),(0,ye.o)((e=>{let{state:t}=e;return t!==a.LoadingState.Error&&t!==a.LoadingState.Done}),!0));return i=s,l=()=>this.stopQueries(),new ce.y((e=>{const t=i.subscribe({next:t=>e.next(t),error:t=>e.next(t),complete:()=>e.complete()});return()=>{t.unsubscribe(),l()}}));var i,l}stopQueries(){Object.keys(this.logQueries).length>0&&this.makeLogActionRequest("StopQuery",Object.values(this.logQueries).map((e=>({queryId:e.id,region:e.region}))),{makeReplacements:!1,skipCache:!0}).pipe((0,be.x)((()=>{this.logQueries={}})))}async describeLogGroups(e){var t,r,n;return null!==(t=null===(r=(await(0,ae.n)(this.makeLogActionRequest("DescribeLogGroups",[e])))[0])||void 0===r||null===(n=r.fields[0])||void 0===n?void 0:n.values.toArray())&&void 0!==t?t:[]}async getLogGroupFields(e){var t;const r=await(0,ae.n)(this.makeLogActionRequest("GetLogGroupFields",[e])),n=r[0].fields[0].values.toArray(),s=r[0].fields[1].values.toArray();return{logGroupFields:null!==(t=n.map(((e,t)=>({name:e,percent:s[t]}))))&&void 0!==t?t:[]}}getVariables(){return this.templateSrv.getVariables().map((e=>`$${e.name}`))}getPeriod(e,t){let r=this.templateSrv.replace(e.period,t.scopedVars);return r&&"auto"!==r.toLowerCase()&&(r=/^\d+$/.test(r)?parseInt(r,10):a.rangeUtil.intervalToSeconds(r),r<1&&(r=1)),r||""}performTimeSeriesQuery(e,t){let{from:r,to:n}=t;return this.awsRequest(gt,e).pipe((0,pe.U)((e=>{const t=(0,x.toDataQueryResponse)({data:e}).data;if(!t||t.length<=0)return{data:[]};const r=(0,o.findLast)(e.results,(e=>!!e.error));return t.forEach((e=>{e.fields.forEach((t=>{var r,n;t.type===a.FieldType.time&&(t.config.interval=1e3*(null===(r=e.meta)||void 0===r||null===(n=r.custom)||void 0===n?void 0:n.period))}))})),{data:t,error:r?{message:r.error}:null}})),(0,xe.K)((t=>{if(!t.data.results&&t.data&&"Metric request error"===t.data.message&&t.data.error)return t.message=t.data.error,(0,ue._)((()=>t));const r=Object.values(t.data.results),n=r.find((e=>e.error));if(n&&(t.message=n.error),r.some((e=>e.error&&/^Throttling:.*/.test(e.error)))){const r=Object.keys(t.data.results);Object.values(e.queries).reduce(((e,t)=>{let{refId:n,region:s}=t;return n&&!r.includes(n)||e.includes(s)?e:[...e,s]}),[]).forEach((e=>{const t=this.getActualRegion(e);t&&this.debouncedAlert(this.datasourceName,t)}))}return(0,ue._)((()=>t))})))}doMetricResourceRequest(e,t){return this.getResource(e,t)}makeLogActionRequest(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{makeReplacements:!0,skipCache:!1};const n=this.timeSrv.timeRange(),s={from:n.from.valueOf().toString(),to:n.to.valueOf().toString(),queries:t.map((t=>Object.assign({refId:t.refId||"A",intervalMs:1,maxDataPoints:1,datasource:this.getRef(),type:"logAction",subtype:e},t)))};r.makeReplacements&&s.queries.forEach((e=>{const t=["queryString","logGroupNames","logGroupName","logGroupNamePrefix"],n=e;for(const s of t)e.hasOwnProperty(s)&&(Array.isArray(n[s])?n[s]=n[s].map((e=>this.replace(e,r.scopedVars,!0,s))):n[s]=this.replace(n[s],r.scopedVars,!0,s));n.region&&(n.region=this.replace(n.region,r.scopedVars,!0,"region"),n.region=this.getActualRegion(n.region))}));let i={};return r.skipCache&&(i={"X-Cache-Skip":!0}),this.awsRequest(gt,s,i).pipe((0,pe.U)((e=>{return t={data:e},(0,x.toDataQueryResponse)(t).data||[];var t})),(0,xe.K)((e=>{var t,r;if(400===e.status)throw e;if(null!==(t=e.data)&&void 0!==t&&t.error)throw e.data.error;if(null!==(r=e.data)&&void 0!==r&&r.message)throw e.data.message;throw e})))}getRegions(){return this.doMetricResourceRequest("regions").then((e=>[{label:"default",value:"default",text:"default"},...e]))}getNamespaces(){return this.doMetricResourceRequest("namespaces")}async getMetrics(e,t){return e?this.doMetricResourceRequest("metrics",{region:this.templateSrv.replace(this.getActualRegion(t)),namespace:this.templateSrv.replace(e)}):[]}async getAllMetrics(e){return(await this.doMetricResourceRequest("all-metrics",{region:this.templateSrv.replace(this.getActualRegion(e))})).map((e=>({metricName:e.value,namespace:e.text})))}async getDimensionKeys(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"";return e?this.doMetricResourceRequest("dimension-keys",{region:this.templateSrv.replace(this.getActualRegion(t)),namespace:this.templateSrv.replace(e),dimensionFilters:JSON.stringify(this.convertDimensionFormat(r,{})),metricName:n}):[]}async getDimensionValues(e,t,r,n,s){if(!t||!r)return[];return await this.doMetricResourceRequest("dimension-values",{region:this.templateSrv.replace(this.getActualRegion(e)),namespace:this.templateSrv.replace(t),metricName:this.templateSrv.replace(r.trim()),dimensionKey:this.templateSrv.replace(n),dimensions:JSON.stringify(this.convertDimensionFormat(s,{}))})}getEbsVolumeIds(e,t){return this.doMetricResourceRequest("ebs-volume-ids",{region:this.templateSrv.replace(this.getActualRegion(e)),instanceId:this.templateSrv.replace(t)})}getEc2InstanceAttribute(e,t,r){return this.doMetricResourceRequest("ec2-instance-attribute",{region:this.templateSrv.replace(this.getActualRegion(e)),attributeName:this.templateSrv.replace(t),filters:JSON.stringify(r)})}getResourceARNs(e,t,r){return this.doMetricResourceRequest("resource-arns",{region:this.templateSrv.replace(this.getActualRegion(e)),resourceType:this.templateSrv.replace(t),tags:JSON.stringify(r)})}annotationQuery(e){const t=e.annotation,r=this.templateSrv.replace(t.statistic),n=t.prefixMatching?"":"300";let s=t.period||n;s=parseInt(s,10);const i={prefixMatching:t.prefixMatching,region:this.templateSrv.replace(this.getActualRegion(t.region)),namespace:this.templateSrv.replace(t.namespace),metricName:this.templateSrv.replace(t.metricName),dimensions:this.convertDimensionFormat(t.dimensions,{}),statistic:r,period:s,actionPrefix:t.actionPrefix||"",alarmNamePrefix:t.alarmNamePrefix||""};return(0,ae.n)(this.awsRequest(gt,{from:e.range.from.valueOf().toString(),to:e.range.to.valueOf().toString(),queries:[Object.assign({refId:"annotationQuery",datasource:this.getRef(),type:"annotationQuery"},i)]}).pipe((0,pe.U)((e=>{const r=(0,x.toDataQueryResponse)({data:e}).data;return(0,a.toLegacyResponseData)(r[0]).rows.map((e=>({annotation:t,time:Date.parse(e[0]),title:e[1],tags:[e[2]],text:e[3]})))}))))}targetContainsTemplate(e){var t;return this.templateSrv.containsTemplate(e.region)||this.templateSrv.containsTemplate(e.namespace)||this.templateSrv.containsTemplate(e.metricName)||this.templateSrv.containsTemplate(e.expression)||(null===(t=e.logGroupNames)||void 0===t?void 0:t.some((e=>this.templateSrv.containsTemplate(e))))||(0,o.find)(e.dimensions,((e,t)=>this.templateSrv.containsTemplate(t)||this.templateSrv.containsTemplate(e)))}awsRequest(e,t){const r={method:"POST",url:e,data:t,headers:arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}};return(0,x.getBackendSrv)().fetch(r).pipe((0,pe.U)((e=>e.data)))}getDefaultRegion(){return this.defaultRegion}getActualRegion(e){return"default"===e||void 0===e||""===e?this.getDefaultRegion():e}showContextToggle(){return!0}convertToCloudWatchTime(e,t){return(0,o.isString)(e)&&(e=a.dateMath.parse(e,t)),Math.round(e.valueOf()/1e3)}convertDimensionFormat(e,t){return Object.entries(e).reduce(((e,r)=>{let[n,s]=r;if(n=this.replace(n,t,!0,"dimension keys"),Array.isArray(s))return Object.assign({},e,{[n]:s});if(!s)return Object.assign({},e,{[n]:null});const i=this.templateSrv.getVariables().find((e=>{let{name:t}=e;return t===this.templateSrv.getVariableName(s)}));if(i){if(i.multi){const r=this.templateSrv.replace(s,t,"pipe").split("|");return Object.assign({},e,{[n]:r})}return Object.assign({},e,{[n]:[this.templateSrv.replace(s,t)]})}return Object.assign({},e,{[n]:[s]})}),{})}replace(e,t,r,n){if(r&&e){const t=this.templateSrv.getVariables().find((t=>{let{name:r}=t;return r===this.templateSrv.getVariableName(e)}));t&&t.multi&&this.debouncedCustomAlert("CloudWatch templating error",`Multi template variables are not supported for ${n||e}`)}return this.templateSrv.replace(e,t)}getQueryDisplayText(e){var t;return"Logs"===e.queryMode?null!==(t=e.expression)&&void 0!==t?t:"":JSON.stringify(e)}interpolateVariablesInQueries(e,t){return e.length?e.map((e=>Object.assign({},e,{region:this.getActualRegion(this.replace(e.region,t)),expression:this.replace(e.expression,t)},!(0,Ze.iZ)(e)&&this.interpolateMetricsQueryVariables(e,t)))):e}interpolateMetricsQueryVariables(e,t){var r;return{alias:this.replace(e.alias,t),metricName:this.replace(e.metricName,t),namespace:this.replace(e.namespace,t),period:this.replace(e.period,t),sqlExpression:this.replace(e.sqlExpression,t),dimensions:Object.entries(null!==(r=e.dimensions)&&void 0!==r?r:{}).reduce(((e,r)=>{let[n,s]=r;return Array.isArray(s)?Object.assign({},e,{[n]:s}):Object.assign({},e,{[this.replace(n,t)]:this.replace(s,t)})}),{})}}}function St(e){const t=e.lastIndexOf(":");return e.slice(t+1)}const wt=new a.DataSourcePlugin(xt).setQueryEditorHelp(ee).setConfigEditor((e=>{const{options:t}=e,r=function(e){const[t,r]=(0,d.useState)();return(0,d.useEffect)((()=>{(0,v.ak)().loadDatasource(e).then((e=>{r(e)}))}),[e]),t}(t.name);!function(e){const t=e=>{y.h.dispatch((0,g.$l)((0,f.ZR)("CloudWatch Authentication",e)))};(0,d.useEffect)((()=>{"arn"===e.authType?t('Since grafana 7.3 authentication type "arn" is deprecated, falling back to default SDK provider'):"credentials"!==e.authType||e.profile||e.database||t('As of grafana 7.3 authentication type "credentials" should be used only for shared file credentials.              If you don\'t have a credentials file, switch to the default SDK provider for extracting credentials              from environment variables or IAM roles')}),[e.authType,e.database,e.profile])}(t.jsonData);const n=function(e){const[t,r]=(0,d.useState)(void 0);return(0,p.Z)((()=>{if(e)try{a.rangeUtil.describeInterval(e),r(void 0)}catch(e){r(e.toString())}else r(void 0)}),350,[e]),t}(e.options.jsonData.logsTimeout);return(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(m.ConnectionConfig,Object.assign({},e,{loadRegions:r&&(()=>r.getRegions().then((e=>e.filter((e=>"default"!==e.value)).map((e=>e.value))))),children:(0,S.jsx)(h.InlineField,{label:"Namespaces of Custom Metrics",labelWidth:28,tooltip:"Namespaces of Custom Metrics.",children:(0,S.jsx)(h.Input,{width:60,placeholder:"Namespace1,Namespace2",value:t.jsonData.customMetricsNamespaces||"",onChange:(0,a.onUpdateDatasourceJsonDataOption)(e,"customMetricsNamespaces")})})})),R||(R=(0,S.jsx)("h3",{className:"page-heading",children:"CloudWatch Logs"})),(0,S.jsx)("div",{className:"gf-form-group",children:(0,S.jsx)(h.InlineField,{label:"Timeout",labelWidth:28,tooltip:'Custom timout for CloudWatch Logs insights queries which have max concurrency limits. Default is 15 minutes. Must be a valid duration string, such as "15m" "30s" "2000ms" etc.',invalid:Boolean(n),children:(0,S.jsx)(h.Input,{width:60,placeholder:"15m",value:t.jsonData.logsTimeout||"",onChange:(0,a.onUpdateDatasourceJsonDataOption)(e,"logsTimeout"),title:'The timeout must be a valid duration string, such as "15m" "30s" "2000ms" etc.'})})}),(0,S.jsx)(A,{onChange:t=>(0,a.updateDatasourcePluginJsonDataOption)(e,"tracingDatasourceUid",t),datasourceUid:t.jsonData.tracingDatasourceUid})]})})).setQueryEditor(ne.S).setMetadataInspector((function(e){let{data:t=[]}=e;const r=(0,d.useMemo)((()=>(0,o.groupBy)(t,"refId")),[t]);return(0,S.jsx)(S.Fragment,{children:(0,S.jsxs)("table",{className:"filter-table form-inline",children:[te||(te=(0,S.jsx)("thead",{children:(0,S.jsxs)("tr",{children:[(0,S.jsx)("th",{children:"RefId"}),(0,S.jsx)("th",{children:"Metric Data Query ID"}),(0,S.jsx)("th",{children:"Metric Data Query Expression"}),(0,S.jsx)("th",{children:"Period"}),(0,S.jsx)("th",{})]})})),Object.entries(r).map(((e,t)=>{var r,n;let[s,i]=e;if(!i.length)return null;const a=i[0],o=null===(r=a.meta)||void 0===r?void 0:r.custom;return o?(0,S.jsx)("tbody",{children:(0,S.jsxs)("tr",{children:[(0,S.jsx)("td",{children:s}),(0,S.jsx)("td",{children:o.id}),(0,S.jsx)("td",{children:null===(n=a.meta)||void 0===n?void 0:n.executedQueryString}),(0,S.jsx)("td",{children:o.period})]})},t):null}))]})})})).setExploreMetricsQueryField(ne.S).setExploreLogsQueryField(re.b).setAnnotationQueryCtrl(l)}}]);
  //# sourceMappingURL=cloudwatchPlugin.b208037f6b1954dc031d.js.map