lokiPlugin.634a81c278b8a1b3e5b2.js 97 KB

12345678910111213141516171819202122232425262728293031323334
  1. "use strict";(self.webpackChunkgrafana=self.webpackChunkgrafana||[]).push([[1598],{90441:(e,t,r)=>{r.d(t,{JX:()=>m,TQ:()=>O,Wz:()=>g,oZ:()=>p,uG:()=>d});var a,n=r(36636),s=r(82897),i=(r(68404),r(90923)),o=r(69783),l=r(91871),c=r(45916);const u=["instant","range"];const d=[{value:l.EM.Range,label:"Range",description:"Run query over a range of time."},{value:l.EM.Instant,label:"Instant",description:'Run query against a single point in time. For this query, the "To" time is used.'}];i.config.featureToggles.lokiLive&&d.push({value:l.EM.Stream,label:"Stream",description:"Run a query and keep sending results on an interval"});const O={value:1,label:"1/1"},p=[O].concat((0,s.map)([2,3,4,5,10],(e=>({value:e,label:"1/"+e}))));function m(e){var t,r;const{lineLimitValue:s,resolution:i,onRunQuery:O,runOnBlur:m,onChange:h}=e,f=null!==(t=e.query)&&void 0!==t?t:{};let y=null!==(r=f.queryType)&&void 0!==r?r:f.instant?l.EM.Instant:l.EM.Range;function v(e){const t=function(e,t){if(null==e)return{};var r,a,n={},s=Object.keys(e);for(a=0;a<s.length;a++)r=s[a],t.indexOf(r)>=0||(n[r]=e[r]);return n}(f,u);h(Object.assign({},t,{queryType:e}))}return(0,c.jsxs)("div",{"aria-label":"Loki extra field",className:"gf-form-inline",children:[(0,c.jsxs)("div",{"data-testid":"queryTypeField",className:(0,n.cx)("gf-form explore-input-margin",n.css`
  2. flex-wrap: nowrap;
  3. `),"aria-label":"Query type field",children:[a||(a=(0,c.jsx)(o.InlineFormLabel,{width:"auto",children:"Query type"})),(0,c.jsx)(o.RadioButtonGroup,{options:d,value:y,onChange:e=>{v(e),m&&O()}})]}),(0,c.jsxs)("div",{"data-testid":"lineLimitField",className:(0,n.cx)("gf-form",n.css`
  4. flex-wrap: nowrap;
  5. `),"aria-label":"Line limit field",children:[(0,c.jsx)(o.InlineField,{label:"Line limit",tooltip:"Upper limit for number of log lines returned by query.",children:(0,c.jsx)(o.Input,{className:"width-4",placeholder:"auto",type:"number",min:0,onChange:function(e){f.maxLines!==g(e.currentTarget.value)&&function(e){const t=Object.assign({},f,{maxLines:g(e)});h(t)}(e.currentTarget.value)},onKeyDown:function(e){"Enter"===e.key&&O()},value:s,onBlur:()=>{m&&O()}})}),(0,c.jsx)(o.InlineField,{label:"Resolution",tooltip:"Resolution 1/1 sets step parameter of Loki metrics range queries such that each pixel corresponds to one data point. For better performance, lower resolutions can be picked. 1/2 only retrieves a data point for every other pixel, and 1/10 retrieves one data point per 10 pixels.",children:(0,c.jsx)(o.Select,{isSearchable:!1,onChange:function(e){const t=Object.assign({},f,{resolution:e.value});h(t)},options:p,value:i,"aria-label":"Select resolution"})})]})]})}function g(e){return 0===e.length?NaN:e.length>0&&(isNaN(+e)||+e<0)?0:+e}},42084:(e,t,r)=>{r.r(t),r.d(t,{plugin:()=>Oa});var a,n,s,i=r(43215);class o{constructor(e){this.annotation=e.ctrl.annotation,this.annotation.target=this.annotation.target||{},this.onQueryChange=this.onQueryChange.bind(this)}onQueryChange(e){this.annotation.expr=e.expr,this.annotation.maxLines=e.maxLines,this.annotation.instant=e.instant}}o.$inject=["$scope"],s="partials/annotations.editor.html",(n="templateUrl")in(a=o)?Object.defineProperty(a,n,{value:s,enumerable:!0,configurable:!0,writable:!0}):a[n]=s;var l,c,u,d,O,p,m,g,h,f=r(82897),y=r(68404),v=r(90923),b=r(45916);function x(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}const Q=['{job="default/prometheus"}'],P=["job","app","k8s_app"],_=[{title:"Log pipeline",expression:'{job="mysql"} |= "metrics" | logfmt | duration > 10s',label:'This query targets the MySQL job, filters out logs that don’t contain the word "metrics" and parses each log line to extract more labels and filters with them.'},{title:"Count over time",expression:'count_over_time({job="mysql"}[5m])',label:"This query counts all the log lines within the last five minutes for the MySQL job."},{title:"Rate",expression:'rate(({job="mysql"} |= "error" != "timeout")[10s])',label:"This query gets the per-second rate of all non-timeout errors within the last ten seconds for the MySQL job."},{title:"Aggregate, count, and group",expression:'sum(count_over_time({job="mysql"}[5m])) by (level)',label:"Get the count of logs during the last five minutes, grouping by level."}];class R extends y.PureComponent{constructor(){super(...arguments),x(this,"state",{userExamples:[]}),x(this,"checkUserLabels",(async()=>{var e;const t=null===(e=this.props.datasource)||void 0===e?void 0:e.languageProvider;if(t.started){const e=t.getLabelKeys()||[],r=P.find((t=>e.includes(t)));if(r){const e=await t.getLabelValues(r),a=(0,f.shuffle)(e).slice(0,5).map((e=>`{${r}="${e}"}`));this.setState({userExamples:a})}}else this.scheduleUserLabelChecking()}))}componentDidMount(){this.scheduleUserLabelChecking(),(0,v.reportInteraction)("grafana_loki_cheatsheet_opened",{})}componentWillUnmount(){clearTimeout(this.userLabelTimer)}scheduleUserLabelChecking(){this.userLabelTimer=setTimeout(this.checkUserLabels,1e3)}renderExpression(e){const{onClickExample:t}=this.props;return(0,b.jsx)("div",{className:"cheat-sheet-item__example",onClick:r=>(t({refId:"A",expr:e}),void(0,v.reportInteraction)("grafana_loki_cheatsheet_example_clicked",{})),children:(0,b.jsx)("code",{children:e})},e)}render(){const{userExamples:e}=this.state,t=e.length>0;return(0,b.jsxs)("div",{children:[l||(l=(0,b.jsx)("h2",{children:"Loki Cheat Sheet"})),(0,b.jsxs)("div",{className:"cheat-sheet-item",children:[c||(c=(0,b.jsx)("div",{className:"cheat-sheet-item__title",children:"See your logs"})),u||(u=(0,b.jsx)("div",{className:"cheat-sheet-item__label",children:"Start by selecting a log stream from the Log browser, or alternatively you can write a stream selector into the query field."})),t?(0,b.jsxs)("div",{children:[d||(d=(0,b.jsx)("div",{className:"cheat-sheet-item__label",children:"Here are some example streams from your logs:"})),e.map((e=>this.renderExpression(e)))]}):(0,b.jsxs)("div",{children:[O||(O=(0,b.jsx)("div",{className:"cheat-sheet-item__label",children:"Here is an example of a log stream:"})),this.renderExpression(Q[0])]})]}),(0,b.jsxs)("div",{className:"cheat-sheet-item",children:[p||(p=(0,b.jsx)("div",{className:"cheat-sheet-item__title",children:"Combine stream selectors"})),this.renderExpression('{app="cassandra",namespace="prod"}'),m||(m=(0,b.jsx)("div",{className:"cheat-sheet-item__label",children:"Returns all log lines from streams that have both labels."}))]}),(0,b.jsxs)("div",{className:"cheat-sheet-item",children:[g||(g=(0,b.jsx)("div",{className:"cheat-sheet-item__title",children:"Filtering for search terms."})),this.renderExpression('{app="cassandra"} |~ "(duration|latency)s*(=|is|of)s*[d.]+"'),this.renderExpression('{app="cassandra"} |= "exact match"'),this.renderExpression('{app="cassandra"} != "do not match"'),h||(h=(0,b.jsxs)("div",{className:"cheat-sheet-item__label",children:[(0,b.jsx)("a",{href:"https://grafana.com/docs/loki/latest/logql/#log-pipeline",target:"logql",children:"LogQL"})," ","supports exact and regular expression filters."]}))]}),_.map((e=>(0,b.jsxs)("div",{className:"cheat-sheet-item",children:[(0,b.jsx)("div",{className:"cheat-sheet-item__title",children:e.title}),this.renderExpression(e.expression),(0,b.jsx)("div",{className:"cheat-sheet-item__label",children:e.label})]},e.expression)))]})}}var L=r(90747),w=r(69783),q=r(55268),j=r(50966),$=r(82631),T=r(7524),F=r(37393),S=r(19093),k=r(17245);let E,C,X;!function(e){e.Aggregations="Aggregations",e.RangeFunctions="Range functions",e.Functions="Functions",e.Formats="Formats",e.LineFilters="Line filters",e.LabelFilters="Label filters",e.BinaryOps="Binary operations"}(E||(E={})),function(e){e.Json="json",e.Logfmt="logfmt",e.Regexp="regexp",e.Pattern="pattern",e.Unpack="unpack",e.LineFormat="line_format",e.LabelFormat="label_format",e.Rate="rate",e.CountOverTime="count_over_time",e.SumOverTime="sum_over_time",e.AvgOverTime="avg_over_time",e.MaxOverTime="max_over_time",e.MinOverTime="min_over_time",e.FirstOverTime="first_over_time",e.LastOverTime="last_over_time",e.StdvarOverTime="stdvar_over_time",e.StddevOverTime="stddev_over_time",e.QuantileOverTime="quantile_over_time",e.BytesRate="bytes_rate",e.BytesOverTime="bytes_over_time",e.AbsentOverTime="absent_over_time",e.Sum="sum",e.Avg="avg",e.Min="min",e.Max="max",e.Stddev="stddev",e.Stdvar="stdvar",e.Count="count",e.TopK="topk",e.BottomK="bottomk",e.LineContains="__line_contains",e.LineContainsNot="__line_contains_not",e.LineMatchesRegex="__line_matches_regex",e.LineMatchesRegexNot="__line_matches_regex_not",e.LabelFilter="__label_filter",e.LabelFilterNoErrors="__label_filter_no_errors",e.Unwrap="unwrap",e.Addition="__addition",e.Subtraction="__subtraction",e.MultiplyBy="__multiply_by",e.DivideBy="__divide_by",e.Modulo="__modulo",e.Exponent="__exponent",e.NestedQuery="__nested_query",e.EqualTo="__equal_to",e.NotEqualTo="__not_equal_to",e.GreaterThan="__greater_than",e.LessThan="__less_than",e.GreaterOrEqual="__greater_or_equal",e.LessOrEqual="__less_or_equal"}(C||(C={})),function(e){e[e.LineFilters=1]="LineFilters",e[e.LineFormats=2]="LineFormats",e[e.LabelFilters=3]="LabelFilters",e[e.Unwrap=4]="Unwrap",e[e.NoErrors=5]="NoErrors",e[e.RangeVectorFunction=5]="RangeVectorFunction",e[e.Last=6]="Last"}(X||(X={}));const U=[{id:C.Addition,name:"Add scalar",sign:"+"},{id:C.Subtraction,name:"Subtract scalar",sign:"-"},{id:C.MultiplyBy,name:"Multiply by scalar",sign:"*"},{id:C.DivideBy,name:"Divide by scalar",sign:"/"},{id:C.Modulo,name:"Modulo by scalar",sign:"%"},{id:C.Exponent,name:"Exponent",sign:"^"},{id:C.EqualTo,name:"Equal to",sign:"==",comparison:!0},{id:C.NotEqualTo,name:"Not equal to",sign:"!=",comparison:!0},{id:C.GreaterThan,name:"Greater than",sign:">",comparison:!0},{id:C.LessThan,name:"Less than",sign:"<",comparison:!0},{id:C.GreaterOrEqual,name:"Greater or equal to",sign:">=",comparison:!0},{id:C.LessOrEqual,name:"Less or equal to",sign:"<=",comparison:!0}],I=U.map((e=>{const t=[{name:"Value",type:"number"}],r=[2];return e.comparison&&(t.unshift({name:"Bool",type:"boolean",description:"If checked comparison will return 0 or 1 for the value rather than filtering."}),r.unshift(!1)),{id:e.id,name:e.name,params:t,defaultParams:r,alternativesKey:"binary scalar operations",category:E.BinaryOps,renderer:(a=e.sign,function(e,t,r){let n=e.params[0],s="";return 2===e.params.length&&(n=e.params[1],s=e.params[0]?" bool":""),`${r} ${a}${s} ${n}`}),addOperationHandler:S.PP};var a}));function N(){const e=[C.Sum,C.Min,C.Max,C.Avg,C.Stddev,C.Stdvar,C.Count].flatMap((e=>(0,S.IT)(e,{addOperationHandler:W,orderRank:X.Last}))),t=[C.TopK,C.BottomK].flatMap((e=>(0,S.Z3)(e,{params:[{name:"K-value",type:"number"}],defaultParams:[5]},{addOperationHandler:W,orderRank:X.Last})));return[V(C.Rate),V(C.CountOverTime),V(C.SumOverTime),V(C.BytesRate),V(C.BytesOverTime),V(C.AbsentOverTime),V(C.AvgOverTime),V(C.MaxOverTime),V(C.MinOverTime),V(C.FirstOverTime),V(C.LastOverTime),V(C.StdvarOverTime),V(C.StddevOverTime),V(C.QuantileOverTime),...e,...t,{id:C.Json,name:"Json",params:[],defaultParams:[],alternativesKey:"format",category:E.Formats,orderRank:X.LineFormats,renderer:G,addOperationHandler:W},{id:C.Logfmt,name:"Logfmt",params:[],defaultParams:[],alternativesKey:"format",category:E.Formats,orderRank:X.LineFormats,renderer:G,addOperationHandler:W,explainHandler:()=>"This will extract all keys and values from a [logfmt](https://grafana.com/docs/loki/latest/logql/log_queries/#logfmt) formatted log line as labels. The extracted labels can be used in label filter expressions and used as values for a range aggregation via the unwrap operation."},{id:C.Regexp,name:"Regexp",params:[{name:"String",type:"string",hideName:!0,placeholder:"<re>",description:"The regexp expression that matches the structure of a log line.",minWidth:20}],defaultParams:[""],alternativesKey:"format",category:E.Formats,orderRank:X.LineFormats,renderer:(e,t,r)=>`${r} | regexp \`${e.params[0]}\``,addOperationHandler:W,explainHandler:()=>'The [regexp parser](https://grafana.com/docs/loki/latest/logql/log_queries/#regular-expression) takes a single parameter | regexp "<re>" which is the regular expression using the Golang RE2 syntax. The regular expression must contain a least one named sub-match (e.g (?P<name>re)), each sub-match will extract a different label. The expression matches the structure of a log line. The extracted labels can be used in label filter expressions and used as values for a range aggregation via the unwrap operation.'},{id:C.Pattern,name:"Pattern",params:[{name:"String",type:"string",hideName:!0,placeholder:"<pattern-expression>",description:"The expression that matches the structure of a log line.",minWidth:20}],defaultParams:[""],alternativesKey:"format",category:E.Formats,orderRank:X.LineFormats,renderer:(e,t,r)=>`${r} | pattern \`${e.params[0]}\``,addOperationHandler:W,explainHandler:()=>"The [pattern parser](https://grafana.com/docs/loki/latest/logql/log_queries/#pattern) allows the explicit extraction of fields from log lines by defining a pattern expression (| pattern `<pattern-expression>`). The expression matches the structure of a log line. The extracted labels can be used in label filter expressions and used as values for a range aggregation via the unwrap operation."},{id:C.Unpack,name:"Unpack",params:[],defaultParams:[],alternativesKey:"format",category:E.Formats,orderRank:X.LineFormats,renderer:G,addOperationHandler:W,explainHandler:()=>"This will extract all keys and values from a JSON log line, [unpacking](https://grafana.com/docs/loki/latest/logql/log_queries/#unpack) all embedded labels in the pack stage. The extracted labels can be used in label filter expressions and used as values for a range aggregation via the unwrap operation."},{id:C.LineFormat,name:"Line format",params:[{name:"String",type:"string",hideName:!0,placeholder:"{{.status_code}}",description:"A line template that can refer to stream labels and extracted labels.",minWidth:20}],defaultParams:[""],alternativesKey:"format",category:E.Formats,orderRank:X.LineFormats,renderer:(e,t,r)=>`${r} | line_format \`${e.params[0]}\``,addOperationHandler:W,explainHandler:()=>"This will replace log line using a specified template. The template can refer to stream labels and extracted labels.\n\n Example: `{{.status_code}} - {{.message}}`\n\n [Read the docs](https://grafana.com/docs/loki/latest/logql/log_queries/#line-format-expression) for more.\n "},{id:C.LabelFormat,name:"Label format",params:[{name:"Label",type:"string"},{name:"Rename",type:"string"}],defaultParams:["",""],alternativesKey:"format",category:E.Formats,orderRank:X.LineFormats,renderer:(e,t,r)=>`${r} | label_format ${e.params[1]}=\`${e.params[0]}\``,addOperationHandler:W,explainHandler:()=>'This will change name of label to desired new label. In the example below, label "error_level" will be renamed to "level".\n\n Example: error_level=`level`\n\n [Read the docs](https://grafana.com/docs/loki/latest/logql/log_queries/#labels-format-expression) for more.\n '},{id:C.LineContains,name:"Line contains",params:[{name:"String",type:"string",hideName:!0,placeholder:"Text to find",description:"Find log lines that contains this text",minWidth:20,runQueryOnEnter:!0}],defaultParams:[""],alternativesKey:"line filter",category:E.LineFilters,orderRank:X.LineFilters,renderer:Y("|="),addOperationHandler:W,explainHandler:e=>`Return log lines that contain string \`${e.params[0]}\`.`},{id:C.LineContainsNot,name:"Line does not contain",params:[{name:"String",type:"string",hideName:!0,placeholder:"Text to exclude",description:"Find log lines that does not contain this text",minWidth:26,runQueryOnEnter:!0}],defaultParams:[""],alternativesKey:"line filter",category:E.LineFilters,orderRank:X.LineFilters,renderer:Y("!="),addOperationHandler:W,explainHandler:e=>`Return log lines that does not contain string \`${e.params[0]}\`.`},{id:C.LineMatchesRegex,name:"Line contains regex match",params:[{name:"Regex",type:"string",hideName:!0,placeholder:"Pattern to match",description:"Find log lines that match this regex pattern",minWidth:30,runQueryOnEnter:!0}],defaultParams:[""],alternativesKey:"line filter",category:E.LineFilters,orderRank:X.LineFilters,renderer:Y("|~"),addOperationHandler:W,explainHandler:e=>`Return log lines that match regex \`${e.params[0]}\`.`},{id:C.LineMatchesRegexNot,name:"Line does not match regex",params:[{name:"Regex",type:"string",hideName:!0,placeholder:"Pattern to exclude",description:"Find log lines that does not match this regex pattern",minWidth:30,runQueryOnEnter:!0}],defaultParams:[""],alternativesKey:"line filter",category:E.LineFilters,orderRank:X.LineFilters,renderer:Y("!~"),addOperationHandler:W,explainHandler:e=>`Return log lines that does not match regex \`${e.params[0]}\`.`},{id:C.LabelFilter,name:"Label filter expression",params:[{name:"Label",type:"string"},{name:"Operator",type:"string",options:["=","!="," =~","!~",">","<",">=","<="]},{name:"Value",type:"string"}],defaultParams:["","=",""],alternativesKey:"label filter",category:E.LabelFilters,orderRank:X.LabelFilters,renderer:A,addOperationHandler:W,explainHandler:()=>"Label expression filter allows filtering using original and extracted labels."},{id:C.LabelFilterNoErrors,name:"No pipeline errors",params:[],defaultParams:[],alternativesKey:"label filter",category:E.LabelFilters,orderRank:X.NoErrors,renderer:(e,t,r)=>`${r} | __error__=\`\``,addOperationHandler:W,explainHandler:()=>"Filter out all formatting and parsing errors."},{id:C.Unwrap,name:"Unwrap",params:[{name:"Identifier",type:"string",hideName:!0,minWidth:16,placeholder:"Label key"}],defaultParams:[""],alternativesKey:"format",category:E.Formats,orderRank:X.Unwrap,renderer:(e,t,r)=>`${r} | unwrap ${e.params[0]}`,addOperationHandler:W,explainHandler:e=>`Use the extracted label \`${String(e.params[0]).length>0?e.params[0]:"<label>"}\` as sample values instead of log lines for the subsequent range aggregation.`},...I,{id:C.NestedQuery,name:"Binary operation with query",params:[],defaultParams:[],category:E.BinaryOps,renderer:(e,t,r)=>r,addOperationHandler:z}]}function V(e){const t=[{name:"Range",type:"string",options:["$__interval","$__range","1m","5m","10m","1h","24h"]}],r=["$__interval"];let a=D;return e===C.QuantileOverTime&&(r.push("0.95"),t.push({name:"Quantile",type:"number"}),a=M),{id:e,name:(0,S.t7)(e),params:t,defaultParams:r,alternativesKey:"range function",category:E.RangeFunctions,orderRank:X.RangeVectorFunction,renderer:a,addOperationHandler:W,explainHandler:(e,t)=>{var r,a;let n=null!==(r=null===(a=k.r8.find((t=>t.insertText===e.id)))||void 0===a?void 0:a.documentation)&&void 0!==r?r:"";return"$__interval"===e.params[0]?`${n} \`$__interval\` is variable that will be replaced with a calculated interval based on **Max data points**, **Min interval** and query time range. You find these options you find under **Query options** at the right of the data source select dropdown.`:`${n} The [range vector](https://grafana.com/docs/loki/latest/logql/metric_queries/#range-vector-aggregation) is set to \`${e.params[0]}\`.`}}}function D(e,t,r){var a,n;let s=null!==(a=(null!==(n=e.params)&&void 0!==n?n:[])[0])&&void 0!==a?a:"$__interval";return`${t.id}(${r} [${s}])`}function M(e,t,r){var a,n;const s=null!==(a=e.params)&&void 0!==a?a:[],i=null!==(n=s[0])&&void 0!==n?n:"$__interval",o=s[1];return`${t.id}(${o}, ${r} [${i}])`}function Y(e){return function(t,r,a){return`${a} ${e} \`${t.params[0]}\``}}function A(e,t,r){return""===e.params[0]?r:"<"===e.params[1]||">"===e.params[1]?`${r} | ${e.params[0]} ${e.params[1]} ${e.params[2]}`:`${r} | ${e.params[0]}${e.params[1]}\`${e.params[2]}\``}function G(e,t,r){return`${r} | ${e.id}`}function B(e,t,r){const a=e.findIndex((e=>{const a=t.getOperationDef(e.id);return!!a&&r(a)}));return-1===a?e.length:a}function W(e,t,r){const a={id:e.id,params:e.defaultParams},n=[...t.operations],s=n.find((e=>{const t=r.getOperationDef(e.id);return!!t&&function(e){return e.category===E.RangeFunctions}(t)}));switch(e.category){case E.Aggregations:case E.Functions:if(!s){const e=B(n,r,(e=>e.category===E.Functions));n.splice(e,0,{id:C.Rate,params:["$__interval"]})}n.push(a);break;case E.RangeFunctions:if(s){const e=n.indexOf(s);n[e]=a;break}default:const t=B(n,r,(t=>{var r,a;return(null!==(r=e.orderRank)&&void 0!==r?r:100)<(null!==(a=t.orderRank)&&void 0!==a?a:100)}));n.splice(t,0,a)}return Object.assign({},t,{operations:n})}function z(e,t){var r;return Object.assign({},t,{binaryQueries:[...null!==(r=t.binaryQueries)&&void 0!==r?r:[],{operator:"/",query:t}]})}class K extends F.x{constructor(){super(N),this.setOperationCategories([E.Aggregations,E.RangeFunctions,E.Formats,E.BinaryOps,E.LabelFilters,E.LineFilters])}renderLabels(e){return 0===e.length?"{}":super.renderLabels(e)}getQueryPatterns(){return[{name:"Log query with parsing",operations:[{id:C.Logfmt,params:[]},{id:C.LabelFilterNoErrors,params:[]}]},{name:"Log query with filtering and parsing",operations:[{id:C.LineContains,params:[""]},{id:C.Logfmt,params:[]},{id:C.LabelFilterNoErrors,params:[]}]},{name:"Log query with parsing and label filter",operations:[{id:C.LineContains,params:[""]},{id:C.Logfmt,params:[]},{id:C.LabelFilterNoErrors,params:[]},{id:C.LabelFilter,params:["label","=","value"]}]},{name:"Log query with parsing of nested json",operations:[{id:C.LineContains,params:[""]},{id:C.Json,params:[]},{id:C.LabelFilterNoErrors,params:[]},{id:C.LineFormat,params:["{{.message}}"]},{id:C.Json,params:[]},{id:C.LabelFilterNoErrors,params:[]}]},{name:"Log query with reformatted log line",operations:[{id:C.LineContains,params:[""]},{id:C.Logfmt,params:[]},{id:C.LabelFilterNoErrors,params:[]},{id:C.LineFormat,params:["{{.message}}"]}]},{name:"Log query with mapped log level",operations:[{id:C.LineContains,params:[""]},{id:C.Logfmt,params:[]},{id:C.LabelFilterNoErrors,params:[]},{id:C.LabelFormat,params:["lvl","level"]}]},{name:"Metrics query on value inside log line",operations:[{id:C.LineContains,params:[""]},{id:C.Logfmt,params:[]},{id:C.LabelFilterNoErrors,params:[]},{id:C.Unwrap,params:[""]},{id:C.LabelFilterNoErrors,params:[]},{id:C.SumOverTime,params:["$__interval"]},{id:C.Sum,params:[]}]},{name:"Metrics query for total requests per label of streams",operations:[{id:C.LineContains,params:[""]},{id:C.CountOverTime,params:["$__interval"]},{id:C.Sum,params:[]}]},{name:"Metrics query for total requests per parsed label or label of streams",operations:[{id:C.LineContains,params:[""]},{id:C.Logfmt,params:[]},{id:C.LabelFilterNoErrors,params:[]},{id:C.CountOverTime,params:["$__interval"]},{id:C.Sum,params:[]}]},{name:"Metrics query for bytes used by log stream",operations:[{id:C.LineContains,params:[""]},{id:C.BytesOverTime,params:["$__interval"]}]},{name:"Metrics query for count of log lines per stream",operations:[{id:C.LineContains,params:[""]},{id:C.CountOverTime,params:["$__interval"]}]},{name:"Metrics query for top n results by label or parsed label",operations:[{id:C.Logfmt,params:[]},{id:C.LabelFilterNoErrors,params:[]},{id:C.CountOverTime,params:["$__interval"]},{id:C.Sum,params:[]},{id:C.TopK,params:[10]}]},{name:"Metrics query for extracted quantile",operations:[{id:C.Logfmt,params:[]},{id:C.LabelFilterNoErrors,params:[]},{id:C.Unwrap,params:["latency"]},{id:C.LabelFilterNoErrors,params:[]},{id:C.QuantileOverTime,params:[.5,"$__interval"]},{id:C.Sum,params:[]}]}]}}const Z=new K;var H=r(85409);const J={json:1,logfmt:2,unpack:3,pattern:4,regexp:5,ip:7,label_format:8,line_format:9,label_replace:10,offset:11,bool:12,on:13,ignoring:14,group_left:15,group_right:16,unwrap:6},ee={by:17,without:18,and:19,or:20,unless:21,sum:22,avg:23,count:24,max:25,min:26,stddev:27,stdvar:28,bottomk:29,topk:30},te={__proto__:null,count_over_time:255,rate:257,bytes_over_time:259,bytes_rate:261,avg_over_time:263,sum_over_time:265,min_over_time:267,max_over_time:269,stddev_over_time:271,stdvar_over_time:273,quantile_over_time:275,first_over_time:277,last_over_time:279,absent_over_time:281,bytes:287,duration:289,duration_seconds:291},re=H.WQ.deserialize({version:13,states:"ASOYQPOOO#VQPO'#DPO$fQPO'#DOOYQPO'#DOOOQO'#D{'#D{O$sQPO'#DzOOQO'#Eg'#EgO$xQPO'#EfQ%TQPOOOOQO'#Eu'#EuO&UQPO'#EuO&ZQPO'#EvOOQO'#Dy'#DyOOQO'#C}'#C}OOQO'#D|'#D|OOQO'#D}'#D}OOQO'#EO'#EOOOQO'#EP'#EPOOQO'#EQ'#EQOOQO'#ER'#EROOQO'#ES'#ESOOQO'#ET'#ETOOQO'#EU'#EUOOQO'#EV'#EVOOQO'#EW'#EWOOQO'#EX'#EXOOQO'#EY'#EYOOQO'#EZ'#EZO&`QPO'#DROOQO'#DQ'#DQO&nQPO,59kOOQO'#D^'#D^O&vQPO'#D]O'OQPO'#D[OOQO'#DZ'#DZO(iQPO'#DZOOQO'#DY'#DYO*bQPO,59jO+pQPO,59jO+wQPO,5:eO,OQPO,5:fO,ZQPO'#EdO.YQPO,5;QO.aQPO,5;QO.fQPO,5;SO.fQPO,5;SO.fQPO,5;SO.fQPO,5;SO.fQPO,5;SO.fQPO,5;SOOQO,5;a,5;a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Selector Matchers Matcher Identifier Eq String Neq Re Nre PipelineExpr PipelineStage LineFilters LineFilter Filter PipeExact PipeMatch FilterOp Pipe LabelParser JsonExpressionParser JsonExpressionList JsonExpression LabelFilter IpLabelFilter UnitFilter DurationFilter Gtr Duration Gte Lss Lte Eql BytesFilter Bytes NumberFilter Number LineFormatExpr LabelFormatExpr LabelsFormat LabelFormatMatcher MetricExpr RangeAggregationExpr RangeOp CountOverTime Rate BytesOverTime BytesRate AvgOverTime SumOverTime MinOverTime MaxOverTime StddevOverTime StdvarOverTime QuantileOverTime FirstOverTime LastOverTime AbsentOverTime LogRangeExpr Range OffsetExpr UnwrapExpr ConvOp BytesConv DurationConv DurationSecondsConv Grouping Labels VectorAggregationExpr VectorOp BinOpExpr BinOpModifier OnOrIgnoringModifier GroupingLabels GroupingLabelList GroupingLabel LabelName Add Sub Mul Div Mod Pow LiteralExpr LabelReplaceExpr",maxTerm:145,skippedNodes:[0,31],repeatNodeCount:0,tokenData:"3{~RwX^#lpq#lqr$ars$tst%huv%swx%xxy&gyz&lz{&q{|&v|}&{}!O'Q!O!P'V!P!Q(V!Q!R([!R![)r![!]0r!^!_1W!_!`1e!`!a1z!c!}2X!}#O2o#P#Q2t#Q#R2y#R#S2X#S#T3O#T#o2X#o#p3[#p#q3a#q#r3v#y#z#l$f$g#l#BY#BZ#l$IS$I_#l$I|$JO#l$JT$JU#l$KV$KW#l&FU&FV#l~#qY#m~X^#lpq#l#y#z#l$f$g#l#BY#BZ#l$IS$I_#l$I|$JO#l$JT$JU#l$KV$KW#l&FU&FV#l~$dQ!_!`$j#r#s$o~$oOy~~$tO{~~$yUx~OY$tZr$trs%]s#O$t#O#P%b#P~$t~%bOx~~%ePO~$t~%mQo~OY%hZ~%h~%xO#g~~%}Ux~OY%xZw%xwx%]x#O%x#O#P&a#P~%x~&dPO~%x~&lO#q~~&qO#r~~&vO#e~~&{O#c~~'QO#o~~'VO#d~~'YP!Q![']~'bR!h~!Q![']!g!h'k#X#Y'k~'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specialized:[{term:38,get:(e,t)=>((e,t)=>J[e.toLowerCase()]||-1)(e)<<1},{term:38,get:(e,t)=>((e,t)=>ee[e.toLowerCase()]||-1)(e)<<1|1},{term:38,get:e=>te[e]||-1}],tokenPrec:0});var ae=r(25890);function ne(e){const t=(0,ae.bU)(e),r=re.parse(t).topNode,a={query:{labels:[],operations:[]},errors:[]};try{se(t,r,a)}catch(e){console.error(e),a.errors.push({text:e.message})}return function(e){if(0===e.labels.length&&0===e.operations.length)return!0;return!1}(a.query)&&(a.errors=[]),a}function se(e,t,r){const a=r.query;switch(t.name){case"Matcher":{a.labels.push(function(e,t){const r=t.getChild("Identifier"),a=(0,ae.KF)(e,r),n=(0,ae.KF)(e,r.nextSibling),s=(0,ae.KF)(e,t.getChild("String")).replace(/"/g,"");return{label:a,op:n,value:s}}(e,t));const n=t.getChild(ae.GQ);n&&r.errors.push((0,ae.wf)(e,n));break}case"LineFilter":{const{operation:n,error:s}=function(e,t){if((0,ae.ff)(e,t,"Ip").length>0)return{error:"Matching ip addresses not supported in query builder"};const r={"|=":"__line_contains","!=":"__line_contains_not","|~":"__line_matches_regex","!~":'"__line_matches_regex"_not'},a=(0,ae.KF)(e,t.getChild("Filter")),n=oe((0,ae.KF)(e,t.getChild("String")));return{operation:{id:r[a],params:[n]}}}(e,t);n&&a.operations.push(n),s&&r.errors.push(ce(e,t,s));break}case"LabelParser":a.operations.push(function(e,t){const r=t.firstChild,a=(0,ae.KF)(e,r),n=oe((0,ae.KF)(e,t.getChild("String")));return{id:a,params:n?[n]:[]}}(e,t));break;case"LabelFilter":{const{operation:n,error:s}=function(e,t){if(t.getChild("Or")||t.getChild("And")||t.getChild("Comma"))return{error:'Label filter with comma, "and", "or" not supported in query builder'};if("IpLabelFilter"===t.firstChild.name)return{error:"IpLabelFilter not supported in query builder"};const r="__label_filter";if("UnitFilter"===t.firstChild.name){const a=t.firstChild.firstChild.firstChild,n=a.nextSibling,s=n.nextSibling,i=oe((0,ae.KF)(e,s));return{operation:{id:r,params:[(0,ae.KF)(e,a),(0,ae.KF)(e,n),i]}}}const a=t.firstChild.firstChild,n=a.nextSibling,s=n.nextSibling,i=[(0,ae.KF)(e,a),(0,ae.KF)(e,n),oe((0,ae.KF)(e,s))];if("__error__="===i.join(""))return{operation:{id:"__label_filter_no_errors",params:[]}};return{operation:{id:r,params:i}}}(e,t);n&&a.operations.push(n),s&&r.errors.push(ce(e,t,s));break}case"JsonExpressionParser":{const a="JsonExpressionParser not supported in visual query builder";r.errors.push(ce(e,t,a))}case"LineFormatExpr":a.operations.push(function(e,t){const r="line_format",a=oe((0,ae.KF)(e,t.getChild("String")));return{id:r,params:[a]}}(e,t));break;case"LabelFormatMatcher":a.operations.push(function(e,t){const r="label_format",a=t.getChild("Identifier"),n=a.nextSibling.nextSibling;let s=oe((0,ae.KF)(e,n));return{id:r,params:[(0,ae.KF)(e,a),s]}}(e,t));break;case"UnwrapExpr":{const{operation:n,error:s}=function(e,t,r){const a=t.getChild("UnwrapExpr"),n=t.getChild("LabelFilter"),s=t.getChild("Unwrap");a&&se(e,a,r);n&&se(e,n,r);if(s){var i;return"ConvOp"===(null==s||null===(i=s.nextSibling)||void 0===i?void 0:i.type.name)?{error:"Unwrap with conversion operator not supported in query builder"}:{operation:{id:"unwrap",params:[(0,ae.KF)(e,null==s?void 0:s.nextSibling)]}}}return{}}(e,t,r);n&&a.operations.push(n),s&&r.errors.push(ce(e,t,s));break}case"RangeAggregationExpr":a.operations.push(function(e,t,r){const a=t.getChild("RangeOp"),n=(0,ae.KF)(e,a),s=t.getChild("Number"),i=t.getChild("LogRangeExpr"),o=null!=s?[(0,ae.KF)(e,s)]:[];let l=(0,ae.KF)(e,t).match(/\[(.+)\]/);null!=l&&l[1]&&o.push(l[1]);const c={id:n,params:o};i&&se(e,i,r);return c}(e,t,r));break;case"VectorAggregationExpr":a.operations.push(function(e,t,r){const a=t.getChild("VectorOp");let n=(0,ae.KF)(e,a);const s=t.getChild("Grouping"),i=[],o=t.getChild("Number");o&&i.push(Number((0,ae.KF)(e,o)));if(s){s.getChild("By")&&n&&(n=`__${n}_by`);s.getChild("Without")&&(n=`__${n}_without`),i.push(...(0,ae.ff)(e,s,"Identifier"))}const l=t.getChild("MetricExpr"),c={id:n,params:i};l&&se(e,l,r);return c}(e,t,r));break;case"BinOpExpr":!function(e,t,r){const a=r.query,n=t.firstChild,s=(0,ae.KF)(e,n.nextSibling),i=function(e,t){if(!t)return;if(t.getChild("Bool"))return{isBool:!0,isMatcher:!1};{var r;const a=t.getChild("OnOrIgnoring");if(!a)return;return{isMatcher:!0,isBool:!1,matches:(0,ae.KF)(e,null===(r=a.getChild("GroupingLabels"))||void 0===r?void 0:r.getChild("GroupingLabelList")),matchType:a.getChild("On")?"on":"ignoring"}}}(e,t.getChild("BinModifiers")),o=t.lastChild,l=ie[s],c=le(n,"MetricExpr.LiteralExpr.Number"),u=le(o,"MetricExpr.LiteralExpr.Number"),d=o.getChild("BinOpExpr");c||se(e,n,r);if(u)a.operations.push((0,ae.Es)(l,e,o,!(null==i||!i.isBool)));else if(d){const t=(0,ae.ge)(o);"Number"===(null==t?void 0:t.name)&&a.operations.push((0,ae.Es)(l,e,t,!(null==i||!i.isBool))),se(e,o,r)}else{a.binaryQueries=a.binaryQueries||[];const t={operator:s,query:{labels:[],operations:[]}};null!=i&&i.isMatcher&&(t.vectorMatchesType=i.matchType,t.vectorMatches=i.matches),a.binaryQueries.push(t),se(e,o,{query:t.query,errors:r.errors})}}(e,t,r);break;case ae.GQ:if(function(e){var t;return"Range"===(null==e||null===(t=e.parent)||void 0===t?void 0:t.name)}(t))break;r.errors.push((0,ae.wf)(e,t));break;default:{let a=t.firstChild;for(;a;)se(e,a,r),a=a.nextSibling}}}const ie=U.reduce(((e,t)=>(e[t.sign]={id:t.id,comparison:t.comparison},e)),{});function oe(e){return'"'===e[0]&&'"'===e[e.length-1]?e.replace(/"/g,"").replace(/\\\\/g,"\\"):e.replace(/`/g,"")}function le(e,t){let r=e;const a=t.split(".");for(const e of a)if(r=r.getChild(e),!r)return null;return r}function ce(e,t,r){const a=(0,ae.wf)(e,t);return a.text=`${r}: ${a.text}`,a}var ue=r(17421),de=r(91871);const Oe="LokiQueryEditorModeDefault";function pe(e){if(null!=e&&""!==e)return T.c.Code;const t=ue.Z.get(Oe);switch(t){case T.c.Builder:case T.c.Code:case T.c.Explain:return t;default:return T.c.Builder}}const me="LokiQueryEditorRawQueryDefault";function ge(){const[e,t]=(0,y.useState)(function(){const e=ue.Z.get(me);return void 0===e||Boolean(parseInt(e,10))}()),r=(0,y.useCallback)((e=>{!function(e){ue.Z.set(me,e?"1":"0")}(e),t(e)}),[]);return[e,r]}var he,fe=r(53772),ye=r(50818),ve=r(13177),be=r(77441),xe=r(5782),Qe=r(36636),Pe=r(64722);const _e=y.memo((e=>{let{nestedQuery:t,index:r,datasource:a,onChange:n,onRemove:s,onRunQuery:o}=e;const l=(0,w.useStyles2)(Le);return(0,b.jsxs)("div",{className:l.card,children:[(0,b.jsxs)("div",{className:l.header,children:[(0,b.jsx)("div",{className:l.name,children:"Operator"}),(0,b.jsx)(w.Select,{width:"auto",options:Re,value:(0,i.toOption)(t.operator),onChange:e=>{n(r,Object.assign({},t,{operator:e.value}))}}),(0,b.jsx)("div",{className:l.name,children:"Vector matches"}),(0,b.jsxs)("div",{className:l.vectorMatchWrapper,children:[(0,b.jsx)(w.Select,{width:"auto",value:t.vectorMatchesType||"on",allowCustomValue:!0,options:[{value:"on",label:"on"},{value:"ignoring",label:"ignoring"}],onChange:e=>{n(r,Object.assign({},t,{vectorMatchesType:e.value}))}}),(0,b.jsx)(Pe.H,{className:l.vectorMatchInput,minWidth:20,defaultValue:t.vectorMatches,onCommitChange:e=>{n(r,Object.assign({},t,{vectorMatches:e.currentTarget.value,vectorMatchesType:t.vectorMatchesType||"on"}))}})]}),he||(he=(0,b.jsx)(L.FlexItem,{grow:1})),(0,b.jsx)(w.IconButton,{name:"times",size:"sm",onClick:()=>s(r)})]}),(0,b.jsx)("div",{className:l.body,children:(0,b.jsx)(L.EditorRows,{children:(0,b.jsx)(qe,{query:t.query,datasource:a,nested:!0,onRunQuery:o,onChange:e=>{n(r,Object.assign({},t,{query:e}))}})})})]})})),Re=U.map((e=>({label:e.sign,value:e.sign})));_e.displayName="NestedQuery";const Le=e=>({card:(0,Qe.css)({label:"card",display:"flex",flexDirection:"column",gap:e.spacing(.5)}),header:(0,Qe.css)({label:"header",padding:e.spacing(.5,.5,.5,1),gap:e.spacing(1),display:"flex",alignItems:"center"}),name:(0,Qe.css)({label:"name",whiteSpace:"nowrap"}),body:(0,Qe.css)({label:"body",paddingLeft:e.spacing(2)}),vectorMatchInput:(0,Qe.css)({label:"vectorMatchInput",marginLeft:-1}),vectorMatchWrapper:(0,Qe.css)({label:"vectorMatchWrapper",display:"flex"})});function we(e){var t;let{query:r,datasource:a,onChange:n,onRunQuery:s}=e;const i=null!==(t=r.binaryQueries)&&void 0!==t?t:[],o=(e,t)=>{const a=[...i];a.splice(e,1,t),n(Object.assign({},r,{binaryQueries:a}))},l=e=>{const t=[...i.slice(0,e),...i.slice(e+1)];n(Object.assign({},r,{binaryQueries:t}))};return(0,b.jsx)(L.Stack,{direction:"column",gap:1,children:i.map(((e,t)=>(0,b.jsx)(_e,{nestedQuery:e,index:t,onChange:o,datasource:a,onRemove:l,onRunQuery:s},t.toString())))})}const qe=y.memo((e=>{let{datasource:t,query:r,nested:a,onChange:n,onRunQuery:s}=e;const i=async e=>{const r=await e;return[...t.getVariables(),...r].map((e=>({label:e,value:e})))},o=(0,y.useMemo)((()=>{const{labels:e,operations:t}=r;if(!e.length&&t.length){if(1===t.length&&t[0].id===C.LineContains&&""===t[0].params[0])return;return"You need to specify at least 1 label filter (stream selector)"}}),[r]);return(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)(L.EditorRow,{children:(0,b.jsx)(ye.P,{onGetLabelNames:e=>i((async e=>{const a=r.labels.filter((t=>t!==e));if(0===a.length)return await t.languageProvider.refreshLogLabels(),t.languageProvider.getLabelKeys();const n=Z.renderLabels(a),s=await t.languageProvider.fetchSeriesLabels(n);return Object.keys(s).sort()})(e)),onGetLabelValues:e=>i((async e=>{if(!e.label)return[];let a;const n=r.labels.filter((t=>t!==e));if(0===n.length)a=await t.languageProvider.fetchLabelValues(e.label);else{const r=Z.renderLabels(n);a=(await t.languageProvider.fetchSeriesLabels(r))[t.interpolateString(e.label)]}return a?a.map((t=>(0,xe.Hk)(t,e.op))):[]})(e)),labelsFilters:r.labels,onChange:e=>{n(Object.assign({},r,{labels:e}))},error:o})}),(0,b.jsx)(be.B,{children:(0,b.jsx)(ve.P,{queryModeller:Z,query:r,onChange:n,onRunQuery:s,datasource:t})}),r.binaryQueries&&r.binaryQueries.length>0&&(0,b.jsx)(we,{query:r,datasource:t,onChange:n,onRunQuery:s})]})}));qe.displayName="LokiQueryBuilder";var je=r(3690);function $e(e){let{query:t}=e;return(0,b.jsx)(L.EditorRow,{children:(0,b.jsx)(L.EditorFieldGroup,{children:(0,b.jsx)(L.EditorField,{label:"Raw query",children:(0,b.jsx)(je.U,{query:t,lang:{grammar:k.xY,name:"lokiql"}})})})})}function Te(e){const{query:t,onChange:r,onRunQuery:a,datasource:n,showRawQuery:s}=e,[i,o]=(0,y.useReducer)(Fe.reducer,{expr:t.expr,visQuery:""===t.expr?{labels:[],operations:[{id:"__line_contains",params:[""]}]}:void 0});(0,y.useEffect)((()=>{o(ke(t.expr))}),[t.expr]);return i.visQuery?(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)(qe,{query:i.visQuery,datasource:n,onChange:t=>{const a=Z.renderQuery(t);o(Se({visQuery:t,expr:a})),r(Object.assign({},e.query,{expr:a}))},onRunQuery:a}),s&&(0,b.jsx)($e,{query:t.expr})]}):null}const Fe=(0,fe.oM)({name:"loki-builder-container",initialState:{expr:""},reducers:{visualQueryChange:(e,t)=>{e.expr=t.payload.expr,e.visQuery=t.payload.visQuery},exprChanged:(e,t)=>{if(!e.visQuery||e.expr!==t.payload){e.expr=t.payload;const r=ne(t.payload);e.visQuery=r.query}}}}),{visualQueryChange:Se,exprChanged:ke}=Fe.actions;var Ee=r(2926),Ce=r(74929);const Xe=y.memo((e=>{let{query:t}=e;const r=ne(t||"").query,a={grammar:k.xY,name:"lokiql"};return(0,b.jsxs)(L.Stack,{gap:0,direction:"column",children:[(0,b.jsx)(Ee.B,{children:(0,b.jsx)(je.U,{query:t,lang:a})}),(0,b.jsx)(Ee.B,{stepNumber:1,title:(0,b.jsx)(je.U,{query:`${Z.renderLabels(r.labels)}`,lang:a}),children:"Fetch all log lines matching label filters."}),(0,b.jsx)(Ce.V,{stepNumber:2,queryModeller:Z,query:r,lang:a})]})}));Xe.displayName="LokiQueryBuilderExplained";var Ue=r(68374),Ie=r(90441),Ne=r(50539),Ve=r.n(Ne),De=r(26702),Me=r(58788),Ye=r(2937),Ae=r(73296),Ge=r(10010),Be=r(76913),We=r(53720),ze=r(31359),Ke=r(62236),Ze=r(75478),He=r(7166),Je=r(25857),et=r(18887),tt=r(53454);const rt=[...tt.YO,...tt.fP,...tt.Os,...k.zy],at=/([A-Za-z:][\w:]*)\b(?![\]{=!",])/g;function nt(e,t,r,a,n){if(!t||!r)throw new Error("Need label to add to query.");const s=r===1/0?"+Inf":r.toString();let i;e=e.replace(at,((t,r,a)=>{const s=function(e,t,r,a,n){const s=function(e,t,r,a){const n=e.slice(t).indexOf(r),s=e.slice(t).indexOf(a);return s>-1&&(-1===n||n>s)}(e,r,"{","}"),i=a&&tt.fP.indexOf(a)>-1,o=t.endsWith(":"),l='"'===e[r-1],c="$"===e[r-1],u=["s","m","h","d","w"].includes(t)&&Boolean(Number(e[r-1]));if(!(n||s||o||i||l||c||u||-1!==rt.indexOf(t)))return!0;return!1}(e,r,a,i,n);return i=r,s?`${r}{}`:r}));const o=/(\$)?{([^{]*)}/g,l=[];let c=0,u="",d=o.exec(e);for(;d;){const r=e.slice(c,d.index);if(c=d.index+d[2].length+2,u=e.slice(d.index+d[0].length),d[0].startsWith("{.")||d[1])l.push(r),l.push(d[0]);else{const e=it(d[2],t,s,a);l.push(r,e)}d=o.exec(e)}return l.push(u),l.join("")}const st=/(\w+)\s*(=|!=|=~|!~)\s*("[^"]*")/g;function it(e,t,r,a){const n=[];if(e){let t=st.exec(e);for(;t;)n.push({key:t[1],operator:t[2],value:t[3]}),t=st.exec(e)}const s=a||"=";n.push({key:t,operator:s,value:`"${r}"`});const i=(0,f.chain)(n).uniqWith(f.isEqual).compact().sortBy("key").map((e=>{let{key:t,operator:r,value:a}=e;return`${t}${r}${a}`})).value().join(",");return`{${i}}`}function ot(e){const t=(0,v.getDataSourceSrv)(),r=e.reduce(((e,r)=>{if(r.datasourceUid){var a;const n=t.getInstanceSettings(r.datasourceUid);e.push({title:r.urlDisplayLabel||"",url:"",internal:{query:{query:r.url},datasourceUid:r.datasourceUid,datasourceName:null!==(a=null==n?void 0:n.name)&&void 0!==a?a:"Data source not found"}})}else r.url&&e.push({title:r.urlDisplayLabel||"",url:r.url});return e}),[]);return{name:e[0].name,type:i.FieldType.string,config:{links:r},values:new i.ArrayVector([])}}function lt(e){const t=e.filter((e=>void 0!==e.refId)),r=(0,f.groupBy)(t,(e=>e.refId));return Object.entries(r).map((e=>{let[t,r]=e;return function(e,t){const r={name:"Time",config:{},values:new i.ArrayVector,type:i.FieldType.time},a={name:`Value #${t}`,config:{},values:new i.ArrayVector,type:i.FieldType.number},n=new Set(e.map((e=>e.fields.map((e=>{var t;return Object.keys(null!==(t=e.labels)&&void 0!==t?t:{})})).flat())).flat()),s=Array.from(n).sort().map((e=>({name:e,config:{filterable:!0},values:new i.ArrayVector,type:i.FieldType.string})));return e.forEach((e=>{var t;const n=e.fields.find((e=>e.type===i.FieldType.time)),o=e.fields.find((e=>e.type===i.FieldType.number));if(null==n||null==o)return;const l=n.values.toArray(),c=o.values.toArray();for(let e of l)r.values.add(e);for(let e of c)a.values.add(e);const u=null!==(t=o.labels)&&void 0!==t?t:{};for(let e of s){var d;const t=null!==(d=u[e.name])&&void 0!==d?d:"";for(let r=0;r<c.length;r++)e.values.add(t)}})),{fields:[r,...s,a],refId:t,meta:{preferredVisualisationType:"table"},length:r.values.length}}(r,t)}))}const ct=["instant","range"],ut=["instant","range"],dt=["instant","range"];function Ot(e,t){if(null==e)return{};var r,a,n={},s=Object.keys(e);for(a=0;a<s.length;a++)r=s[a],t.indexOf(r)>=0||(n[r]=e[r]);return n}function pt(e){return`${e||""}`.trim()}function mt(e){let t=e;const r=[];for(;t;){const e=t.search(/\|=|\|~|!=|!~/);if(-1===e)break;const a=t.slice(e,e+2),n=0===t.slice(e).search(/!=|!~/);if(t=t.slice(e+2),n)continue;const s=t.search(/\|/);let i;-1===s?i=t.trim():(i=t.slice(0,s).trim(),t=t.slice(s));const o=i.match(/"(.*?)"/),l=i.match(/`(.*?)`/),c=o||l;if(!c)return r;{const e=c[1];let t="";t="|~"===a?l?e:e.replace(/\\\\/g,"\\"):(0,f.escapeRegExp)(e),t&&r.push(t)}}return r}function gt(e){const{queryType:t}=e;if(t===de.EM.Range||t===de.EM.Instant||t===de.EM.Stream){return Ot(e,ct)}if(!0===e.instant){const t=Ot(e,ut);return Object.assign({},t,{queryType:de.EM.Instant})}const r=Ot(e,dt);return Object.assign({},r,{queryType:de.EM.Range})}function ht(e){var t,r;const a=null!==(t=null===(r=e.fields.find((e=>"labels"===e.name)))||void 0===r?void 0:r.values.toArray())&&void 0!==t?t:[];return a.some((e=>void 0!==e.__error__))}const ft=["meta"],yt=["data","error"];function vt(e,t){if(null==e)return{};var r,a,n={},s=Object.keys(e);for(a=0;a<s.length;a++)r=s[a],t.indexOf(r)>=0||(n[r]=e[r]);return n}function bt(e,t){const{meta:r}=e,a=vt(e,ft),n=Object.assign({},r,t);return Object.assign({},a,{meta:n})}function xt(e,t,r){var a;const n=Object.assign({},null===(a=e.meta)||void 0===a?void 0:a.custom,{lokiQueryStatKey:"Summary: total bytes processed"});ht(e)&&(n.error="Error when parsing some of the logs");const s=bt(e,{preferredVisualisationType:"logs",limit:null==t?void 0:t.maxLines,searchWords:void 0!==t?mt(pt(t.expr)):void 0,custom:n}),o=function(e,t){if(!t.length)return[];const r=(0,f.groupBy)(t,"name"),a=Object.values(r).map(ot),n=e.fields.find((e=>e.type===i.FieldType.string));if(void 0===n)throw new Error("invalid logs-dataframe, string-field missing");return n.values.toArray().forEach((e=>{for(const t of a){const a=e.match(r[t.name][0].matcherRegex);t.values.add(a&&a[1])}})),a}(s,r);return Object.assign({},s,{fields:[...s.fields,...o]})}function Qt(e,t,r){return e.map((e=>xt(e,void 0!==e.refId?t.get(e.refId):void 0,r)))}function Pt(e){const t={preferredVisualisationType:"graph"};return e.map((e=>bt(e,t)))}function _t(e,t){const r=[],a=[],n=[];return e.forEach((e=>{if(function(e){return e.fields.every((e=>e.type===i.FieldType.time||e.type===i.FieldType.number))}(e)){var s;null!=e.refId&&(null===(s=t.get(e.refId))||void 0===s?void 0:s.queryType)===de.EM.Instant?a.push(e):n.push(e)}else r.push(e)})),{streamsFrames:r,metricInstantFrames:a,metricRangeFrames:n}}function Rt(e,t){if(void 0===e)return e;const{refId:r,message:a}=e;if(void 0===r||void 0===a)return e;const n=t.get(r);return void 0===n?e:a.includes("escape")&&n.expr.includes("\\")?Object.assign({},e,{message:`${a}. Make sure that all special characters are escaped with \\. For more information on escaping of special characters visit LogQL documentation at https://grafana.com/docs/loki/latest/logql/.`}):e}var Lt=r(64303),wt=r.n(Lt),qt=r(82777);function jt(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}const $t=["job","namespace"],Tt="{}",Ft=[{label:"$__interval",sortValue:"$__interval"},{label:"$__range",sortValue:"$__range"},{label:"1m",sortValue:"00:01:00"},{label:"5m",sortValue:"00:05:00"},{label:"10m",sortValue:"00:10:00"},{label:"30m",sortValue:"00:30:00"},{label:"1h",sortValue:"01:00:00"},{label:"1d",sortValue:"24:00:00"}],St=e=>({label:e,filterText:`"${e}"`});class kt extends i.LanguageProvider{constructor(e,t){super(),jt(this,"labelKeys",void 0),jt(this,"labelFetchTs",void 0),jt(this,"started",!1),jt(this,"datasource",void 0),jt(this,"lookupsDisabled",!1),jt(this,"seriesCache",new(wt())({max:10})),jt(this,"labelsCache",new(wt())({max:10})),jt(this,"cleanText",(e=>e.replace(/[{}[\]="(),!~+\-*/^%\|]/g,"").trim())),jt(this,"request",(async(e,t)=>{try{return await this.datasource.metadataRequest(e,t)}catch(e){console.error(e)}})),jt(this,"start",(()=>(this.startTask||(this.startTask=this.fetchLabels().then((()=>(this.started=!0,[])))),this.startTask))),jt(this,"getBeginningCompletionItems",(e=>({suggestions:[...this.getEmptyCompletionItems(e).suggestions,...this.getTermCompletionItems().suggestions]}))),jt(this,"getTermCompletionItems",(()=>{const e=[];return e.push({prefixMatch:!0,label:"Functions",items:k.r8.map((e=>Object.assign({},e,{kind:"function"})))}),{suggestions:e}})),jt(this,"getPipeCompletionItem",(()=>{const e=[];return e.push({label:"Operators",items:k.Rd.map((e=>Object.assign({},e,{kind:"operators"})))}),e.push({label:"Parsers",items:k.uR.map((e=>Object.assign({},e,{kind:"parsers"})))}),{suggestions:e}})),jt(this,"fetchSeriesLabels",(async e=>{const t=this.datasource.interpolateString(e),r="series",{start:a,end:n}=this.datasource.getTimeRangeParams(),s=this.generateCacheKey(r,a,n,t);let i=this.seriesCache.get(s);if(!i){this.seriesCache.set(s,{});const e={"match[]":t,start:a,end:n},o=await this.request(r,e),{values:l}=(0,qt.DY)(o);i=l,this.seriesCache.set(s,i)}return i})),jt(this,"fetchSeries",(async e=>{const{start:t,end:r}=this.datasource.getTimeRangeParams(),a={"match[]":e,start:t,end:r};return await this.request("series",a)})),this.datasource=e,this.labelKeys=[],this.labelFetchTs=0,Object.assign(this,t)}getSyntax(){return k.ZP}getLabelKeys(){return this.labelKeys}async provideCompletionItems(e,t){const{wrapperClasses:r,value:a,prefix:n,text:s}=e,i={suggestions:[]};if(!a)return i;const o=0===(null==a?void 0:a.document.text.length),l=a.document.getTextsAtRange(a.selection),c=1===l.size?l.first().getText():null,u=c?c[a.selection.anchor.offset]:null,d=r.length>3,O=n&&!d,p=!u||")"===u,m=n&&!s.match(/^['"~=\]})\s]+$/)&&p,g=s.match(/[+\-*/^%]/);return r.includes("context-range")?this.getRangeCompletionItems():r.includes("context-labels")?await this.getLabelCompletionItems(e):r.includes("context-pipe")?this.getPipeCompletionItem():o?this.getEmptyCompletionItems(t):O&&p&&!g?this.getBeginningCompletionItems(t):O&&m?this.getTermCompletionItems():i}getEmptyCompletionItems(e){const t=null==e?void 0:e.history,r=[];if(null!=t&&t.length){const e=(0,f.chain)(t).map((e=>e.query.expr)).filter().uniq().take(10).map(St).map((e=>function(e,t){const r=Date.now()-864e5,a=t.filter((t=>t.ts>r&&t.query.expr===e.label));let n=`Queried ${a.length} times in the last 24h.`;const s=a[0];s&&(n=`${n} Last queried ${(0,i.dateTime)(s.ts).fromNow()}.`);return Object.assign({},e,{documentation:n})}(e,t))).value();r.push({prefixMatch:!0,skipSort:!0,label:"History",items:e})}return{suggestions:r}}getRangeCompletionItems(){return{context:"context-range",suggestions:[{label:"Range vector",items:[...Ft]}]}}async getLabelCompletionItems(e){let{text:t,wrapperClasses:r,labelKey:a,value:n}=e,s="context-labels";const i=[];if(!n)return{context:s,suggestions:[]};const o=n.anchorBlock.getText(),l=n.selection.anchor.offset,c=t.match(/^(=|=~|!=|!~)/);let u,d;try{d=(0,qt.rV)(o,l),u=d.selector}catch{u=Tt}if(!a&&u===Tt){await this.start();return{context:s,suggestions:[{label:"Labels",items:this.getLabelKeys().map(St)}]}}const O=d?d.labelKeys:[];let p;if(u)if(u===Tt&&a){p={[a]:await this.getLabelValues(a)}}else p=await this.getSeriesLabels(u);if(!p)return console.warn(`Server did not return any values for selector = ${u}`),{context:s,suggestions:i};if(t&&c||r.includes("attr-value"))a&&p[a]&&(s="context-label-values",i.push({label:`Label values for "${a}"`,items:p[a].map(St).filter((e=>{let{filterText:r}=e;return r!==t}))}));else{const e=p?Object.keys(p):$t;if(e){const t=(0,f.difference)(e,O);if(t.length){const e=t.map((e=>({label:e}))),r={label:"Labels",items:e};i.push(r)}}}return{context:s,suggestions:i}}importFromAbstractQuery(e){return{refId:e.refId,expr:(0,qt.PL)(e),queryType:de.EM.Range}}exportToAbstractQuery(e){const t=e.expr;if(!t||0===t.length)return{refId:e.refId,labelMatchers:[]};const r=Ve().tokenize(t,k.ZP);return{refId:e.refId,labelMatchers:(0,qt.UO)(r)}}async getSeriesLabels(e){if(!this.lookupsDisabled)try{return await this.fetchSeriesLabels(e)}catch(e){return void console.error(e)}}async fetchLabels(){const e=this.datasource.getTimeRangeParams();this.labelFetchTs=Date.now().valueOf();const t=await this.request("labels",e);if(Array.isArray(t)){const e=t.slice().sort().filter((e=>"__name__"!==e));this.labelKeys=e}return[]}async refreshLogLabels(e){(this.labelKeys&&Date.now().valueOf()-this.labelFetchTs>3e4||e)&&await this.fetchLabels()}generateCacheKey(e,t,r,a){return[e,this.roundTime(t),this.roundTime(r),a].join()}roundTime(e){return e?Math.floor(e/1e6/1e3/60/5):0}async getLabelValues(e){return await this.fetchLabelValues(e)}async fetchLabelValues(e){var t;const r=encodeURIComponent(this.datasource.interpolateString(e)),a=`label/${r}/values`,n=this.datasource.getTimeRangeParams(),{start:s,end:i}=n,o=this.generateCacheKey(a,s,i,r),l={start:s,end:i};let c=this.labelsCache.get(o);if(!c){this.labelsCache.set(o,[]);const e=await this.request(a,l);Array.isArray(e)&&(c=e.slice().sort(),this.labelsCache.set(o,c))}return null!==(t=c)&&void 0!==t?t:[]}}var Et=r(14629),Ct=r(94925),Xt=r(44998),Ut=r(92838),It=r(9683),Nt=r(80574),Vt=r(75273),Dt=r(21132),Mt=r(99918),Yt=r(61928),At={url:"",deserializer:function(e){return JSON.parse(e.data)},serializer:function(e){return JSON.stringify(e)}},Gt=function(e){function t(t,r){var a=e.call(this)||this;if(a._socket=null,t instanceof Dt.y)a.destination=r,a.source=t;else{var n=a._config=(0,It.__assign)({},At);if(a._output=new Nt.x,"string"==typeof t)n.url=t;else for(var s in t)t.hasOwnProperty(s)&&(n[s]=t[s]);if(!n.WebSocketCtor&&WebSocket)n.WebSocketCtor=WebSocket;else if(!n.WebSocketCtor)throw new Error("no WebSocket constructor can be found");a.destination=new Yt.t}return a}return(0,It.__extends)(t,e),t.prototype.lift=function(e){var r=new t(this._config,this.destination);return r.operator=e,r.source=this,r},t.prototype._resetState=function(){this._socket=null,this.source||(this.destination=new Yt.t),this._output=new Nt.x},t.prototype.multiplex=function(e,t,r){var a=this;return new Dt.y((function(n){try{a.next(e())}catch(e){n.error(e)}var s=a.subscribe({next:function(e){try{r(e)&&n.next(e)}catch(e){n.error(e)}},error:function(e){return n.error(e)},complete:function(){return n.complete()}});return function(){try{a.next(t())}catch(e){n.error(e)}s.unsubscribe()}}))},t.prototype._connectSocket=function(){var e=this,t=this._config,r=t.WebSocketCtor,a=t.protocol,n=t.url,s=t.binaryType,i=this._output,o=null;try{o=a?new r(n,a):new r(n),this._socket=o,s&&(this._socket.binaryType=s)}catch(e){return void i.error(e)}var l=new Mt.w0((function(){e._socket=null,o&&1===o.readyState&&o.close()}));o.onopen=function(t){if(!e._socket)return o.close(),void e._resetState();var r=e._config.openObserver;r&&r.next(t);var a=e.destination;e.destination=Vt.Lv.create((function(t){if(1===o.readyState)try{var r=e._config.serializer;o.send(r(t))}catch(t){e.destination.error(t)}}),(function(t){var r=e._config.closingObserver;r&&r.next(void 0),t&&t.code?o.close(t.code,t.reason):i.error(new TypeError("WebSocketSubject.error must be called with an object with an error code, and an optional reason: { code: number, reason: string }")),e._resetState()}),(function(){var t=e._config.closingObserver;t&&t.next(void 0),o.close(),e._resetState()})),a&&a instanceof Yt.t&&l.add(a.subscribe(e.destination))},o.onerror=function(t){e._resetState(),i.error(t)},o.onclose=function(t){o===e._socket&&e._resetState();var r=e._config.closeObserver;r&&r.next(t),t.wasClean?i.complete():i.error(t)},o.onmessage=function(t){try{var r=e._config.deserializer;i.next(r(t))}catch(e){i.error(e)}}},t.prototype._subscribe=function(e){var t=this,r=this.source;return r?r.subscribe(e):(this._socket||this._connectSocket(),this._output.subscribe(e),e.add((function(){var e=t._socket;0===t._output.observers.length&&(!e||1!==e.readyState&&0!==e.readyState||e.close(),t._resetState())})),e)},t.prototype.unsubscribe=function(){var t=this._socket;!t||1!==t.readyState&&0!==t.readyState||t.close(),this._resetState(),e.prototype.unsubscribe.call(this)},t}(Nt.u);var Bt=r(25058),Wt=r(91152);const zt=function(e){if(!(0,Wt.Z)(e))throw TypeError("Invalid UUID");var t,r=new Uint8Array(16);return r[0]=(t=parseInt(e.slice(0,8),16))>>>24,r[1]=t>>>16&255,r[2]=t>>>8&255,r[3]=255&t,r[4]=(t=parseInt(e.slice(9,13),16))>>>8,r[5]=255&t,r[6]=(t=parseInt(e.slice(14,18),16))>>>8,r[7]=255&t,r[8]=(t=parseInt(e.slice(19,23),16))>>>8,r[9]=255&t,r[10]=(t=parseInt(e.slice(24,36),16))/1099511627776&255,r[11]=t/4294967296&255,r[12]=t>>>24&255,r[13]=t>>>16&255,r[14]=t>>>8&255,r[15]=255&t,r};function Kt(e,t,r,a){switch(e){case 0:return t&r^~t&a;case 1:case 3:return t^r^a;case 2:return t&r^t&a^r&a}}function Zt(e,t){return e<<t|e>>>32-t}var Ht=function(e,t,r){function a(e,a,n,s){if("string"==typeof e&&(e=function(e){e=unescape(encodeURIComponent(e));for(var t=[],r=0;r<e.length;++r)t.push(e.charCodeAt(r));return t}(e)),"string"==typeof a&&(a=zt(a)),16!==a.length)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");var i=new Uint8Array(16+e.length);if(i.set(a),i.set(e,a.length),(i=r(i))[6]=15&i[6]|t,i[8]=63&i[8]|128,n){s=s||0;for(var o=0;o<16;++o)n[s+o]=i[o];return n}return(0,Bt.Z)(i)}try{a.name=e}catch(e){}return a.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",a.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8",a}("v5",80,(function(e){var t=[1518500249,1859775393,2400959708,3395469782],r=[1732584193,4023233417,2562383102,271733878,3285377520];if("string"==typeof e){var a=unescape(encodeURIComponent(e));e=[];for(var n=0;n<a.length;++n)e.push(a.charCodeAt(n))}else Array.isArray(e)||(e=Array.prototype.slice.call(e));e.push(128);for(var s=e.length/4+2,i=Math.ceil(s/16),o=new Array(i),l=0;l<i;++l){for(var c=new Uint32Array(16),u=0;u<16;++u)c[u]=e[64*l+4*u]<<24|e[64*l+4*u+1]<<16|e[64*l+4*u+2]<<8|e[64*l+4*u+3];o[l]=c}o[i-1][14]=8*(e.length-1)/Math.pow(2,32),o[i-1][14]=Math.floor(o[i-1][14]),o[i-1][15]=8*(e.length-1)&4294967295;for(var d=0;d<i;++d){for(var O=new Uint32Array(80),p=0;p<16;++p)O[p]=o[d][p];for(var m=16;m<80;++m)O[m]=Zt(O[m-3]^O[m-8]^O[m-14]^O[m-16],1);for(var g=r[0],h=r[1],f=r[2],y=r[3],v=r[4],b=0;b<80;++b){var x=Math.floor(b/20),Q=Zt(g,5)+Kt(x,h,f,y)+v+t[x]+O[b]>>>0;v=y,y=f,f=Zt(h,30)>>>0,h=g,g=Q}r[0]=r[0]+g>>>0,r[1]=r[1]+h>>>0,r[2]=r[2]+f>>>0,r[3]=r[3]+y>>>0,r[4]=r[4]+v>>>0}return[r[0]>>24&255,r[0]>>16&255,r[0]>>8&255,255&r[0],r[1]>>24&255,r[1]>>16&255,r[1]>>8&255,255&r[1],r[2]>>24&255,r[2]>>16&255,r[2]>>8&255,255&r[2],r[3]>>24&255,r[3]>>16&255,r[3]>>8&255,255&r[3],r[4]>>24&255,r[4]>>16&255,r[4]>>8&255,255&r[4]]}));const Jt=Ht;var er=r(65660);function tr(e,t){const r=new i.ArrayVector([]),a=new i.ArrayVector([]),n=new i.ArrayVector([]),s=new i.ArrayVector([]),o=new i.ArrayVector([]),l={};for(const i of e){const e=i.stream,c=Object.entries(e).map((e=>{let[t,r]=e;return`${t}="${r}"`})).sort().join("");for(const[u,d]of i.values)r.add(e),a.add(new Date(parseInt(u.slice(0,-6),10)).toISOString()),n.add(u),s.add(d),o.add(rr(u,c,d,l,t))}return function(e,t,r,a,n,s){return{refId:s,fields:[{name:"labels",type:i.FieldType.other,config:{},values:n},{name:"Time",type:i.FieldType.time,config:{},values:e},{name:"Line",type:i.FieldType.string,config:{},values:r},{name:"tsNs",type:i.FieldType.time,config:{},values:t},{name:"id",type:i.FieldType.string,config:{},values:a}],length:e.length}}(a,n,s,o,r,t)}function rr(e,t,r,a,n){let s=Jt(`${e}_${t}_${r}`,"6ec946da-0f49-47a8-983a-1d76d17e7c92");if(s in a){const e=a[s]+1;a[s]=e,s=`${s}_${e}`}else a[s]=0;return n?`${s}_${n}`:s}function ar(e,t){const r=function(e,t){var r;let a=void 0===t||(0,f.isEmpty)(t.legendFormat)?function(e){const t=Object.entries(e).map((e=>`${e[0]}="${e[1]}"`)).join(",");return`{${t}}`}(e):(0,et.W)((0,v.getTemplateSrv)().replace(null!==(r=t.legendFormat)&&void 0!==r?r:"",t.scopedVars),e);!a&&t&&(a=t.query);return a}(e.metric,t);return{target:r,title:r,datapoints:sr(e.values),tags:e.metric,meta:t.meta,refId:t.refId}}function nr(e){switch(e){case"+Inf":return Number.POSITIVE_INFINITY;case"-Inf":return Number.NEGATIVE_INFINITY;default:return parseFloat(e)}}function sr(e){const t=[];for(const[r,a]of e){let e=nr(a);const n=1e3*r;t.push([e,n])}return t}function ir(e,t,r,a){if(!e||0===e.length)return new er.Z;const n=[...new Set(e.reduce(((e,t)=>e.concat(Object.keys(t.metric))),[])).values()].sort(),s=new er.Z;return s.refId=r,s.meta=a,s.columns=[{text:"Time",type:i.FieldType.time},...n.map((e=>({text:e,filterable:!0,type:i.FieldType.string}))),{text:`Value #${r}`,type:i.FieldType.number}],e.forEach((e=>{const t={metric:e.metric,values:e.value?[e.value]:e.values};t.values&&(t.metric?s.rows.push(...t.values.map((e=>{let[r,a]=e;return[1e3*r,...n.map((e=>t.metric[e]||"")),parseFloat(a)]}))):s.rows.concat(t.values.map((e=>{let[t,r]=e;return[1e3*t,parseFloat(r)]}))))})),s}function or(e,t,r,a){const n=r>0?e.data.result:[],s=function(e){const t=[];if(!e)return t;for(const a in e){const n=e[a];for(const e in n){const s=n[e];let i;/time/i.test(e)&&s?i="s":/bytes.*persecond/i.test(e)?i="Bps":/bytes/i.test(e)&&(i="decbytes");const o=`${(0,f.capitalize)(a)}: ${r=e,r.replace(/[A-Z]/g,(e=>` ${e.toLowerCase()}`))}`;t.push({displayName:o,value:s,unit:i})}}var r;return t}(e.data.stats),i={searchWords:mt(pt(t.expr)),limit:r,stats:s,custom:{lokiQueryStatKey:"Summary: total bytes processed",frameType:"LabeledTimeValues"},preferredVisualisationType:"logs"},o=tr(n,t.refId);return lr(o,a),i.custom&&ht(o)&&(i.custom.error="Error when parsing some of the logs"),s.length&&!n.length?[{fields:[],length:0,refId:t.refId,meta:i}]:[Object.assign({},o,{refId:t.refId,meta:i})]}const lr=(e,t)=>{var r;if(!t)return;const a=null!==(r=t.derivedFields)&&void 0!==r?r:[];if(!a.length)return;const n=(0,f.groupBy)(a,"name"),s=Object.values(n).map(cr);new i.DataFrameView(e).forEach((e=>{for(const t of s){const r=e.Line.match(n[t.name][0].matcherRegex);t.values.add(r&&r[1])}})),e.fields=[...e.fields,...s]};function cr(e){const t=(0,v.getDataSourceSrv)(),r=e.reduce(((e,r)=>{if(r.datasourceUid){var a;const n=t.getInstanceSettings(r.datasourceUid);e.push({title:r.urlDisplayLabel||"",url:"",internal:{query:{query:r.url},datasourceUid:r.datasourceUid,datasourceName:null!==(a=null==n?void 0:n.name)&&void 0!==a?a:"Data source not found"}})}else r.url&&e.push({title:r.urlDisplayLabel||"",url:r.url});return e}),[]);return{name:e[0].name,type:i.FieldType.string,config:{links:r},values:new i.ArrayVector([])}}function ur(e,t,r,a){const n=function(e,t,r,a){var n;const s={legendFormat:null!==(n=r.legendFormat)&&void 0!==n?n:"",query:t.query,refId:r.refId,meta:{preferredVisualisationType:"graph"},scopedVars:a};switch(e.data.resultType){case de.ox.Vector:return e.data.result.map((e=>ar({metric:e.metric,values:[e.value]},s)));case de.ox.Matrix:return e.data.result.map((e=>ar(e,s)));default:return[]}}(e,t,r,a),s=n.map((e=>(0,i.toDataFrame)(e))),{step:o}=t;if(null!=o){const e=1e3*o;s.forEach((t=>{t.fields.forEach((t=>{t.type===i.FieldType.time&&(t.config.interval=e)}))}))}return s}class dr{constructor(){!function(e,t,r){t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r}(this,"streams",{})}getStream(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3,r=this.streams[e.url];if(r)return r;const a=new i.CircularDataFrame({capacity:e.size});var n;return a.addField({name:"labels",type:i.FieldType.other}),a.addField({name:"Time",type:i.FieldType.time,config:{}}),a.addField({name:"Line",type:i.FieldType.string}).labels=(0,i.parseLabels)(e.query),a.addField({name:"id",type:i.FieldType.string}),a.addField({name:"tsNs",type:i.FieldType.time,config:{}}),a.meta=Object.assign({},a.meta,{preferredVisualisationType:"logs"}),a.refId=e.refId,r=(n=e.url,new Gt(n)).pipe((0,Ge.U)((e=>(function(e,t){const r=e.streams;if(!r||!r.length)return;let a={};for(const e of t.fields)if(e.type===i.FieldType.string){e.labels&&(a=e.labels);break}const n=t.fields[0],s=t.fields[1],o=t.fields[2],l=t.fields[3],c=t.fields[4],u={};for(const e of r){const r=(0,i.findUniqueLabels)(e.stream,a),d=Object.entries(e.stream).map((e=>{let[t,r]=e;return`${t}="${r}"`})).sort().join("");for(const[a,i]of e.values)s.values.add(new Date(parseInt(a.slice(0,-6),10)).toISOString()),c.values.add(a),o.values.add(i),n.values.add(r),l.values.add(rr(a,d,i,u,t.refId))}}(e,a),[a]))),(0,Ct.a)((e=>e.pipe((0,Xt.z)(((e,r)=>{const a=r+1;return 1006===e.code&&a<30?(a>10&&console.warn(`Websocket connection is being disrupted. We keep reconnecting but consider starting new live tailing again. Error: ${e.reason}`),(0,Et.H)(t)):(0,De._)(e)}))))),(0,Ut.x)((()=>{delete this.streams[e.url]}))),this.streams[e.url]=r,r}}const Or=["fields"];function pr(e,t){const{fields:r}=e,a=function(e,t){if(null==e)return{};var r,a,n={},s=Object.keys(e);for(a=0;a<s.length;a++)r=s[a],t.indexOf(r)>=0||(n[r]=e[r]);return n}(e,Or),n=r.find((e=>"tsNs"===e.name));if(void 0===n)throw new Error("missing nanosecond-timestamp field. should never happen");const s=function(e,t){const r=e.values.toArray(),a=Array(r.length);for(let e=0;e<a.length;e++)a[e]=e;const n="ASCENDING"===t;return a.sort(((e,t)=>{const a=r[e],s=r[t];return a<s?n?-1:1:a>s?n?1:-1:0})),a}(n,t);return Object.assign({},a,{fields:r.map((e=>Object.assign({},e,{values:new i.SortedVector(e.values,s)})))})}var mr=r(95647),gr=r(19323);function hr(e,t,r){var a;const n=r.range,s=n.to.valueOf()-n.from.valueOf()+1e3;let o,l=null!==(a=r.maxDataPoints)&&void 0!==a?a:1e3;l>100&&(l*=2);const c=t=>{if(null!=t&&t.message){const r=t.message;o?o.push(r):o=gr.Av.fromDataFrameJSON(r,{maxLength:l,maxDelta:s,displayNameFormat:e.legendFormat})}return o};return(0,mr.P)((()=>async function(e){const t=JSON.stringify({expr:e.expr}),r=(new TextEncoder).encode(t),a=await crypto.subtle.digest("SHA-1",r);return Array.from(new Uint8Array(a.slice(0,8))).map((e=>e.toString(16).padStart(2,"0"))).join("")}(e))).pipe((0,Xt.z)((r=>(0,v.getGrafanaLiveSrv)().getStream({scope:i.LiveChannelScope.DataSource,namespace:t.uid,path:`tail/${r}`,data:Object.assign({},e,{timeRange:{from:n.from.valueOf().toString(),to:n.to.valueOf().toString()}})}).pipe((0,Ge.U)((e=>{const t=c(e);return{data:t?[t]:[],state:i.LoadingState.Streaming}}))))))}const fr=["__interval","__interval_ms"];function yr(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}const vr=1e6,br="/loki/api/v1/query",xr={limit:1e3,query:""};function Qr(e,t,r,a){const n=i.rangeUtil.calculateInterval(t,1);return{targets:[e],requestId:a,interval:n.interval,intervalMs:n.intervalMs,range:t,scopedVars:{},timezone:"UTC",app:r,startTime:Date.now()}}class Pr extends v.DataSourceWithBackend{constructor(e){var t,r,a,n;let s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:(0,He.J)(),o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:(0,Ze.$t)();super(e),t=this,yr(this,"streams",new dr),yr(this,"languageProvider",void 0),yr(this,"maxLines",void 0),yr(this,"useBackendMode",void 0),yr(this,"runInstantQuery",(function(e,r){const a=t.getTime(r.range.to,!0),n=Lr(e.expr)?r.maxDataPoints:e.maxLines,s={query:e.expr,time:`${a+(1e9-a%1e9)}`,limit:Math.min(n||1/0,t.maxLines),direction:e.direction===de.sb.Forward?"FORWARD":"BACKWARD"},i={preferredVisualisationType:"table"};return t._request(br,s).pipe((0,Ge.U)((r=>r.data.data.resultType===de.ox.Stream?{data:r.data?or(r.data,e,s.limit,t.instanceSettings.jsonData):[],key:`${e.refId}_instant`}:{data:[ir(r.data.data.result,0,e.refId,i)],key:`${e.refId}_instant`})),(0,Be.K)((r=>(0,De._)((()=>t.processError(r,e))))))})),yr(this,"runRangeQuery",((e,t)=>{let r=Lr(e.expr)?t.maxDataPoints||this.maxLines:e.maxLines||this.maxLines;if(t.liveStreaming)return this.runLiveQuery(e,r);const a=this.createRangeQuery(e,t,r),n=e.volumeQuery?{"X-Query-Tags":"Source=logvolhist"}:void 0;return this._request("/loki/api/v1/query_range",a,{headers:n}).pipe((0,Be.K)((t=>(0,De._)((()=>this.processError(t,e))))),(0,We.w)((n=>function(e,t,r,a,n,s){switch(e.data.resultType){case de.ox.Stream:return(0,Ye.of)({data:or(e,t,a,n),key:`${t.refId}_log`});case de.ox.Vector:case de.ox.Matrix:return(0,Ye.of)({data:ur(e,r,t,s),key:t.refId});default:throw new Error(`Unknown result type "${e.data.resultType}".`)}}(n.data,e,a,r,this.instanceSettings.jsonData,t.scopedVars))))})),yr(this,"runLiveQuery",((e,t)=>{const r=this.createLiveTarget(e,t);return this.streams.getStream(r).pipe((0,Ge.U)((e=>({data:e||[],key:`loki-${r.refId}`,state:i.LoadingState.Streaming}))),(0,Be.K)((e=>(0,De._)((()=>`Live tailing was stopped due to following error: ${e.reason}`)))))})),yr(this,"getLogRowContext",((e,t)=>{const r=t&&t.direction||"BACKWARD",a=t&&t.limit||10,{query:n,range:s}=this.prepareLogRowContextQueryTarget(e,a,r),o=e=>{const t=e.data.map((e=>pr(e,"DESCENDING"))).map((e=>(e=>{const t=new i.FieldCache(e),r=t.getFirstFieldOfType(i.FieldType.time),a=t.getFirstFieldOfType(i.FieldType.string),n=t.getFieldByName("id");return void 0===r||void 0===a||void 0===n?Object.assign({},e,{fields:[]}):Object.assign({},e,{fields:[Object.assign({},r,{name:"ts"}),Object.assign({},a,{name:"line"}),Object.assign({},n,{name:"id"})]})})(e)));return Object.assign({},e,{data:t})},l=i.CoreApp.Explore;return(0,Me.n)(this.query(Qr(n,s,l,`log-row-context-query-${r}`)).pipe((0,Be.K)((e=>{throw{message:"Error during context query. Please check JS console logs.",status:e.status,statusText:e.statusText}})),(0,We.w)((e=>(0,Ye.of)(o(e))))))})),yr(this,"prepareLogRowContextQueryTarget",((e,t,r)=>{const a=this.languageProvider.getLabelKeys(),n=Object.keys(e.labels).map((t=>a.includes(t)?`${t}="${e.labels[t].replace(/\\/g,"\\\\")}"`:"")).filter((e=>!!e)).join(","),s=72e5,o="FORWARD"===r?de.sb.Forward:de.sb.Backward,l={expr:`{${n}}`,queryType:de.EM.Range,refId:"",maxLines:t,direction:o},c=new i.FieldCache(e.dataFrame).getFirstFieldOfType(i.FieldType.time);if(void 0===c)throw new Error("loki: dataframe missing time-field, should never happen");const u=c.values.get(e.rowIndex),d=(0,i.toUtc)(u),O=o===de.sb.Forward?{from:d,to:(0,i.toUtc)(e.timeEpochMs+s)}:{from:(0,i.toUtc)(e.timeEpochMs-s),to:d};return{query:l,range:{from:O.from,to:O.to,raw:O}}})),this.instanceSettings=e,this.templateSrv=s,this.timeSrv=o,this.languageProvider=new kt(this);const l=e.jsonData||{};this.maxLines=parseInt(null!==(r=l.maxLines)&&void 0!==r?r:"0",10)||1e3;const c=(null!==(a=l.keepCookies)&&void 0!==a?a:[]).length>0;this.useBackendMode=!c&&null!==(n=v.config.featureToggles.lokiBackendMode)&&void 0!==n&&n}_request(e,t,r){const a=this.instanceSettings.url,n=t?(0,Je.tW)(t):"",s=`${a}${e}${n.length?`?${n}`:""}`;(this.instanceSettings.withCredentials||this.instanceSettings.basicAuth)&&(r=Object.assign({},r,{withCredentials:!0}),this.instanceSettings.basicAuth&&(r.headers=Object.assign({},r.headers,{Authorization:this.instanceSettings.basicAuth})));const i=Object.assign({},r,{url:s});return(0,v.getBackendSrv)().fetch(i)}getLogsVolumeDataProvider(e){const t=e=>{const t=gt(e),{expr:r}=t;return r&&!Lr(r)&&t.queryType===de.EM.Range};if(!e.targets.some(t))return;const r=(0,f.cloneDeep)(e);return r.targets=r.targets.filter(t).map((e=>Object.assign({},e,{instant:!1,volumeQuery:!0,expr:`sum by (level) (count_over_time(${e.expr}[$__interval]))`}))),(0,ze.Bz)(this,r,{extractLevel:wr,range:e.range,targets:e.targets})}query(e){const t=[],r=Object.assign({},e.scopedVars,this.getRangeScopedVars(e.range));if(this.useBackendMode){var a;const t=e.targets.map(gt).map((e=>Object.assign({},e,{maxLines:e.maxLines||this.maxLines}))),r=Object.assign({},e,{targets:t}),n=r.targets.filter((e=>e.queryType===de.EM.Stream));if(v.config.featureToggles.lokiLive&&n.length>0&&"now"===(null===(a=r.rangeRaw)||void 0===a?void 0:a.to)){const e=Object.assign({},r,{targets:n});return(0,Ae.T)(...n.map((t=>hr(t,this,e))))}return r.liveStreaming?this.runLiveQueryThroughBackend(r):super.query(r).pipe((0,Ge.U)((e=>{var t;return function(e,t,r){const{data:a,error:n}=e,s=vt(e,yt),o=a.map((e=>{if(!(0,i.isDataFrame)(e))throw new Error("transformation only supports dataframe responses");return e})),l=new Map(t.map((e=>[e.refId,e]))),{streamsFrames:c,metricInstantFrames:u,metricRangeFrames:d}=_t(o,l);return Object.assign({},s,{error:Rt(n,l),data:[...Pt(d),...(O=u,O.length>0?lt(O):[]),...Qt(c,l,r)]});var O}(e,r.targets,null!==(t=this.instanceSettings.jsonData.derivedFields)&&void 0!==t?t:[])})))}const n=e.targets.filter((e=>e.expr&&!e.hide)).map((e=>{const t=this.addAdHocFilters(e.expr);return Object.assign({},e,{expr:this.templateSrv.replace(t,r,this.interpolateQueryExpr)})}));for(const r of n){var s;r.instant||r.queryType===de.EM.Instant?t.push(this.runInstantQuery(r,e,n.length)):v.config.featureToggles.lokiLive&&r.queryType===de.EM.Stream&&"now"===(null===(s=e.rangeRaw)||void 0===s?void 0:s.to)?t.push(hr(r,this,e)):t.push(this.runRangeQuery(r,e))}return(0,f.isEmpty)(t)?(0,Ye.of)({data:[],state:i.LoadingState.Done}):(0,Ae.T)(...t)}runLiveQueryThroughBackend(e){const t=e.targets.filter((e=>""!==e.expr&&!Lr(e.expr)));if(0===t.length)return(0,Ye.of)({data:[],state:i.LoadingState.Done});const r=t.map((e=>{const t=e.maxLines||this.maxLines;return this.runLiveQuery(e,t)}));return(0,Ae.T)(...r)}createRangeQuery(e,t,r){const a=e.expr;let n={};if(t.range){const r=this.getTime(t.range.from,!1),a=this.getTime(t.range.to,!0),s=Math.ceil((a-r)/1e6),i=e.resolution||Ie.TQ.value,o=this.adjustInterval(t.intervalMs||1e3,i,s)/1e3;n={start:r,end:a,step:Math.ceil(1e3*o)/1e3}}return Object.assign({},xr,n,{query:a,limit:r,direction:e.direction===de.sb.Forward?"FORWARD":"BACKWARD"})}createLiveTarget(e,t){const r=e.expr,a=this.instanceSettings.url,n=(0,Je.tW)({query:r});return{query:r,url:(0,Ke.F3)(`${a}/loki/api/v1/tail?${n}`),refId:e.refId,size:t}}getRangeScopedVars(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.timeSrv.timeRange();const t=e.to.diff(e.from),r=Math.round(t/1e3);return{__range_ms:{text:t,value:t},__range_s:{text:r,value:r},__range:{text:r+"s",value:r+"s"}}}interpolateVariablesInQueries(e,t){let r=e;return e&&e.length&&(r=e.map((e=>Object.assign({},e,{datasource:this.getRef(),expr:this.templateSrv.replace(e.expr,t,this.interpolateQueryExpr)})))),r}getQueryDisplayText(e){return e.expr}getTimeRangeParams(){const e=this.timeSrv.timeRange();return{start:e.from.valueOf()*vr,end:e.to.valueOf()*vr}}async importFromAbstractQueries(e){await this.languageProvider.start();const t=this.languageProvider.labelKeys;return t&&t.length&&(e=e.map((e=>(e.labelMatchers=e.labelMatchers.filter((e=>t.includes(e.name))),e)))),e.map((e=>this.languageProvider.importFromAbstractQuery(e)))}async exportToAbstractQueries(e){return e.map((e=>this.languageProvider.exportToAbstractQuery(e)))}async metadataRequest(e,t){if(e.startsWith("/"))throw new Error(`invalid metadata request url: ${e}`);if(this.useBackendMode){return(await this.getResource(e,t)).data||[]}{const r=`/loki/api/v1/${e}`;return(await(0,Me.n)(this._request(r,t,{hideFromInspector:!0}))).data.data||[]}}async metricFindQuery(e){if(!e)return Promise.resolve([]);const t=this.templateSrv.replace(e,{},this.interpolateQueryExpr);return await this.processMetricFindQuery(t)}async processMetricFindQuery(e){if(e.match(/^label_names\(\)\s*$/))return await this.labelNamesQuery();const t=e.match(/^label_values\((?:(.+),\s*)?([a-zA-Z_][a-zA-Z0-9_]*)\)\s*$/);return t?t[1]?await this.labelValuesSeriesQuery(t[1],t[2]):await this.labelValuesQuery(t[2]):Promise.resolve([])}async labelNamesQuery(){const e=this.getTimeRangeParams();return(await this.metadataRequest("labels",e)).map((e=>({text:e})))}async labelValuesQuery(e){const t=this.getTimeRangeParams(),r=`label/${e}/values`;return(await this.metadataRequest(r,t)).map((e=>({text:e})))}async labelValuesSeriesQuery(e,t){const r=this.getTimeRangeParams(),a=Object.assign({},r,{"match[]":e}),n=new Set;return(await this.metadataRequest("series",a)).forEach((e=>{e[t]&&n.add({text:e[t]})})),Array.from(n)}async getTagKeys(){return await this.labelNamesQuery()}async getTagValues(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return await this.labelValuesQuery(e.key)}interpolateQueryExpr(e,t){if(!t.multi&&!t.includeAll)return _r(e);if("string"==typeof e)return Rr(e);return(0,f.map)(e,Rr).join("|")}modifyQuery(e,t){var r;let a=null!==(r=e.expr)&&void 0!==r?r:"";switch(t.type){case"ADD_FILTER":a=this.addLabelToQuery(a,t.key,t.value,"=");break;case"ADD_FILTER_OUT":a=this.addLabelToQuery(a,t.key,t.value,"!=")}return Object.assign({},e,{expr:a})}getTime(e,t){return"string"==typeof e&&(e=i.dateMath.parse(e,t)),Math.ceil(1e6*e.valueOf())}testDatasource(){const e=Date.now(),t={start:(e-6e5)*vr,end:e*vr};return this.metadataRequest("labels",t).then((e=>e.length>0?{status:"success",message:"Data source connected and labels found."}:{status:"error",message:"Data source connected, but no labels received. Verify that Loki and Promtail is configured properly."}),(e=>{var t,r;const a=null!==(t=null==e||null===(r=e.data)||void 0===r?void 0:r.message)&&void 0!==t?t:"";return{status:"error",message:`Unable to fetch labels from Loki${""!==a?` (${a})`:""}, please check the server logs for more details`}}))}async annotationQuery(e){const{expr:t,maxLines:r,instant:a,tagKeys:n="",titleFormat:s="",textFormat:o=""}=e.annotation;if(!t)return[];const l=`annotation-${e.annotation.name}`,c=Qr({refId:l,expr:t,maxLines:r,instant:a,queryType:a?de.EM.Instant:de.EM.Range},e.range,i.CoreApp.Dashboard,l),{data:u}=await(0,Me.n)(this.query(c)),d=[],O=n.split(",").filter((e=>""!==e));for(const e of u){new i.DataFrameView(e).forEach((e=>{const{labels:t}=e,r=Object.entries(t).map((e=>{let[t,r]=e;return[t,r.trim()]})).filter((e=>{let[t,r]=e;return""!==r&&!(O.length&&!O.includes(t))})).map((e=>{let[t,r]=e;return r})),a=Array.from(new Set(r));d.push({time:new Date(e.Time).valueOf(),title:(0,et.W)(s,t),text:(0,et.W)(o,t)||e.Line,tags:a})}))}return d}showContextToggle(e){return!0===(e&&e.searchWords&&e.searchWords.length>0)}processError(e,t){let r=(0,f.cloneDeep)(e);return r.refId=t.refId,r.data&&e.data.message.includes("escape")&&t.expr.includes("\\")&&(r.data.message=`Error: ${e.data.message}. Make sure that all special characters are escaped with \\. For more information on escaping of special characters visit LogQL documentation at https://grafana.com/docs/loki/latest/logql/.`),r}adjustInterval(e,t,r){let a=r/11e3;return a>1&&(a=Math.ceil(a)),Math.max(t*e,a)}addAdHocFilters(e){let t=e;return t=this.templateSrv.getAdhocFilters(this.name).reduce(((e,t)=>{const{key:r,operator:a}=t;let{value:n}=t;return this.addLabelToQuery(e,r,n,a,!0)}),t),t}addLabelToQuery(e,t,r,a,n){let s=(0,xe.Hk)(r.toString(),a);return!function(e){const t=k.uR.map((e=>`${e.label}`)).join("|");return new RegExp(`\\|\\s?(${t})`).test(e)}(e)||Lr(e)||n?nt(e,t,s,a,!0):function(e,t,r,a){return e+` | ${t}${a}"${r.toString()}"`}(e,t,s,a)}filterQuery(e){return!e.hide&&""!==e.expr}applyTemplateVariables(e,t){const r=function(e,t){if(null==e)return{};var r,a,n={},s=Object.keys(e);for(a=0;a<s.length;a++)r=s[a],t.indexOf(r)>=0||(n[r]=e[r]);return n}(t,fr),a=this.addAdHocFilters(e.expr);return Object.assign({},e,{legendFormat:this.templateSrv.replace(e.legendFormat,r),expr:this.templateSrv.replace(a,r,this.interpolateQueryExpr)})}interpolateString(e){return this.templateSrv.replace(e,void 0,this.interpolateQueryExpr)}getVariables(){return this.templateSrv.getVariables().map((e=>`$${e.name}`))}}function _r(e){return"string"==typeof e?e.replace(/'/g,"\\\\'"):e}function Rr(e){return"string"==typeof e?_r(e.replace(/\\/g,"\\\\\\\\").replace(/[$^*{}\[\]+?.()|]/g,"\\\\$&")):e}function Lr(e){if(!e)return!1;return Ve().tokenize(e,k.ZP).some((e=>"string"!=typeof e&&"function"===e.type))}function wr(e){var t;let r;try{r=new i.FieldCache(e).getFirstFieldOfType(i.FieldType.number)}catch{}return null!==(t=r)&&void 0!==t&&t.labels?function(e){const t=["level","lvl","loglevel"];let r;for(let a of t)if(a in e){r=a;break}return r?(0,i.getLogLevelFromKey)(e[r]):i.LogLevel.unknown}(r.labels):i.LogLevel.unknown}const qr=y.memo((e=>{var t,r,a;let{app:n,query:s,onChange:i,onRunQuery:o}=e;let l=null!==(t=s.queryType)&&void 0!==t?t:s.instant?de.EM.Instant:de.EM.Range,c=!Lr(s.expr);return(0,b.jsx)(L.EditorRow,{children:(0,b.jsxs)(Ue.d,{title:"Options",collapsedInfo:jr(s,l,c),children:[(0,b.jsx)(L.EditorField,{label:"Legend",tooltip:"Series name override or template. Ex. {{hostname}} will be replaced with label value for hostname.",children:(0,b.jsx)(Pe.H,{placeholder:"{{label}}",id:"loki-query-editor-legend-format",type:"string",minWidth:14,defaultValue:s.legendFormat,onCommitChange:e=>{i(Object.assign({},s,{legendFormat:e.currentTarget.value})),o()}})}),(0,b.jsx)(L.EditorField,{label:"Type",children:(0,b.jsx)(w.RadioButtonGroup,{options:Ie.uG,value:l,onChange:e=>{i(Object.assign({},s,{queryType:e})),o()}})}),c&&(0,b.jsx)(L.EditorField,{label:"Line limit",tooltip:"Upper limit for number of log lines returned by query.",children:(0,b.jsx)(Pe.H,{className:"width-4",placeholder:"auto",type:"number",min:0,defaultValue:null!==(r=null===(a=s.maxLines)||void 0===a?void 0:a.toString())&&void 0!==r?r:"",onCommitChange:function(e){const t=(0,Ie.Wz)(e.currentTarget.value);s.maxLines!==t&&(i(Object.assign({},s,{maxLines:t})),o())}})}),(0,b.jsx)(L.EditorField,{label:"Resolution",children:(0,b.jsx)(w.Select,{isSearchable:!1,onChange:e=>{(0,v.reportInteraction)("grafana_loki_resolution_clicked",{app:n,resolution:e.value}),i(Object.assign({},s,{resolution:e.value})),o()},options:Ie.oZ,value:s.resolution||1,"aria-label":"Select resolution"})})]})})}));function jr(e,t,r){const a=Ie.uG.find((e=>e.value===t)),n=Ie.oZ.find((t=>{var r;return t.value===(null!==(r=e.resolution)&&void 0!==r?r:1)})),s=[];return e.legendFormat&&s.push(`Legend: ${e.legendFormat}`),e.resolution&&s.push(`Resolution: ${null==n?void 0:n.label}`),s.push(`Type: ${null==a?void 0:a.label}`),r&&e.maxLines&&s.push(`Line limit: ${e.maxLines}`),s}qr.displayName="LokiQueryBuilderOptions";var $r,Tr=r(11410);function Fr(e){var t;const{query:r,data:a,datasource:n,onChange:s,onRunQuery:i,range:o}=e,l=(0,b.jsx)("div",{className:"gf-form-inline",children:(0,b.jsxs)("div",{className:"gf-form",children:[$r||($r=(0,b.jsx)(w.InlineFormLabel,{width:6,tooltip:"Controls the name of the time series, using name or pattern. For example {{hostname}} will be replaced with label value for the label hostname. The legend only applies to metric queries.",children:"Legend"})),(0,b.jsx)("input",{type:"text",className:"gf-form-input",placeholder:"legend format",value:r.legendFormat||"",onChange:e=>{const t=Object.assign({},r,{legendFormat:e.currentTarget.value});s(t)},onBlur:i})]})});return(0,b.jsx)(Tr.n,{datasource:n,query:r,onChange:s,onRunQuery:i,onBlur:i,history:[],data:a,"data-testid":Sr.editor,range:o,ExtraFieldElement:(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)(Ie.JX,{lineLimitValue:(null==r||null===(t=r.maxLines)||void 0===t?void 0:t.toString())||"",resolution:(null==r?void 0:r.resolution)||1,query:r,onRunQuery:i,onChange:s,runOnBlur:!0}),l]})})}const Sr={editor:"loki-editor"};function kr(e){let{query:t,datasource:r,range:a,onRunQuery:n,onChange:s,data:o,app:l}=e;const c=(0,w.useStyles2)(Er),u=l===i.CoreApp.Explore?()=>{}:void 0;return(0,b.jsx)("div",{className:c.wrapper,children:(0,b.jsx)(Tr.n,{datasource:r,query:t,range:a,onRunQuery:n,onChange:s,onBlur:u,history:[],data:o,"data-testid":Sr.editor,app:l})})}const Er=e=>({wrapper:Qe.css`
  6. .gf-form {
  7. margin-bottom: 0;
  8. }
  9. `});var Cr,Xr,Ur;const Ir=y.memo((e=>{const{onChange:t,onRunQuery:r,data:a,app:n}=e,[s,o]=(0,y.useState)(!1),[l,c]=(0,y.useState)(!1),u=function(e){let t=e;return e.editorMode||(t=Object.assign({},e,{editorMode:pe(e.expr)})),null==e.expr&&(t=Object.assign({},t,{expr:""})),null==e.queryType&&(t=Object.assign({},t,{queryType:de.EM.Range})),t}(e.query),[d,O]=ge(),p=u.editorMode,m=(0,y.useCallback)((e=>{var r;if((0,v.reportInteraction)("grafana_loki_editor_mode_clicked",{newEditor:e,previousEditor:null!==(r=u.editorMode)&&void 0!==r?r:"",newQuery:!u.expr,app:null!=n?n:""}),e===T.c.Builder){if(ne(u.expr||"").errors.length)return void o(!0)}!function(e,t,r){""===e.expr&&ue.Z.set(Oe,t),r(Object.assign({},e,{editorMode:t}))}(u,e,t)}),[t,u,n]);(0,y.useEffect)((()=>{c(!1)}),[a]);const g=e=>{c(!0),t(e)};return(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)(w.ConfirmModal,{isOpen:s,title:"Query parsing",body:"There were errors while trying to parse the query. Continuing to visual builder may loose some parts of the query.",confirmText:"Continue",onConfirm:()=>{t(Object.assign({},u,{editorMode:T.c.Builder})),o(!1)},onDismiss:()=>o(!1)}),(0,b.jsxs)(L.EditorHeader,{children:[(0,b.jsx)(L.InlineSelect,{value:null,placeholder:"Query patterns",allowCustomValue:!0,onChange:e=>{let{value:r}=e;const a=ne(u.expr||"");a.query.operations=null==r?void 0:r.operations,t(Object.assign({},u,{expr:Z.renderQuery(a.query)}))},options:Z.getQueryPatterns().map((e=>({label:e.name,value:e})))}),p===T.c.Builder&&(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)($.n,{label:"Raw query",value:d,onChange:e=>{const t=e.currentTarget.checked;O(t)}}),Cr||(Cr=(0,b.jsx)(q.R,{feedbackUrl:"https://github.com/grafana/grafana/discussions/50785"}))]}),Xr||(Xr=(0,b.jsx)(L.FlexItem,{grow:1})),n!==i.CoreApp.Explore&&(0,b.jsx)(w.Button,{variant:l?"primary":"secondary",size:"sm",onClick:r,icon:(null==a?void 0:a.state)===i.LoadingState.Loading?"fa fa-spinner":void 0,disabled:(null==a?void 0:a.state)===i.LoadingState.Loading,children:"Run queries"}),(0,b.jsx)(j.k,{mode:p,onChange:m})]}),Ur||(Ur=(0,b.jsx)(L.Space,{v:.5})),(0,b.jsxs)(L.EditorRows,{children:[p===T.c.Code&&(0,b.jsx)(kr,Object.assign({},e,{onChange:g})),p===T.c.Builder&&(0,b.jsx)(Te,{datasource:e.datasource,query:u,onChange:g,onRunQuery:e.onRunQuery,showRawQuery:d}),p===T.c.Explain&&(0,b.jsx)(Xe,{query:u.expr}),p!==T.c.Explain&&(0,b.jsx)(qr,{query:u,onChange:t,onRunQuery:r,app:n})]})]})}));Ir.displayName="LokiQueryEditorSelector";const Nr=(0,y.memo)((e=>{var t;const{query:r,data:a,datasource:n,history:s,onChange:i,onRunQuery:o,range:l}=e;return(0,b.jsx)(Tr.n,{datasource:n,query:r,onChange:i,onBlur:()=>{},onRunQuery:o,history:s,data:a,range:l,"data-testid":Vr.editor,ExtraFieldElement:(0,b.jsx)(Ie.JX,{lineLimitValue:(null==r||null===(t=r.maxLines)||void 0===t?void 0:t.toString())||"",resolution:r.resolution||1,query:r,onRunQuery:o,onChange:i})})}));Nr.displayName="LokiExploreQueryEditor";const Vr={editor:"loki-editor-explore"};function Dr(e){const{query:t,data:r,datasource:a,onChange:n,onRunQuery:s}=e;return(0,b.jsx)(Tr.n,{datasource:a,query:t,onChange:n,onRunQuery:s,onBlur:s,history:[],data:r,placeholder:"Enter a Loki query","data-testid":Mr.editor})}const Mr={editor:"loki-editor-cloud-alerting"};function Yr(e){const{app:t}=e;switch(t){case i.CoreApp.CloudAlerting:return(0,b.jsx)(Dr,Object.assign({},e));case i.CoreApp.Explore:return v.config.featureToggles.lokiQueryBuilder?(0,b.jsx)(Ir,Object.assign({},e)):(0,b.jsx)(Nr,Object.assign({},e));default:return v.config.featureToggles.lokiQueryBuilder?(0,b.jsx)(Ir,Object.assign({},e)):(0,b.jsx)(Fr,Object.assign({},e))}}const Ar=(0,y.memo)(Yr);var Gr,Br=r(82139),Wr=r(23019),zr=r.n(Wr),Kr=r(67892);const{FormField:Zr}=w.LegacyForms,Hr=e=>{const{derivedFields:t,className:r}=e,[a,n]=(0,y.useState)("");let s=[];return a&&t&&(s=function(e,t){return e.filter((e=>e.name&&e.matcherRegex)).map((e=>{try{const r=t.match(e.matcherRegex),a=r&&r[1];let n=null;return e.url&&a&&(n=(0,Kr.a)({field:{name:"",type:i.FieldType.string,values:new i.ArrayVector([a]),config:{links:[{title:"",url:e.url}]}},rowIndex:0,range:{}})[0]),{name:e.name,value:a||"<no match>",href:n&&n.href}}catch(t){return{name:e.name,error:t}}}))}(t,a)),(0,b.jsxs)("div",{className:r,children:[(0,b.jsx)(Zr,{labelWidth:12,label:"Debug log message",inputEl:(0,b.jsx)("textarea",{placeholder:"Paste an example log line here to test the regular expressions of your derived fields",className:zr()("gf-form-input gf-form-textarea",Qe.css`
  10. width: 100%;
  11. `),value:a,onChange:e=>n(e.currentTarget.value)})}),!!s.length&&(0,b.jsx)(Jr,{fields:s})]})},Jr=e=>{let{fields:t}=e;return(0,b.jsxs)("table",{className:"filter-table",children:[Gr||(Gr=(0,b.jsx)("thead",{children:(0,b.jsxs)("tr",{children:[(0,b.jsx)("th",{children:"Name"}),(0,b.jsx)("th",{children:"Value"}),(0,b.jsx)("th",{children:"Url"})]})})),(0,b.jsx)("tbody",{children:t.map((e=>{let t=e.value;return e.error?t=e.error.message:e.href&&(t=(0,b.jsx)("a",{href:e.href,children:t})),(0,b.jsxs)("tr",{children:[(0,b.jsx)("td",{children:e.name}),(0,b.jsx)("td",{children:t}),(0,b.jsx)("td",{children:e.href?(0,b.jsx)("a",{href:e.href,children:e.href}):""})]},`${e.name}=${e.value}`)}))})]})};var ea=r(20002);const{Switch:ta,FormField:ra}=w.LegacyForms,aa=(0,w.stylesFactory)((()=>({row:Qe.css`
  12. display: flex;
  13. align-items: baseline;
  14. `,nameField:Qe.css`
  15. flex: 2;
  16. `,regexField:Qe.css`
  17. flex: 3;
  18. `,urlField:Qe.css`
  19. flex: 1;
  20. `,urlDisplayLabelField:Qe.css`
  21. flex: 1;
  22. `}))),na=e=>{const{value:t,onChange:r,onDelete:a,suggestions:n,className:s}=e,i=aa(),[o,l]=(0,y.useState)(!!t.datasourceUid),c=(0,ea.Z)(t.datasourceUid);(0,y.useEffect)((()=>{c||!t.datasourceUid||o||l(!0),c&&!t.datasourceUid&&o&&l(!1)}),[c,t.datasourceUid,o]);const u=e=>a=>{r(Object.assign({},t,{[e]:a.currentTarget.value}))};return(0,b.jsxs)("div",{className:s,children:[(0,b.jsxs)("div",{className:i.row,children:[(0,b.jsx)(ra,{className:i.nameField,labelWidth:5,inputWidth:null,label:"Name",type:"text",value:t.name,onChange:u("name")}),(0,b.jsx)(ra,{className:i.regexField,inputWidth:null,label:"Regex",type:"text",value:t.matcherRegex,onChange:u("matcherRegex"),tooltip:"Use to parse and capture some part of the log message. You can use the captured groups in the template."}),(0,b.jsx)(w.Button,{variant:"destructive",title:"Remove field",icon:"times",onClick:e=>{e.preventDefault(),a()},className:Qe.css`
  23. margin-left: 8px;
  24. `})]}),(0,b.jsxs)("div",{className:i.row,children:[(0,b.jsx)(ra,{label:o?"Query":"URL",inputEl:(0,b.jsx)(w.DataLinkInput,{placeholder:o?"${__value.raw}":"http://example.com/${__value.raw}",value:t.url||"",onChange:e=>r(Object.assign({},t,{url:e})),suggestions:n}),className:i.urlField}),(0,b.jsx)(ra,{className:i.urlDisplayLabelField,inputWidth:null,label:"URL Label",type:"text",value:t.urlDisplayLabel,onChange:u("urlDisplayLabel"),tooltip:"Use to override the button label when this derived field is found in a log."})]}),(0,b.jsxs)("div",{className:i.row,children:[(0,b.jsx)(ta,{label:"Internal link",checked:o,onChange:()=>{o&&r(Object.assign({},t,{datasourceUid:void 0})),l(!o)}}),o&&(0,b.jsx)(v.DataSourcePicker,{tracing:!0,onChange:e=>r(Object.assign({},t,{datasourceUid:e.uid})),current:t.datasourceUid})]})]})};var sa;const ia=e=>{const{value:t,onChange:r}=e,a=(e=>({infoText:Qe.css`
  25. padding-bottom: ${e.spacing(2)};
  26. color: ${e.colors.text.secondary};
  27. `,derivedField:Qe.css`
  28. margin-bottom: ${e.spacing(1)};
  29. `}))((0,w.useTheme2)()),[n,s]=(0,y.useState)(!1);return(0,b.jsxs)(b.Fragment,{children:[sa||(sa=(0,b.jsx)("h3",{className:"page-heading",children:"Derived fields"})),(0,b.jsx)("div",{className:a.infoText,children:"Derived fields can be used to extract new fields from a log message and create a link from its value."}),(0,b.jsxs)("div",{className:"gf-form-group",children:[t&&t.map(((e,n)=>(0,b.jsx)(na,{className:a.derivedField,value:e,onChange:e=>{const a=[...t];a.splice(n,1,e),r(a)},onDelete:()=>{const e=[...t];e.splice(n,1),r(e)},suggestions:[{value:i.DataLinkBuiltInVars.valueRaw,label:"Raw value",documentation:"Exact string captured by the regular expression",origin:i.VariableOrigin.Value}]},n))),(0,b.jsxs)("div",{children:[(0,b.jsx)(w.Button,{variant:"secondary",className:Qe.css`
  30. margin-right: 10px;
  31. `,icon:"plus",onClick:e=>{e.preventDefault();const a=[...t||[],{name:"",matcherRegex:""}];r(a)},children:"Add"}),t&&t.length>0&&(0,b.jsx)(w.Button,{variant:"secondary",type:"button",onClick:()=>s(!n),children:n?"Hide example log message":"Show example log message"})]})]}),n&&(0,b.jsx)("div",{className:"gf-form-group",children:(0,b.jsx)(Hr,{className:Qe.css`
  32. margin-bottom: 10px;
  33. `,derivedFields:t})})]})},{FormField:oa}=w.LegacyForms,la=e=>{const{value:t,onChange:r}=e;return(0,b.jsx)(oa,{label:"Maximum lines",labelWidth:11,inputWidth:20,inputEl:(0,b.jsx)("input",{type:"number",className:"gf-form-input width-8 gf-form-input--has-help-icon",value:t,onChange:e=>r(e.currentTarget.value),spellCheck:!1,placeholder:"1000"}),tooltip:(0,b.jsx)(b.Fragment,{children:"Loki queries must contain a limit of the maximum number of lines returned (default: 1000). Increase this limit to have a bigger result set for ad-hoc analysis. Decrease this limit if your browser becomes sluggish when displaying the log results."})})},ca=e=>(t,r)=>Object.assign({},t,{jsonData:Object.assign({},t.jsonData,{[e]:r})}),ua=ca("maxLines"),da=ca("derivedFields"),Oa=new i.DataSourcePlugin(Pr).setQueryEditor(Ar).setConfigEditor((e=>{const{options:t,onOptionsChange:r}=e,a=(0,Br.Tc)();return(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)(w.DataSourceHttpSettings,{defaultUrl:"http://localhost:3100",dataSourceConfig:t,showAccessOptions:!1,onChange:r}),(0,b.jsx)(w.AlertingSettings,{alertmanagerDataSources:a,options:t,onOptionsChange:r}),(0,b.jsx)("div",{className:"gf-form-group",children:(0,b.jsx)("div",{className:"gf-form-inline",children:(0,b.jsx)("div",{className:"gf-form",children:(0,b.jsx)(la,{value:t.jsonData.maxLines||"",onChange:e=>r(ua(t,e))})})})}),(0,b.jsx)(ia,{value:t.jsonData.derivedFields,onChange:e=>r(da(t,e))})]})})).setQueryEditorHelp(R).setAnnotationQueryCtrl(o)},91871:(e,t,r)=>{let a,n,s;r.d(t,{EM:()=>n,ox:()=>a,sb:()=>s}),function(e){e.Stream="streams",e.Vector="vector",e.Matrix="matrix"}(a||(a={})),function(e){e.Range="range",e.Instant="instant",e.Stream="stream"}(n||(n={})),function(e){e.Backward="backward",e.Forward="forward"}(s||(s={}))}}]);
  34. //# sourceMappingURL=lokiPlugin.634a81c278b8a1b3e5b2.js.map