Files
HX_KI_com-Com1/grafana/plugins/grafana-pyroscope-app/72.js
2026-03-06 14:37:04 +00:00

777 lines
314 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use strict";(self.webpackChunkgrafana_pyroscope_app=self.webpackChunkgrafana_pyroscope_app||[]).push([[72],{4137:(e,t,n)=>{n.d(t,{$0:()=>i,Gy:()=>o,R2:()=>r,bw:()=>a});const r=n(2533).id,o=`/a/${r}`,i=`/api/plugin-proxy/${r}`;var a=function(e){return e.EXPLORE="/explore",e.ADHOC="/ad-hoc",e.SETTINGS="/settings",e.RECORDING_RULES="/recording-rules",e.GITHUB_CALLBACK="/github/callback",e}({})},9897:(e,t,n)=>{n.d(t,{N:()=>r});var r=function(e){return e.BASELINE="baseline",e.COMPARISON="comparison",e}({})},9838:(e,t,n)=>{n.d(t,{O:()=>ou,a:()=>iu});var r=n(6089),o=n(9869),i=n(2007),a=n(2673);function s(){history.pushState(null,"")}var l,c,u,d=n(7907),p=n(5959),m=n.n(p),f=n(7781),h=n(897),g=n(3241);class b extends f.BusEventWithPayload{}u="timeseries-data-received",(c="type")in(l=b)?Object.defineProperty(l,c,{value:u,enumerable:!0,configurable:!0,writable:!0}):l[c]=u;var y=function(e){return e.partial="partial",e["attribute-operator-value"]="attribute-operator-value",e["attribute-operator"]="attribute-operator",e}({}),v=function(e){return e["="]="=",e["!="]="!=",e.in="in",e["not-in"]="not-in",e["is-empty"]="is-empty",e["=~"]="=~",e["!~"]="!~",e}({}),E=function(e){return e.attribute="attribute",e.operator="operator",e.value="value",e}({}),S=function(e){return e.attribute="attribute",e.operator="operator",e.value="value",e}({});var w=n(1015),O=n(7268),x=n(8987),P=n(9221),C=n(8531),T=n(9090);class A extends T.Q{constructor(e){var t;const{dataSourceUid:n}=e;let{appSubUrl:r="",bootData:o}=C.config;"/"!==(null==r?void 0:r.at(-1))&&(r+="/"),super(`${r}api/datasources/proxy/uid/${n}`,{"content-type":"application/json","X-Grafana-Org-Id":String((null==o||null===(t=o.user)||void 0===t?void 0:t.orgId)||"")}),function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(this,"dataSourceUid",void 0),this.dataSourceUid=e.dataSourceUid}}function j(e,t,n,r,o,i,a){try{var s=e[i](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function k(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var i=e.apply(t,n);function a(e){j(i,r,o,a,s,"next",e)}function s(e){j(i,r,o,a,s,"throw",e)}a(void 0)}))}}class N extends A{static queryToMatchers(e){const t=e.indexOf("{");if(t>0){return[`{__profile_type__="${e.substring(0,t)}", ${e.substring(t+1,e.length)}`]}return 0===t?[e]:[`{__profile_type__="${e}"}`]}fetchLabels(e,t,n){var r=this;return k((function*(){return r._post("/querier.v1.QuerierService/LabelNames",{matchers:N.queryToMatchers(e),start:t,end:n}).then((e=>e.json()))}))()}fetchLabelValues(e,t,n,r){var o=this;return k((function*(){return o._post("/querier.v1.QuerierService/LabelValues",{name:e,matchers:N.queryToMatchers(t),start:n,end:r}).then((e=>e.json()))}))()}_post(e,t){return super.fetch(e,{method:"POST",body:JSON.stringify(t)})}constructor(e){super(e)}}class R{static buildCacheKey(e){let t="";for(const n of e)t+=String(n);return t}get(e){return this.store.get(R.buildCacheKey(e))}set(e,t){this.store.set(R.buildCacheKey(e),t)}delete(e){this.store.delete(R.buildCacheKey(e))}constructor(){!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(this,"store",new Map)}}function I(e,t){if(!e)throw new Error(t)}function _(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class D{setApiClient(e){this.apiClient=e}setCacheClient(e){this.cacheClient=e}cancel(e){this.apiClient.abort(e)}constructor(e){_(this,"apiClient",void 0),_(this,"cacheClient",void 0),this.apiClient=e.apiClient,this.cacheClient=null==e?void 0:e.cacheClient}}var L=n(5656);function F(e,t,n,r,o,i,a){try{var s=e[i](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function B(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var i=e.apply(t,n);function a(e){F(i,r,o,a,s,"next",e)}function s(e){F(i,r,o,a,s,"throw",e)}a(void 0)}))}}class $ extends L.O{static queryToMatchers(e){const t=e.indexOf("{");if(t>0){return[`{__profile_type__="${e.substring(0,t)}", ${e.substring(t+1,e.length)}`]}return 0===t?[e]:[`{__profile_type__="${e}"}`]}fetchLabels(e,t,n){var r=this;return B((function*(){return r._post("/querier.v1.QuerierService/LabelNames",{matchers:$.queryToMatchers(e),start:t,end:n}).then((e=>e.json()))}))()}fetchLabelValues(e,t,n,r){var o=this;return B((function*(){return o._post("/querier.v1.QuerierService/LabelValues",{name:e,matchers:$.queryToMatchers(t),start:n,end:r}).then((e=>e.json()))}))()}_post(e,t){return super.fetch(e,{method:"POST",body:JSON.stringify(t)})}}function M(e,t,n,r,o,i,a){try{var s=e[i](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function V(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var i=e.apply(t,n);function a(e){M(i,r,o,a,s,"next",e)}function s(e){M(i,r,o,a,s,"throw",e)}a(void 0)}))}}function U(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class G extends D{static parseLabelsResponse(e){if(!Array.isArray(e.names))return[];return Array.from(new Set(e.names.filter(G.isNotMetaLabelOrServiceName))).map((e=>({value:e,label:e})))}static parseLabelValuesResponse(e){if(!Array.isArray(e.names))return[];return e.names.map((e=>({value:e,label:e})))}static assertParams(e,t,n){I(Boolean(e),'Missing "query" parameter!'),I(t>0&&n>0&&n>t,"Invalid timerange!")}listLabels({query:e,from:t,to:n}){var r=this;return V((function*(){G.assertParams(e,t,n);const o=[r.apiClient.baseUrl,e,t,n],i=r.cacheClient.get(o);if(i){const e=yield i,t=G.parseLabelsResponse(e);return t.length||r.cacheClient.delete(o),t}const a=r.apiClient.fetchLabels(e,t,n);r.cacheClient.set(o,a);try{const e=yield a;return G.parseLabelsResponse(e)}catch(e){throw r.cacheClient.delete(o),e}}))()}listLabelValues({label:e,query:t,from:n,to:r}){var o=this;return V((function*(){G.assertParams(t,n,r),I(Boolean(e),"Missing label value!");const i=[o.apiClient.baseUrl,e,t,n,r],a=o.cacheClient.get(i);if(a){const e=yield a,t=G.parseLabelsResponse(e);return t.length||o.cacheClient.delete(i),t}const s=o.apiClient.fetchLabelValues(e,t,n,r);o.cacheClient.set(i,s);try{const e=yield s;return G.parseLabelValuesResponse(e)}catch(e){throw o.cacheClient.delete(i),e}}))()}constructor(e){super({apiClient:e.apiClient}),U(this,"cacheClient",void 0),this.cacheClient=e.cacheClient}}U(G,"isNotMetaLabelOrServiceName",(e=>!/^(__.+__|service_name)$/.test(e)));const q=new G({apiClient:new $,cacheClient:new R});function K(e,t){const n=e.filter((({type:e})=>e!==y.partial)),r=t.filter((({type:e})=>e!==y.partial));return n.length===r.length&&n.every((e=>r.find((({type:t,attribute:n,operator:r,value:o})=>{var i,a;return t===e.type&&n.value===e.attribute.value&&(null==r?void 0:r.value)===(null===(i=e.operator)||void 0===i?void 0:i.value)&&(null==o?void 0:o.value)===(null===(a=e.value)||void 0===a?void 0:a.value)}))))}function z(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const W={type:y["attribute-operator"],operator:{value:v["is-empty"],label:"is empty"},value:{value:v["is-empty"],label:""}},H=e=>function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter((function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable})))),r.forEach((function(t){z(e,t,n[t])}))}return e}({},e,W);function Y(e,t){const n=t.filter((({type:e})=>e!==y.partial)).map((e=>{const{attribute:t,operator:n,value:r}=e;switch(n.value){case v.in:return`${t.value}=~"${r.value}"`;case v["not-in"]:return`${t.value}!~"${r.value}"`;case v["is-empty"]:return`${t.value}=""`;default:return`${t.value}${n.value}"${r.value}"`}}));var r;const[,o]=null!==(r=e.match(/{.*(service_name="[^"]*").*}/))&&void 0!==r?r:[];return o&&n.unshift(o),e.replace(/{(.*)}$/,`{${n.join(",")}}`)}const Z=e=>e.at(-1)||null,X=e=>e===v.in||e===v["not-in"],J=e=>(I(Boolean(e),"The filter is falsy!"),e.type===y.partial);function Q(e,t){return e!==t&&(t!==v["is-empty"]&&([v["=~"],v["!~"],v.in,v["not-in"],v["is-empty"]].includes(e)||[v["=~"],v["!~"],v.in,v["not-in"]].includes(t)))}function ee(e,t){I(void 0!==e.operator,"No operator for the filter under edition!");return Q(e.operator.value,t)}function te(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ne(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))})),e}const re=e=>{const t=e.matchAll(/(\w+)(=|!=|=~|!~)"([^"]*)"/g);return Array.from(t).map((([,e,t,n])=>[e,t,n]))},oe=/.+:[^{]+\{(.+)\}$/,ie=/.*(\^|\$|\*|\+|\{|\}|\?).*/;function ae(e){if(!e)return[];const t=e.match(oe);if(!t)return[];return re(t[1]).filter((([e])=>"service_name"!==e)).map((([e,t,n])=>{const r={id:(0,x.Ak)(10),type:y["attribute-operator-value"],active:!0,attribute:{value:e,label:e},operator:{value:t,label:t},value:{value:n,label:n}};if(t===v["="]&&""===n)return H(r);return[v["=~"],v["!~"]].includes(t)&&!ie.test(n)?ne(function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter((function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable})))),r.forEach((function(t){te(e,t,n[t])}))}return e}({},r),{operator:t===v["=~"]?{value:v.in,label:"in"}:{value:v["not-in"],label:"not in"},value:{value:n,label:n.split("|").map((e=>e.trim())).join(", ")}}):r}))}function se(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function le(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))})),e}const ce=(e,t)=>e.map((e=>e.type!==y.partial?le(function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter((function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable})))),r.forEach((function(t){se(e,t,n[t])}))}return e}({},e),{active:t}):e));function ue(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function de(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter((function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable})))),r.forEach((function(t){ue(e,t,n[t])}))}return e}function pe(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))})),e}function me(e,t){const n=K(e,ae(t.inputParams.query));return{filters:n?ce(e,!0):e,query:Y(t.query,e),isQueryUpToDate:n}}const fe={cancelAllLoad:()=>{q.cancel("Discarded by user")},setFilterAttribute:(0,P.kp)(((e,t)=>{const n=[...e.filters,{id:(0,x.Ak)(10),type:y.partial,active:!1,attribute:t.data}];return pe(de({},e),{filters:n,isQueryUpToDate:K(n,ae(e.inputParams.query))})})),editFilterAttribute:(0,P.kp)(((e,t)=>{if(null===e.edition)throw new Error("Cannot edit filter attribute without edition data!");const{filterId:n}=e.edition,r=e.filters.map((e=>e.id===n?pe(de({},e),{attribute:t.data,operator:void 0,value:void 0}):e));return pe(de({},e),{filters:r,isQueryUpToDate:K(r,ae(e.inputParams.query)),edition:null})})),setFilterOperator:(0,P.kp)(((e,t)=>{const n=e.filters.map((e=>{if(!J(e))return e;const n=t.data;return n.value===v["is-empty"]?H(e):pe(de({},e),{operator:n,value:void 0})}));return de({},e,me(n,e))})),editFilterOperator:(0,P.kp)(((e,t)=>{if(null===e.edition)throw new Error("Cannot edit filter operator without edition data!");const{filterId:n}=e.edition,r=t.data;let o=null;const i=e.filters.map((t=>{const i=t.operator.value;return t.id!==n||i===r.value?t:r.value===v["is-empty"]?H(pe(de({},t),{active:!1})):(i===v["is-empty"]&&(t.value={value:"(no value)",label:"(no value)"}),!J(t)&&Q(i,r.value)&&(o=pe(de({},e.edition),{part:E.value})),pe(de({},t),{operator:r,value:X(i)&&!X(r.value)&&t.value?{value:t.value.value.split("|").shift(),label:t.value.label.split(", ").shift()}:t.value,active:!1}))}));return pe(de({},e,me(i,e)),{edition:o})})),setFilterValue:(0,P.kp)(((e,t)=>{const n=e.filters.map((e=>J(e)?pe(de({},e),{type:y["attribute-operator-value"],active:!1,value:t.data}):e));return de({},e,me(n,e))})),editFilterValue:(0,P.kp)(((e,t)=>{if(null===e.edition)throw new Error("Cannot edit filter value without edition data!");const{filterId:n}=e.edition,r=e.filters.map((e=>e.id===n?pe(de({},e),{type:y["attribute-operator-value"],active:!1,value:t.data}):e));return pe(de({},e,me(r,e)),{edition:null})})),removeFilter:(0,P.kp)(((e,t)=>{const n=t.data,r=ce(e.filters.filter((({id:e})=>e!==n)),!1);return de({},e,me(r,e))})),removeLastFilter:(0,P.kp)((e=>{const{filters:t}=e,n=Z(t);if(!n)return e;if(J(n)&&n.operator){const r=t.slice(0,t.length-1).concat(pe(de({},n),{operator:void 0}));return pe(de({},e),{filters:r,isQueryUpToDate:!0})}const r=t.slice(0,t.length-1).map((e=>pe(de({},e),{active:!1})));return de({},e,me(r,e))})),setEdition:(0,P.kp)({edition:(e,t)=>t.data}),changeInputParams:(0,P.kp)(((e,t)=>(t.data.dataSourceUid&&q.setApiClient(new N({dataSourceUid:t.data.dataSourceUid})),{inputParams:t.data,query:t.data.query,filters:ae(t.data.query),isQueryUpToDate:!0}))),activateFilters:(0,P.kp)((e=>de({},e,me(e.filters,e))))};function he(e){const{edition:t,filters:n}=e;I(null!==t,'"edition" is null!');const r=n.find((({id:e})=>e===t.filterId));return I(void 0!==r,"Cannot find the filter under edition!"),r}const ge={shouldSuggestAttributes:e=>{const t=Z(e.filters);return!t||!J(t)},shouldSuggestOperators:e=>{var t;return!(null===(t=Z(e.filters))||void 0===t?void 0:t.operator)},shouldSuggestValues:e=>{const t=Z(e.filters);return Boolean((null==t?void 0:t.operator)&&!(null==t?void 0:t.value))},isEditing:e=>null!==e.edition,shouldSuggestValuesAfterOperatorEdition:(e,t)=>!!e.edition&&ee(he(e),t.data.value),shouldNotSuggestValuesAfterOperatorEdition:(e,t)=>!!e.edition&&!ee(he(e),t.data.value),hasPartialFilter:e=>{const t=Z(e.filters);return Boolean(t&&J(t))},shouldEditAttribute:(e,t)=>t.data.part===E.attribute,shouldEditOperator:(e,t)=>t.data.part===E.operator,shouldEditValue:(e,t)=>t.data.part===E.value};var be=n(2096);function ye(e,t,n,r,o,i,a){try{var s=e[i](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}const ve=new class{list(){return(e=function*(){return[{value:"=",label:"="},{value:"!=",label:"!="},{value:"is-empty",label:"is empty"},{value:"in",label:"in",description:"Is one of"},{value:"not-in",label:"not in",description:"Is not one of"},{value:"=~",label:"=~",description:"Matches regex"},{value:"!~",label:"!~",description:"Does not match regex"}]},function(){var t=this,n=arguments;return new Promise((function(r,o){var i=e.apply(t,n);function a(e){ye(i,r,o,a,s,"next",e)}function s(e){ye(i,r,o,a,s,"throw",e)}a(void 0)}))})();var e}},Ee=e=>e.startsWith("__");function Se(e,t,n,r,o,i,a){try{var s=e[i](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function we(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var i=e.apply(t,n);function a(e){Se(i,r,o,a,s,"next",e)}function s(e){Se(i,r,o,a,s,"throw",e)}a(void 0)}))}}function Oe(e,t){if(e instanceof DOMException&&"AbortError"===e.name)return[];throw be.v.error(e,{info:t}),e}const xe={fetchLabels:function(){var e=we((function*(e){const{from:t,to:n}=e.inputParams;try{const r=yield q.listLabels({query:e.query,from:t,to:n}),o=[],i=[];return r.forEach((e=>{Ee(e.value)?i.push(e):o.push(e)})),[...o,...i]}catch(e){return Oe(e,"Error while fetching labels!")}}));return function(t){return e.apply(this,arguments)}}(),fetchOperators:we((function*(){try{return yield ve.list()}catch(e){return Oe(e,"Error while fetching operators!")}})),fetchLabelValues:function(){var e=we((function*(e){let t,{query:n,edition:r,suggestions:o}=e;try{if(r){const o=e.filters.filter((e=>e.id!==r.filterId||(t=e,!1)));if(!t)throw new Error(`Impossible to edit filter id="${r.filterId}": no filter found!`);n=Y(n,o)}else if(t=Z(e.filters),(null==t?void 0:t.type)!==y.partial)throw new Error("Impossible to load label values: no partial filter found!");if(o.disabled)return[];const i=t.attribute.value,{from:a,to:s}=e.inputParams;return yield q.listLabelValues({label:i,query:n,from:a,to:s})}catch(e){return Oe(e,"Error while fetching label values!")}}));return function(t){return e.apply(this,arguments)}}()},Pe={always:[{cond:"shouldSuggestOperators",target:"loadOperators"},{cond:"shouldSuggestValues",target:"loadLabelValues"},{target:"idle"}]},Ce={FILTER_ADD:"Filter by label values...",SELECT_LABEL:"Select a label...",SELECT_OPERATOR:"Select an operator...",SELECT_VALUE:"Select a value...",SELECT_VALUES:"Select values...",TYPE_VALUE:"Type a regex...",LOADING:"Loading...",ERROR_LOAD:"An unexpected error occurred while loading! Please try again.",SUGGESTIONS_NONE:"No suggestions available.",SUGGESTIONS_DISABLED:"Suggestions are disabled for this label."},Te=e=>e===v["=~"]||e===v["!~"];function Ae(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function je(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))})),e}const ke={entry:["cancelAllLoad",(0,P.kp)({suggestions:e=>{let t=Ce.FILTER_ADD,n=!1;const r=Z(e.filters);return r&&J(r)&&(r.operator?(n=Te(r.operator.value),t=X(r.operator.value)?Ce.SELECT_VALUES:n?Ce.TYPE_VALUE:Ce.SELECT_VALUE):t=Ce.SELECT_OPERATOR),je(function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter((function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable})))),r.forEach((function(t){Ae(e,t,n[t])}))}return e}({},He.suggestions),{placeholder:t,allowCustomValue:n})},edition:null})],on:{START_INPUT:[{cond:"shouldSuggestAttributes",target:"loadLabels"},{cond:"shouldSuggestOperators",target:"loadOperators"},{cond:"shouldSuggestValues",target:"loadLabelValues"}],EDIT_FILTER:[{cond:"shouldEditAttribute",target:"loadLabels",actions:["setEdition"]},{cond:"shouldEditOperator",target:"loadOperators",actions:["setEdition"]},{cond:"shouldEditValue",target:"loadLabelValues",actions:["setEdition"]}],REMOVE_FILTER:[{cond:"hasPartialFilter",target:"autoSuggestProxy",actions:["removeFilter"]},{target:"idle",actions:["removeFilter"]}],REMOVE_LAST_FILTER:{target:"idle",actions:["removeLastFilter"]},CHANGE_INPUT_PARAMS:{target:"idle",actions:["changeInputParams"]},EXECUTE_QUERY:{target:"idle",actions:["activateFilters"]}}};function Ne(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Re(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter((function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable})))),r.forEach((function(t){Ne(e,t,n[t])}))}return e}function Ie(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))})),e}const _e={entry:(0,P.kp)({suggestions:()=>Ie(Re({},He.suggestions),{isVisible:!0,isLoading:!0})}),invoke:{id:"fetchLabels",src:"fetchLabels",onDone:{target:"displayLabels",actions:(0,P.kp)({suggestions:(e,t)=>Ie(Re({},e.suggestions),{items:t.data.filter((({value:t})=>!e.filters.some((e=>{var n;return(null===(n=e.attribute)||void 0===n?void 0:n.value)===t})))),isLoading:!1})})},onError:{target:"displayLabels",actions:(0,P.kp)({suggestions:(e,t)=>Ie(Re({},e.suggestions),{isLoading:!1,error:t.data})})}},on:{DISCARD_SUGGESTIONS:"idle"}},De={entry:(0,P.kp)({suggestions:e=>Ie(Re({},e.suggestions),{type:S.attribute,isVisible:!0,placeholder:Ce.SELECT_LABEL})}),on:{DISCARD_SUGGESTIONS:"idle",SELECT_SUGGESTION:[{cond:"isEditing",target:"loadOperators",actions:["editFilterAttribute"]},{target:"loadOperators",actions:["setFilterAttribute"]}],REMOVE_LAST_FILTER:{target:"idle",actions:["removeLastFilter"]}}};function Le(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Fe(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter((function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable})))),r.forEach((function(t){Le(e,t,n[t])}))}return e}function Be(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))})),e}const $e={entry:(0,P.kp)({suggestions:e=>{const t=e.edition?he(e):Z(e.filters);return I(void 0!==typeof(null==t?void 0:t.operator),"No operator for the target filter!"),Be(Fe({},He.suggestions),{disabled:["=~","!~"].includes(t.operator.value)||Ee(t.attribute.value),isVisible:!0,isLoading:!0})}}),invoke:{id:"fetchLabelValues",src:"fetchLabelValues",onDone:{target:"displayLabelValues",actions:(0,P.kp)({suggestions:(e,t)=>Be(Fe({},e.suggestions),{items:t.data,isLoading:!1})})},onError:{target:"displayLabelValues",actions:(0,P.kp)({suggestions:(e,t)=>Be(Fe({},e.suggestions),{items:[],isLoading:!1,error:t.data})})}},on:{DISCARD_SUGGESTIONS:"idle"}},Me={entry:(0,P.kp)({suggestions:e=>{const t=e.edition?he(e):Z(e.filters);I(void 0!==typeof(null==t?void 0:t.operator),"No operator for the target filter!");const n=t.operator.value,r=Te(n)||e.suggestions.disabled,o=X(n);let i,a;return i=r?Ce.TYPE_VALUE:o?Ce.SELECT_VALUES:Ce.SELECT_VALUE,a=e.suggestions.error?Ce.ERROR_LOAD:e.suggestions.disabled?Ce.SUGGESTIONS_DISABLED:Ce.SUGGESTIONS_NONE,Be(Fe({},e.suggestions),{type:S.value,isVisible:!0,placeholder:i,noOptionsMessage:a,allowCustomValue:r,multiple:o})}}),on:{DISCARD_SUGGESTIONS:"idle",SELECT_SUGGESTION:[{cond:"isEditing",target:"autoSuggestProxy",actions:["editFilterValue"]},{target:"idle",actions:["setFilterValue"]}],REMOVE_LAST_FILTER:{target:"loadOperators",actions:["removeLastFilter"]}}};function Ve(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Ue(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter((function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable})))),r.forEach((function(t){Ve(e,t,n[t])}))}return e}function Ge(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))})),e}const qe={entry:(0,P.kp)({suggestions:()=>Ge(Ue({},He.suggestions),{isVisible:!0,isLoading:!0})}),invoke:{id:"fetchOperators",src:"fetchOperators",onDone:{target:"displayOperators",actions:(0,P.kp)({suggestions:(e,t)=>Ge(Ue({},e.suggestions),{items:t.data,isLoading:!1})})},onError:{target:"displayOperators",actions:(0,P.kp)({suggestions:(e,t)=>Ge(Ue({},e.suggestions),{items:[],isLoading:!1,error:t.data})})}},on:{DISCARD_SUGGESTIONS:"idle"}},Ke={entry:(0,P.kp)({suggestions:e=>Ge(Ue({},e.suggestions),{type:S.operator,isVisible:!0,placeholder:Ce.SELECT_OPERATOR,allowCustomValue:!1,multiple:!1})}),on:{DISCARD_SUGGESTIONS:"idle",SELECT_SUGGESTION:[{cond:"shouldSuggestValuesAfterOperatorEdition",target:"loadLabelValues",actions:["editFilterOperator"]},{cond:"shouldNotSuggestValuesAfterOperatorEdition",target:"autoSuggestProxy",actions:["editFilterOperator"]},{cond:"hasPartialFilter",target:"autoSuggestProxy",actions:["setFilterOperator"]},{target:"loadLabelValues",actions:["setFilterOperator"]}],REMOVE_LAST_FILTER:{target:"loadLabels",actions:["removeLastFilter"]}}};function ze(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function We(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))})),e}const He=Object.freeze({inputParams:{query:"",from:0,to:0},query:"",filters:[],isQueryUpToDate:!0,edition:null,suggestions:{type:null,items:[],isVisible:!1,isLoading:!1,error:null,placeholder:"",noOptionsMessage:"",allowCustomValue:!1,multiple:!1,disabled:!1}}),Ye=e=>({id:"query-builder",initial:"idle",context:e,predictableActionArguments:!0,states:{idle:ke,loadLabels:_e,displayLabels:De,loadOperators:qe,displayOperators:Ke,loadLabelValues:$e,displayLabelValues:Me,autoSuggestProxy:Pe}}),Ze={guards:ge,services:xe,actions:fe};function Xe(e){const{query:t}=e,n=We(function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter((function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable})))),r.forEach((function(t){ze(e,t,n[t])}))}return e}({},He),{inputParams:e,query:t,filters:ae(t)}),r=(0,w.O)(Ye(n),Ze);return{actor:(0,O.U4)(r),initialContext:n}}const Je=new Intl.Collator("en",{sensitivity:"case"}).compare,Qe=e=>(t,n)=>{const r=e.some((e=>e.value===t.value)),o=e.some((e=>e.value===n.value));return r&&o?Je(t.value,n.value):o?1:r?-1:0};function et({selection:e,suggestions:t,onCloseMenu:n}){const r=(0,i.useStyles2)(tt),o=(0,p.useMemo)((()=>{const t=e.value.split("|"),n=e.label.split(", ");return t.map(((e,t)=>({value:e,label:n[t]})))}),[e]),[a,s]=(0,p.useState)(o),l=(0,p.useMemo)((()=>t.items.sort(Qe(a))),[t.items]),c=(0,p.useCallback)((e=>{s(e.map((({value:e="",label:t=""})=>({value:e,label:t}))))}),[]),u=(0,p.useCallback)((()=>{n(a)}),[n,a]);return m().createElement(i.MultiSelect,{className:r.editionSelect,placeholder:t.placeholder,loadingMessage:Ce.LOADING,closeMenuOnSelect:!1,hideSelectedOptions:!1,backspaceRemovesValue:!0,autoFocus:!0,value:a,onChange:c,onCloseMenu:u,options:l,isOpen:!0,isLoading:t.isLoading,invalid:Boolean(t.error),noOptionsMessage:t.noOptionsMessage})}const tt=()=>({editionSelect:r.css`
position: absolute;
z-index: 1;
[aria-label='Remove'] svg {
display: none;
}
`});function nt({placeholder:e,defaultValue:t,onFocus:n,onChange:o,onBlur:a}){const s=(0,i.useStyles2)(rt),l=(0,p.useRef)(null),[c,u]=(0,p.useState)(!1);return(0,p.useEffect)((()=>{l.current&&l.current.focus()}),[]),m().createElement(i.Input,{ref:l,className:(0,r.cx)(t&&s.edition),invalid:c,placeholder:e,defaultValue:t,onFocus:n,onKeyUp:e=>{const t=e.target.value.trim();"Enter"===e.code&&(t?o({value:t,label:t}):u(!0))},onBlur:e=>{const t=e.target.value.trim();t?o({value:t,label:t}):a()}})}const rt=()=>({edition:r.css`
position: absolute;
z-index: 1;
`}),ot=()=>({editionSelect:r.css`
position: absolute;
z-index: 1;
min-width: 160px;
box-shadow: none;
& input:focus {
outline: none !important;
}
`});function it({selection:e,suggestions:t,onChange:n,onCloseMenu:r}){const o=(0,i.useStyles2)(ot);return t.allowCustomValue?m().createElement(nt,{defaultValue:e.value,placeholder:t.placeholder,onChange:n,onBlur:r}):m().createElement(i.Select,{className:o.editionSelect,placeholder:t.placeholder,loadingMessage:Ce.LOADING,closeMenuOnSelect:!1,autoFocus:!0,value:e.value,onChange:n,onCloseMenu:r,options:t.items,isOpen:!0,isLoading:t.isLoading,invalid:Boolean(t.error),noOptionsMessage:t.noOptionsMessage})}const at=()=>{},st=({filter:e,onClick:t,onRemove:n})=>{const o=(0,i.useStyles2)(mt),{attribute:a,operator:s,active:l}=e,c=l?o.chiclet:(0,r.cx)(o.chiclet,o.inactiveChiclet);return m().createElement("div",{className:c,"aria-label":"Filter"},m().createElement(i.Tag,{"aria-label":"Filter label",className:o.chicletAttribute,name:a.label,onClick:at}),m().createElement(i.Tag,{"aria-label":"Filter operator",className:o.chicletOperator,name:s.label,onClick:(n,r)=>t(r,e,E.operator),tabIndex:0}),m().createElement(i.Tag,{"aria-label":"Remove filter",className:o.chicletRemoveButton,icon:"times",name:"",onClick:(t,r)=>n(r,e),tabIndex:0}))},lt=()=>{},ct=({filter:e,onClick:t,onRemove:n})=>{const o=(0,i.useStyles2)(mt),{attribute:a,operator:s,value:l,active:c}=e,u=c?o.chiclet:(0,r.cx)(o.chiclet,o.inactiveChiclet);return m().createElement("div",{className:u,"aria-label":"Filter"},m().createElement(i.Tag,{"aria-label":"Filter label",className:o.chicletAttribute,name:a.label,onClick:lt}),m().createElement(i.Tag,{"aria-label":"Filter operator",className:o.chicletOperator,name:s.label,onClick:(n,r)=>t(r,e,E.operator),tabIndex:0}),m().createElement(i.Tooltip,{content:l.label},m().createElement(i.Tag,{"aria-label":"Filter value",name:l.label,className:o.chicletValue,onClick:(n,r)=>t(r,e,E.value),tabIndex:0})),m().createElement(i.Tag,{"aria-label":"Remove filter",className:o.chicletRemoveButton,icon:"times",name:"",onClick:(t,r)=>n(r,e),tabIndex:0}))},ut=({filter:e,onClick:t})=>{const n=(0,i.useStyles2)(mt),{attribute:o,operator:a}=e;return o||a?m().createElement("div",{className:(0,r.cx)(n.chiclet,n.partialChiclet),"aria-label":"Partial filter"},m().createElement(i.Tag,{colorIndex:9,name:o.label,title:`Edit "${o.label}"`,onClick:(n,r)=>t(r,e,E.attribute),tabIndex:0}),a&&m().createElement(i.Tag,{colorIndex:9,name:a.label,title:`Edit "${a.label}"`,className:n.chicletOperator,onClick:(n,r)=>t(r,e,E.operator),tabIndex:0})):null},dt="rgb(61, 113, 217)",pt="#4a4b52",mt=e=>({chiclet:r.css`
display: flex;
align-items: center;
border: 1px solid ${dt};
border-radius: 2px;
& > button {
height: 30px;
background-color: ${e.colors.background.primary};
color: ${e.colors.text.maxContrast};
}
& > :first-child {
background-color: ${dt};
color: ${"#fff"};
border-radius: 0;
&:hover {
cursor: not-allowed !important;
}
}
& > :last-child {
border-left: 1px solid ${dt};
border-top-left-radius: 0;
border-bottom-left-radius: 0;
}
`,partialChiclet:r.css`
border-color: ${pt};
border-right: 0;
border-top-right-radius: 0;
border-bottom-right-radius: 0;
& > :first-child {
background-color: ${e.colors.background.secondary};
color: ${e.colors.text.maxContrast};
border-radius: 0;
border-left: 0;
&:hover {
cursor: pointer !important;
}
}
& > :last-child {
border-color: ${pt};
color: ${e.colors.text.maxContrast};
}
`,inactiveChiclet:r.css`
border-color: ${pt};
& > button {
color: ${e.colors.text.maxContrast};
}
& > :first-child {
background-color: ${e.colors.background.secondary};
color: ${e.colors.text.maxContrast};
}
& > :last-child {
border-color: ${pt};
}
`,chicletAttribute:r.css`
&:hover {
opacity: 1 !important;
}
`,chicletOperator:r.css`
&:hover {
background-color: ${e.colors.background.secondary};
}
`,chicletValue:r.css`
flex-grow: 1;
text-align: left;
max-width: 420px;
text-overflow: ellipsis;
text-wrap: nowrap;
overflow: hidden;
&:hover {
background-color: ${e.colors.background.secondary};
}
`,chicletRemoveButton:r.css`
&:hover {
background-color: ${e.colors.background.secondary};
}
& svg {
width: 12px;
height: 12px;
}
`}),ft=({filter:e,onClick:t,onRemove:n})=>{switch(e.type){case y.partial:return m().createElement(ut,{filter:e,onClick:t});case y["attribute-operator-value"]:return m().createElement(ct,{filter:e,onClick:t,onRemove:n});case y["attribute-operator"]:return m().createElement(st,{filter:e,onClick:t,onRemove:n});default:throw new TypeError(`Unsupported filter type "${e.type}" (${JSON.stringify(e)})!`)}},ht=(0,p.memo)(ft,((e,t)=>JSON.stringify(e.filter)===JSON.stringify(t.filter))),gt=()=>({chicletsList:r.css`
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 4px;
`,editChicletContainer:r.css`
position: relative;
`});function bt({filters:e,onClickChiclet:t,onRemoveChiclet:n,edition:r,suggestions:o,onChangeSingleSuggestion:a,onCloseSingleSuggestionsMenu:s,onCloseMultipleSuggestionsMenu:l}){const c=(0,i.useStyles2)(gt);return m().createElement("div",{className:c.chicletsList,"data-testid":"filtersList"},e.map((e=>m().createElement("div",{key:e.id,className:c.editChicletContainer},m().createElement(ht,{filter:e,onClick:t,onRemove:n}),(null==r?void 0:r.filterId)===e.id?o.multiple?m().createElement(et,{selection:e[r.part],suggestions:o,onCloseMenu:l}):m().createElement(it,{key:r.part,selection:e[r.part],suggestions:o,onChange:a,onCloseMenu:s}):null))))}const yt=(0,p.memo)(bt),vt=()=>({select:r.css`
border-top-right-radius: 0;
border-bottom-right-radius: 0;
`});function Et({suggestions:e,onFocus:t,onChange:n,onKeyDown:r,onCloseMenu:o}){const a=(0,i.useStyles2)(vt),s=function(e){const[t,n]=(0,p.useState)(!1);return(0,p.useEffect)((()=>{!e||t?e!==t&&n(e):setTimeout((()=>n(!0)),0)}),[t,e]),t}(e.isVisible);return e.allowCustomValue?m().createElement(nt,{placeholder:e.placeholder,onFocus:t,onChange:n,onBlur:o}):m().createElement(i.Select,{className:a.select,placeholder:e.placeholder,loadingMessage:Ce.LOADING,closeMenuOnSelect:!1,value:null,onFocus:t,onKeyDown:r,onChange:n,onCloseMenu:o,options:e.items,isOpen:s,isLoading:e.isLoading,invalid:Boolean(e.error),noOptionsMessage:e.noOptionsMessage})}const St=()=>{};function wt(){const e=(0,i.useStyles2)(vt);return m().createElement(i.Select,{disabled:!0,className:e.select,placeholder:Ce.FILTER_ADD,onChange:St})}function Ot({suggestions:e,onFocus:t,onKeyDown:n,onCloseMenu:r}){const o=(0,i.useStyles2)(xt),[a,s]=(0,p.useState)([]),l=(0,p.useCallback)((e=>{s(e.map((({value:e="",label:t=""})=>({value:e,label:t}))))}),[]),c=(0,p.useCallback)((e=>{n(e,a)}),[n,a]),u=(0,p.useCallback)((()=>{r(a)}),[r,a]);return m().createElement(i.MultiSelect,{className:o.select,placeholder:e.placeholder,loadingMessage:Ce.LOADING,closeMenuOnSelect:!1,hideSelectedOptions:!1,backspaceRemovesValue:!0,autoFocus:!0,value:a,onFocus:t,onKeyDown:c,onChange:l,onCloseMenu:u,options:e.items,isOpen:e.isVisible,isLoading:e.isLoading,invalid:Boolean(e.error),noOptionsMessage:e.noOptionsMessage})}const xt=()=>({select:r.css`
[aria-label='Remove'] svg {
display: none;
}
`}),Pt=()=>({queryBuilder:r.css`
display: flex;
justify-content: flex-start;
align-items: flex-end;
flex-wrap: wrap;
gap: 4px;
width: 100%;
`,controls:r.css`
display: flex;
align-self: flex-start;
flex-grow: 1;
`,executeButton:r.css`
border-top-left-radius: 0;
border-bottom-left-radius: 0;
`});function Ct(e){const t=(0,i.useStyles2)(Pt),{actor:n,internalProps:o}=function({dataSourceUid:e,query:t,from:n,to:r,onChangeQuery:o}){const{actor:i,initialContext:a}=(0,p.useMemo)((()=>Xe({query:t,from:n,to:r})),[]);(0,p.useEffect)((()=>{i.send({type:"CHANGE_INPUT_PARAMS",data:{dataSourceUid:e,query:t,from:n,to:r}})}),[i,e,t,n,r]);const[s,l]=(0,p.useState)(a);return(0,p.useEffect)((()=>(i.start(),i.subscribe((({event:e,context:t})=>{"EXECUTE_QUERY"===e.type&&o(t.query,t.filters),l(t)})),()=>{i.stop()})),[i]),{actor:i,internalProps:s}}(e),{filters:a,edition:s,isQueryUpToDate:l,suggestions:c}=o,{onClickChiclet:u,onRemoveChiclet:d}=function(e){const t=(0,p.useCallback)(((t,n,r)=>{e.send({type:"EDIT_FILTER",data:{filterId:n.id,part:r}})}),[e]),n=(0,p.useCallback)(((t,n)=>{e.send({type:"REMOVE_FILTER",data:n.id})}),[e]);return{onClickChiclet:t,onRemoveChiclet:n}}(n),{onFocus:f,onChangeSingleSuggestion:h,onSingleSelectKeyDown:g,onCloseSingleMenu:b,onMultipleSelectKeyDown:y,onCloseMultipleMenu:v}=function(e,t,n){const r=(0,p.useCallback)((()=>{e.send({type:"START_INPUT"})}),[e]),o=(0,p.useCallback)((t=>{const{value:n="",label:r=""}=t;e.send({type:"SELECT_SUGGESTION",data:{value:n,label:r}})}),[e]),i=(0,p.useCallback)((t=>{"Backspace"!==t.code||t.target.value||e.send({type:"REMOVE_LAST_FILTER"})}),[e]),a=(0,p.useCallback)((()=>{e.send({type:"DISCARD_SUGGESTIONS"})}),[e]),s=(0,p.useCallback)(((t,n)=>{"Backspace"!==t.code||t.target.value||n.length||e.send({type:"REMOVE_LAST_FILTER"})}),[e]),l=(0,p.useCallback)((t=>{t.length?e.send({type:"SELECT_SUGGESTION",data:{value:t.map((e=>e.value)).join("|"),label:t.map((e=>e.label)).join(", ")}}):e.send({type:"DISCARD_SUGGESTIONS"})}),[e]),c=function(e){const t=(0,p.useRef)();return(0,p.useEffect)((()=>{t.current=e})),t.current}(t.isVisible);return(0,p.useEffect)((()=>{var e;!t.isVisible&&c&&(null===(e=document.querySelector(`#${n} input`))||void 0===e||e.blur())}),[t.isVisible,c,n]),{onFocus:r,onChangeSingleSuggestion:o,onSingleSelectKeyDown:i,onMultipleSelectKeyDown:s,onCloseSingleMenu:a,onCloseMultipleMenu:l}}(n,c,e.id),E=(0,p.useCallback)((()=>{n.send({type:"EXECUTE_QUERY"})}),[n]);return(0,p.useEffect)((()=>{if(!e.autoExecute)return;const t=({value:e,context:t,event:r})=>{"idle"!==e||t.isQueryUpToDate||"EXECUTE_QUERY"===r.type||n.send({type:"EXECUTE_QUERY"})};return n.onTransition(t),()=>{n.off(t)}}),[n,e.autoExecute]),m().createElement("div",{id:e.id,className:(0,r.cx)(t.queryBuilder,e.className)},a.length>0?m().createElement(yt,{filters:a,onClickChiclet:u,onRemoveChiclet:d,edition:s,suggestions:c,onChangeSingleSuggestion:h,onCloseSingleSuggestionsMenu:b,onCloseMultipleSuggestionsMenu:v}):null,m().createElement("div",{className:t.controls},s?m().createElement(wt,null):c.multiple?m().createElement(Ot,{suggestions:c,onFocus:f,onKeyDown:y,onCloseMenu:v}):m().createElement(Et,{suggestions:c,onFocus:f,onChange:h,onKeyDown:g,onCloseMenu:b}),!e.autoExecute&&m().createElement(i.Button,{onClick:E,tooltip:l?"Nothing to execute, all filters applied":"Execute new query",className:t.executeButton,disabled:l},"Execute")))}const Tt=(0,p.memo)(Ct);var At=n(4386),jt=n(1269);const kt=Object.freeze({type:"grafana-pyroscope-datasource",uid:"$dataSource"}),Nt=Object.freeze({type:"grafana-pyroscope-series-datasource",uid:"grafana-pyroscope-series-datasource"}),Rt=Object.freeze({type:"grafana-pyroscope-favorites-datasource",uid:"grafana-pyroscope-favorites-datasource"}),It=Object.freeze({type:"grafana-pyroscope-labels-datasource",uid:"grafana-pyroscope-labels-datasource"});function _t(e,t,n,r,o,i,a){try{var s=e[i](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function Dt(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class Lt extends o.fS{onActivate(){this.state.value||this.setState({value:Lt.DEFAULT_VALUE})}update(e=!1){var t,n=this;return(t=function*(){if(!e&&n.state.loading)return;let t=[],r=null;n.setState({loading:!0,options:[],error:null});try{t=yield(0,jt.lastValueFrom)(n.getValueOptions({}))}catch(e){r=e}finally{n.setState({loading:!1,options:t,error:r})}},function(){var e=this,n=arguments;return new Promise((function(r,o){var i=t.apply(e,n);function a(e){_t(i,r,o,a,s,"next",e)}function s(e){_t(i,r,o,a,s,"throw",e)}a(void 0)}))})()}static buildCascaderOptions(e){const t=new Map;for(const{value:n}of e){const e=(0,At.y)(n),{group:r,type:o}=e,i=t.get(r)||{value:r,label:r,items:[]},a=i.items||[];a.push({value:n,label:o}),i.items=a,t.set(r,i)}return Array.from(t.values()).sort(((e,t)=>Je(t.label,e.label)))}constructor(e){super(function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter((function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable})))),r.forEach((function(t){Dt(e,t,n[t])}))}return e}({key:"profileMetricId",name:"profileMetricId",label:"Profile type",datasource:Nt,query:Lt.QUERY_DEFAULT,loading:!0,refresh:f.VariableRefresh.onTimeRangeChanged},e)),Dt(this,"onSelect",(e=>{(0,d.r)("g_pyroscope_app_profile_metric_selected"),this.state.skipUrlSync||s(),this.changeValueTo(e)})),this.changeValueTo=this.changeValueTo.bind(this),this.addActivationHandler(this.onActivate.bind(this))}}Dt(Lt,"DEFAULT_VALUE","process_cpu:cpu:nanoseconds:cpu:nanoseconds"),Dt(Lt,"QUERY_DEFAULT","$dataSource and all profile metrics"),Dt(Lt,"QUERY_SERVICE_NAME_DEPENDENT","$dataSource and only $serviceName profile metrics"),Dt(Lt,"Component",(({model:e})=>{const t=(0,i.useStyles2)(Ft),{loading:n,value:r,options:o,error:a}=e.useState(),s=(0,p.useMemo)((()=>Lt.buildCascaderOptions(o)),[o]);return a?m().createElement(i.Tooltip,{theme:"error",content:a.toString()},m().createElement(i.Icon,{className:t.iconError,name:"exclamation-triangle",size:"xl"})):m().createElement(i.Cascader,{key:(0,x.Ak)(5),"aria-label":"Profile metrics list",width:24,separator:"/",displayAllSelectedLevels:!0,placeholder:n?"Loading...":`Select a profile metric (${o.length})`,options:s,initialValue:r,changeOnSelect:!1,onSelect:e.onSelect})}));const Ft=e=>({iconError:r.css`
height: 32px;
align-self: center;
color: ${e.colors.error.text};
`});var Bt=n(8169);function $t(e,t,n,r,o,i,a){try{var s=e[i](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function Mt(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class Vt extends o.fS{onActivate(){this.setInitialValue(),this.subscribeToState(((e,t)=>{if(e.value&&e.value!==t.value){const t=Bt.x.get(Bt.x.KEYS.PROFILES_EXPLORER)||{};t.serviceName=e.value,Bt.x.set(Bt.x.KEYS.PROFILES_EXPLORER,t)}}))}setInitialValue(){var e,t;const{serviceName:n}=Bt.x.get(Bt.x.KEYS.PROFILES_EXPLORER)||{},r=null===(t=this.initialFilters)||void 0===t||null===(e=t.find((e=>"service_name"===e.key&&"="===e.operator)))||void 0===e?void 0:e.value;!n||this.state.value||r?r&&this.setState({value:r}):this.setState({value:n})}update(){var e,t=this;return(e=function*(){if(t.state.loading)return;let e=[],n=null;t.setState({loading:!0,options:[],error:null});try{e=yield(0,jt.lastValueFrom)(t.getValueOptions({}))}catch(e){n=e}finally{t.setState({loading:!1,options:e,error:n})}},function(){var t=this,n=arguments;return new Promise((function(r,o){var i=e.apply(t,n);function a(e){$t(i,r,o,a,s,"next",e)}function s(e){$t(i,r,o,a,s,"throw",e)}a(void 0)}))})()}constructor(e){super(function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter((function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable})))),r.forEach((function(t){Mt(e,t,n[t])}))}return e}({key:"serviceName",name:"serviceName",label:"Service",datasource:Nt,query:Vt.QUERY_DEFAULT,loading:!0,refresh:f.VariableRefresh.onTimeRangeChanged},e)),Mt(this,"initialFilters",void 0),Mt(this,"selectNewValue",(e=>{(0,d.r)("g_pyroscope_app_service_name_selected"),this.state.skipUrlSync||s(),this.changeValueTo(e)})),this.initialFilters=null==e?void 0:e.initialFilters,this.addActivationHandler(this.onActivate.bind(this))}}Mt(Vt,"QUERY_DEFAULT","$dataSource and all services"),Mt(Vt,"QUERY_PROFILE_METRIC_DEPENDENT","$dataSource and only $profileMetricId services"),Mt(Vt,"Component",(({model:e})=>{const t=(0,i.useStyles2)(Ut),{loading:n,value:r,options:o,error:a}=e.useState(),s=(0,p.useMemo)((()=>function(e){const t=[...e].sort(),n=[],r=new Map;for(const e of t){const t=e.split("/");let o="";for(let e=0;e<t.length;e++){const i=t[e],a=o;o=o?`${o}/${i}`:i;const s=e===t.length-1;if(!r.has(o)||s){const e={value:s?o:o+"/",label:i,items:s?void 0:[]};if(s||r.set(o,e),a){const t=r.get(a);t&&t.items&&t.items.push(e)}else n.push(e)}}}return n}(o.map((({label:e})=>e)))),[o]);return a?m().createElement(i.Tooltip,{theme:"error",content:a.toString()},m().createElement(i.Icon,{className:t.iconError,name:"exclamation-triangle",size:"xl"})):m().createElement(i.Cascader,{key:(0,x.Ak)(5),"aria-label":"Services list",width:32,separator:"/",displayAllSelectedLevels:!0,placeholder:n?"Loading services...":`Select a service (${o.length})`,options:s,initialValue:r,changeOnSelect:!1,onSelect:e.selectNewValue})}));const Ut=e=>({iconError:r.css`
height: 32px;
align-self: center;
color: ${e.colors.error.text};
`});function Gt(e,t){const{value:n}=o.jh.findByKeyAndType(e,"serviceName",Vt).useState(),{value:r}=o.jh.findByKeyAndType(e,"profileMetricId",Lt).useState(),{filterExpression:i}=o.jh.findByKeyAndType(e,t,nn).useState();return(0,p.useMemo)((()=>`${r}{service_name="${n}",${i}}`),[i,r,n])}class qt extends o.mI{onActivate(){this.setState({skipUrlSync:!1}),this.subscribeToState(((e,t)=>{if(e.value&&e.value!==t.value){const t=Bt.x.get(Bt.x.KEYS.PROFILES_EXPLORER)||{};t.dataSource=e.value,Bt.x.set(Bt.x.KEYS.PROFILES_EXPLORER,t)}}))}constructor({initialDS:e}){super({pluginId:"grafana-pyroscope-datasource",key:"dataSource",name:"dataSource",label:"Data source",skipUrlSync:!0,value:null!=e?e:L.O.selectDefaultDataSource().uid}),this.addActivationHandler(this.onActivate.bind(this))}}function Kt(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function zt(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter((function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable})))),r.forEach((function(t){Kt(e,t,n[t])}))}return e}function Wt(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))})),e}const Ht=e=>{let t=e.operator.value;return e.operator.value===v.in?t=v["=~"]:e.operator.value===v["not-in"]&&(t=v["!~"]),{key:e.attribute.value,operator:t,value:e.value.value}};function Yt(e,t){let n;const r=e.filter((e=>e.key!==t||(n=e,!1)));return{found:n,filtersWithoutFound:r}}const Zt=(e,t)=>[...e,t];function Xt(e,t){const{found:n,filtersWithoutFound:r}=Yt(e,t.key);if(!n)return Zt(e,Wt(zt({},t),{operator:"=~"}));if(["!~","!="].includes(n.operator))return Zt(r,Wt(zt({},t),{operator:"=~"}));const o=new Set(n.value.split("|"));return"=~"===n.operator?Zt(r,Wt(zt({},n),{value:Array.from(o.add(t.value)).join("|")})):n.value===t.value?e:Zt(r,Wt(zt({},t),{operator:"=~",value:Array.from(o.add(t.value)).join("|")}))}function Jt(e,t){const{found:n,filtersWithoutFound:r}=Yt(e,t.key);if(!n)return Zt(e,Wt(zt({},t),{operator:"!~"}));if(["=~","="].includes(n.operator))return Zt(r,Wt(zt({},t),{operator:"!~"}));const o=new Set(n.value.split("|"));return"!~"===n.operator?Zt(r,Wt(zt({},n),{value:Array.from(o.add(t.value)).join("|")})):n.value===t.value?e:Zt(r,Wt(zt({},t),{operator:"!~",value:Array.from(o.add(t.value)).join("|")}))}function Qt(e,t){const{found:n,filtersWithoutFound:r}=Yt(e,t.key);if(!n)return e;const o=n.value.split("|").filter((e=>e!==t.value));return o.length>0?Zt(r,Wt(zt({},n),{value:o.join("|")})):[...r]}const en=e=>e.operator in v;function tn(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class nn extends o.H9{reset(){this.setState({filters:nn.DEFAULT_VALUE})}static resetAll(e){["filters","filtersBaseline","filtersComparison"].forEach((t=>{o.jh.findByKeyAndType(e,t,nn).reset()}))}onActivate(){this.setInitialValue();const e=o.jh.findByKeyAndType(this,"dataSource",qt).subscribeToState((()=>{this.reset()}));return()=>{e.unsubscribe()}}setInitialValue(){this.initialFilters&&this.initialFilters.length>0&&this.setState({filters:this.initialFilters})}constructor({key:e,initialFilters:t}){super({key:e,name:e,label:"Filters",filters:nn.DEFAULT_VALUE,expressionBuilder:e=>e.filter(en).map((({key:e,operator:t,value:n})=>t===v["is-empty"]?`${e}=""`:`${e}${t}"${n}"`)).join(",")}),tn(this,"initialFilters",void 0),tn(this,"onChangeQuery",((e,t)=>{(0,d.r)("g_pyroscope_app_filters_changed",{name:this.state.name,count:t.length,operators:(0,g.uniq)(t.map((e=>e.operator.label)))}),this.setState({filters:t.map(Ht)})})),this.initialFilters=t,this.addActivationHandler(this.onActivate.bind(this))}}function rn(e,t){var n;return null===(n=o.jh.lookupVariable(t,e))||void 0===n?void 0:n.getValue()}function on(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}tn(nn,"DEFAULT_VALUE",[]),tn(nn,"Component",(({model:e})=>{const{key:t}=e.useState(),n=Gt(e,t),{value:r}=o.jh.findByKeyAndType(e,"dataSource",qt).useState(),{from:i,to:a}=o.jh.getTimeRange(e).state.value;return m().createElement(Tt,{id:`query-builder-${t}`,autoExecute:!0,dataSourceUid:r,query:n,from:1e3*i.unix(),to:1e3*a.unix(),onChangeQuery:e.onChangeQuery})}));var an=function(e){return e.TIMESERIES="time-series",e.BARGAUGE="bar-gauge",e.TABLE="table",e.HISTOGRAM="histogram",e}({});class sn extends o.Bs{getUrlState(){return{panelType:this.state.panelType}}updateFromUrl(e){const t={};"string"==typeof e.panelType&&e.panelType!==this.state.panelType&&(t.panelType=Object.values(an).includes(e.panelType)?e.panelType:sn.DEFAULT_PANEL_TYPE),this.setState(t)}reset(){this.setState({panelType:sn.DEFAULT_PANEL_TYPE})}constructor(){super({key:"panel-type-switcher",panelType:sn.DEFAULT_PANEL_TYPE}),on(this,"_urlSync",new o.So(this,{keys:["panelType"]})),on(this,"onChange",(e=>{(0,d.r)("g_pyroscope_app_panel_type_changed",{panelType:e}),this.setState({panelType:e})}))}}on(sn,"OPTIONS",[{label:"Time series",value:"time-series",icon:"heart-rate"},{label:"Totals",value:"bar-gauge",icon:"align-left"},{label:"Maxima",value:"table",icon:"angle-double-up"},{label:"Histograms",value:"histogram",icon:"graph-bar"}]),on(sn,"DEFAULT_PANEL_TYPE","time-series"),on(sn,"Component",(({model:e})=>{const{panelType:t}=e.useState();return m().createElement(i.RadioButtonGroup,{"aria-label":"Panel type switcher",options:sn.OPTIONS,value:t,onChange:e.onChange,fullWidth:!1})}));var ln=n(1625);function cn(e){const t=C.config.theme2.visualization;return t.getColorByName(t.palette[e%8])}const un=(e,t)=>{var n;return(null===(n=e.labels)||void 0===n?void 0:n[t])||"(no value)"},dn=(e,t)=>{var n,r,o;return null===(o=e.meta)||void 0===o||null===(r=o.stats)||void 0===r||null===(n=r.find((e=>e.displayName===t)))||void 0===n?void 0:n.value};var pn=n(6415);function mn(e){return e.addActivationHandler((()=>{const{profileTypeId:t,labelSelector:n}=e.state.queries[0];if(!t)return void e.setState({queries:[{refId:"null"}],data:fn(e,"Missing profile type!")});if(!n)return void e.setState({queries:[{refId:"null"}],data:fn(e,"Missing label selector!")});if(!o.jh.interpolate(e,"$profileMetricId"))return void e.setState({queries:[{refId:"null"}],data:fn(e,"Missing profile type!")});(0,pn.m)(o.jh.interpolate(e,`$profileTypeId${n})`)).serviceId||e.setState({queries:[{refId:"null"}],data:fn(e,"Missing service name!")})})),e}function fn(e,t){const n=new Error(t);return be.v.error(n),{state:f.LoadingState.Error,errors:[n],series:[],timeRange:o.jh.getTimeRange(e).state.value}}function hn({serviceName:e,profileMetricId:t,groupBy:n,filters:r},i,a,s){const l=r?[...r]:[];l.unshift({key:"service_name",operator:"=",value:e||"$serviceName"});const c=l.map((({key:e,operator:t,value:n})=>`${e}${t}"${n}"`)).join(",");return mn(new o.dt({datasource:kt,queries:[{refId:`${t||"$profileMetricId"}-${c}-${(null==n?void 0:n.label)||"no-group-by"}`,queryType:"metrics",profileTypeId:t||"$profileMetricId",labelSelector:`{${c},$filters}`,groupBy:(null==n?void 0:n.label)?[n.label]:[],limit:i,annotations:a,includeExemplars:s}]}))}const gn=()=>e=>e.pipe((0,jt.map)((e=>null==e?void 0:e.map(((e,t)=>(0,g.merge)(e,{refId:`${e.refId}-${t}`})))))),bn=()=>e=>e.pipe((0,jt.map)((e=>{const t=null==e?void 0:e.length;return null==e?void 0:e.map((e=>{var n,r;let o=Number.NEGATIVE_INFINITY;const i=null===(r=e.fields)||void 0===r||null===(n=r.find((e=>"number"===e.type)))||void 0===n?void 0:n.values.reduce(((e,t)=>(t>o&&(o=t),e+t)),0);return(0,g.merge)(e,{meta:{stats:[{displayName:"totalSeriesCount",value:t},{displayName:"allValuesSum",value:i},{displayName:"maxValue",value:o}]}})}))})));class yn extends o.Bs{onActivate(e){const{body:t}=this.state,n=t.state.$data.subscribeToState((n=>{var r;if((null===(r=n.data)||void 0===r?void 0:r.state)!==f.LoadingState.Done)return;const{series:o}=n.data;(null==o?void 0:o.length)&&t.setState(this.getConfig(e,o)),this.publishEvent(new b({series:o}),!0)}));return()=>{n.unsubscribe()}}getConfig(e,t){var n;let r=Number.NEGATIVE_INFINITY;for(const e of t){const t=dn(e,"allValuesSum")||0;t>r&&(r=t)}const o=null===(n=e.queryRunnerParams.groupBy)||void 0===n?void 0:n.label,i=o?"This panel displays aggregate values over the current time period":void 0;return{title:t.length>1?`${e.label} (${t.length})`:e.label,description:i,options:{reduceOptions:{values:!1,calcs:["sum"]},orientation:f.VizOrientation.Horizontal,displayMode:ln.eX.Gradient,valueMode:ln.$l.Text,showUnfilled:!0,sizing:ln.T6.Manual,text:{titleSize:13,valueSize:13},namePlacement:ln.TZ.Top,minVizHeight:36,maxVizHeight:36,legend:{showLegend:!1}},fieldConfig:{defaults:{displayName:1===t.length?o:void 0,min:0,max:r,thresholds:{mode:f.ThresholdsMode.Percentage,steps:[]}},overrides:this.getOverrides(e,t)}}}getOverrides(e,t){var n;const{index:r,queryRunnerParams:o}=e,i=null===(n=o.groupBy)||void 0===n?void 0:n.label;return t.map(((e,t)=>({matcher:{id:f.FieldMatcherID.byFrameRefID,options:e.refId},properties:[{id:"displayName",value:un(e.fields[1],i)},{id:"color",value:{mode:"fixed",fixedColor:cn(r+t)}}]})))}static Component({model:e}){const{body:t}=e.useState();return m().createElement(t.Component,{model:t})}constructor({item:e,headerActions:t}){super({key:"bar-gauge-label-values",body:o.d0.bargauge().setTitle(e.label).setData(new o.Es({$data:hn(e.queryRunnerParams),transformations:[gn,bn]})).setHeaderActions(t(e)).build()}),this.addActivationHandler(this.onActivate.bind(this,e))}}function vn(e,t){var n,r;const o=(null===(r=t.fields[1])||void 0===r||null===(n=r.config)||void 0===n?void 0:n.unit)||"short",i=dn(t,"allValuesSum")||0,a=dn(t,"maxValue")||0,s=function(e){var t,n;const r=null===(n=e.meta)||void 0===n||null===(t=n.custom)||void 0===t?void 0:t.rateCalculated;return Boolean(r)}(t);let l,c;if(s){var u;const e=t.fields.find((e=>"number"===e.type));l=i/((null==e||null===(u=e.values)||void 0===u?void 0:u.length)||1),c="avg"}else l=i,c="total";const d=(0,f.getValueFormat)(o)(l),p=(0,f.getValueFormat)(o)(a);return`${c} ${e} = ${d.text}${d.suffix} / max = ${p.text}${p.suffix}`}class En extends o.Bs{onActivate(e){const{body:t}=this.state,n=t.state.$data.subscribeToState((n=>{var r;if((null===(r=n.data)||void 0===r?void 0:r.state)!==f.LoadingState.Done)return;const{series:o}=n.data;(null==o?void 0:o.length)&&t.setState(this.getConfig(e,o)),this.publishEvent(new b({series:o}),!0)}));return()=>{n.unsubscribe()}}getConfig(e,t){var n;const{legendPlacement:r}=this.state,o=null===(n=e.queryRunnerParams.groupBy)||void 0===n?void 0:n.label;return{title:t.length>1?`${e.label} (${t.length})`:e.label,options:{tooltip:{mode:i.TooltipDisplayMode.Single,sort:ln.xB.None},legend:{showLegend:!0,displayMode:i.LegendDisplayMode.List,placement:r,calcs:[]}},fieldConfig:{defaults:{displayName:1===t.length?o:void 0,custom:{lineWidth:1}},overrides:this.getOverrides(e,t)}}}getOverrides(e,t){var n;const{index:r,queryRunnerParams:o}=e,i=null===(n=o.groupBy)||void 0===n?void 0:n.label;return t.map(((e,n)=>{const o=e.fields[1];let a=i?un(o,i):o.name;return 1===t.length&&(a=vn(a,e)),{matcher:{id:f.FieldMatcherID.byFrameRefID,options:e.refId},properties:[{id:"displayName",value:a},{id:"color",value:{mode:"fixed",fixedColor:cn(r+n)}}]}}))}static Component({model:e}){const{body:t}=e.useState();return m().createElement(t.Component,{model:t})}constructor({item:e,headerActions:t,legendPlacement:n}){super({key:"histogram-label-values",legendPlacement:n||"bottom",body:o.d0.histogram().setTitle(e.label).setData(new o.Es({$data:hn(e.queryRunnerParams),transformations:[gn,bn]})).setHeaderActions(t(e)).build()}),this.addActivationHandler(this.onActivate.bind(this,e))}}class Sn extends o.Bs{onActivate(e){const{body:t}=this.state,n=t.state.$data.subscribeToState((n=>{var r;if((null===(r=n.data)||void 0===r?void 0:r.state)!==f.LoadingState.Done)return;const{series:o}=n.data;(null==o?void 0:o.length)&&t.setState(this.getConfig(e,o)),this.publishEvent(new b({series:o}),!0)}));return()=>{n.unsubscribe()}}getConfig(e,t){const n=t[0].fields[0].values.length,r=o.jh.findByKeyAndType(this,"profileMetricId",Lt).state.value,i=(0,At.y)(r).unit;return{title:n>1?`${e.label} (${n})`:e.label,fieldConfig:{defaults:{custom:{filterable:!0,cellOptions:{}}},overrides:[{matcher:{id:"byName",options:"max"},properties:[{id:"unit",value:i},{id:"custom.width",value:100}]}]}}}static Component({model:e}){const t=(0,i.useStyles2)(wn),{body:n}=e.useState();return m().createElement("span",{className:t.container},m().createElement(n.Component,{model:n}))}constructor({item:e,headerActions:t}){super({key:"table-label-values",body:o.d0.table().setTitle(e.label).setData(new o.Es({$data:hn(e.queryRunnerParams),transformations:[{id:f.DataTransformerID.reduce,options:{reducers:["max"],labelsToFields:!0}},{id:f.DataTransformerID.filterFieldsByName,options:{exclude:{names:["Field"]}}},{id:f.DataTransformerID.renameByRegex,options:{regex:"Max",renamePattern:"max"}},{id:f.DataTransformerID.sortBy,options:{sort:[{field:"max",desc:!0}]}}]})).setHeaderActions(t(e)).build()}),this.addActivationHandler(this.onActivate.bind(this,e))}}const wn=()=>({container:r.css`
[data-testid='data-testid table body'] [role='row']:first-child {
color: ${cn(3)};
font-weight: 500;
}
`});var On=n(1835);function xn(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class Pn extends o.Bs{constructor(e){super({showExemplars:e}),xn(this,"onClick",(()=>{this.setState({showExemplars:!this.state.showExemplars});o.jh.getAncestor(this,Yn).handleExemplarToggleChange(this.state.showExemplars)}))}}function Cn(e){return{from:1e4*Math.floor((e.from.valueOf()||0)/1e4),to:1e4*Math.floor((e.to.valueOf()||0)/1e4)}}function Tn(e,t){try{var n;return null!==(n=o.jh.interpolate(e,t))&&void 0!==n?n:""}catch(e){return""}}function An(e,t,n,r,o,i,a){try{var s=e[i](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function jn(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var i=e.apply(t,n);function a(e){An(i,r,o,a,s,"next",e)}function s(e){An(i,r,o,a,s,"throw",e)}a(void 0)}))}}function kn(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Nn(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter((function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable})))),r.forEach((function(t){kn(e,t,n[t])}))}return e}function Rn(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))})),e}xn(Pn,"Component",(({model:e})=>{const{showExemplars:t}=e.useState();return m().createElement(i.Button,{icon:t?"eye":"eye-slash",variant:"secondary",size:"sm","aria-label":t?"Hide exemplars":"Show exemplars",tooltip:t?"Hide exemplars":"Show exemplars",tooltipPlacement:"top",onClick:e.onClick},"Exemplars")}));const In=(0,n(8537).A)(20);class _n extends o.UU{query(){return jn((function*(){return{state:f.LoadingState.Done,data:[{name:"Labels",fields:[{name:"Label",type:f.FieldType.other,values:[],config:{}}],length:0}]}}))()}getParams(e){var t;const{scopedVars:n,range:r}=e,o=null==n||null===(t=n.__sceneObject)||void 0===t?void 0:t.valueOf(),i=Tn(o,"$dataSource"),a=Tn(o,"$serviceName"),s=Tn(o,"$profileMetricId"),l=`${s}{service_name="${a}"}`,{from:c,to:u}=Cn(r);return{dataSourceUid:i,serviceName:a,profileMetricId:s,query:l,from:c,to:u}}fetchLabels(e,t,n,r,o){return jn((function*(){q.setApiClient(new N({dataSourceUid:e}));try{return yield q.listLabels({query:t,from:n,to:r})}catch(e){throw be.v.error(e,{info:"Error while loading Pyroscope label names!",variableName:o||""}),e}}))()}fetchLabelValues(e,t,n,r,o,i){return jn((function*(){let e;try{e=yield q.listLabelValues({query:t,from:n,to:r,label:o})}catch(e){be.v.error(e,{info:"Error while loading Pyroscope label values!",variableName:i||""})}const a=e?e.length:-1;return{value:{value:o,groupBy:{label:o,values:e||[]}},text:`${o} (${a>-1?a:"?"})`,count:a}}))()}metricFindQuery(e,t){var n=this;return jn((function*(){var e,r,o;if(!(null===(r=t.scopedVars)||void 0===r||null===(e=r.__sceneObject)||void 0===e?void 0:e.valueOf()).isActive)return[];const{dataSourceUid:i,serviceName:a,profileMetricId:s,query:l,from:c,to:u}=n.getParams(t);if(!a||!s)return be.v.warn('LabelsDataSource: either serviceName="%s" and/or profileMetricId="%s" is empty! Discarding request.',a,s),[];const d=yield n.fetchLabels(i,l,c,u,null===(o=t.variable)||void 0===o?void 0:o.name),p=yield Promise.all(d.filter((({value:e})=>!Ee(e))).map((({value:e},r)=>In((()=>{var o;return n.fetchLabelValues(r,l,c,u,e,null===(o=t.variable)||void 0===o?void 0:o.name)}))))),m=p.sort(((e,t)=>t.count-e.count)).map((({value:e,text:t},n)=>({value:JSON.stringify(Rn(Nn({},e),{index:n})),text:t})));return[{value:"all",text:"All"},...m]}))()}testDatasource(){return jn((function*(){return{status:"success",message:"OK"}}))()}constructor(){super(It.type,It.uid)}}function Dn(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Ln(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))})),e}kn(_n,"MAX_TIMESERIES_LABEL_VALUES",10);class Fn extends f.MutableDataFrame{addRange(e){this.add(Ln(function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter((function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable})))),r.forEach((function(t){Dn(e,t,n[t])}))}return e}({},e),{isRegion:!0}))}constructor(){super(),[{name:"time",type:f.FieldType.time},{name:"timeEnd",type:f.FieldType.time},{name:"isRegion",type:f.FieldType.boolean},{name:"color",type:f.FieldType.other},{name:"text",type:f.FieldType.string}].forEach((e=>this.addField(e)))}}function Bn(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function $n(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter((function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable})))),r.forEach((function(t){Bn(e,t,n[t])}))}return e}function Mn(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))})),e}function Vn(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Un(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter((function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable})))),r.forEach((function(t){Vn(e,t,n[t])}))}return e}function Gn(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))})),e}const qn=[{text:"Linear",scaleDistribution:{type:ln.L4.Linear}},{text:"Log2",scaleDistribution:{type:ln.L4.Log,log:2}}];class Kn extends o.Bs{onActivate(){this.setState({items:this.buildMenuItems()})}buildMenuItems(){const{scaleType:e,showExemplars:t}=this.state,n=[{text:"Scale type",type:"group",subMenu:qn.map((t=>({text:`${e===t.scaleDistribution.type?"✔ ":""}${t.text}`,onClick:()=>this.onClickScaleOption(t)})))},{type:"divider",text:""},{iconClassName:"compass",text:"Open in Explore",onClick:()=>this.onClickExplore()}];return void 0!==t&&n.unshift({iconClassName:t?"eye":"eye-slash",text:"Exemplars",onClick:()=>this.onClickToggleExemplars()},{type:"divider",text:"new-divider"}),n}onClickToggleExemplars(){const e=!this.state.showExemplars;(0,C.reportInteraction)("g_pyroscope_app_exemplars_toggled",{showExemplars:e}),this.setState({showExemplars:e,items:this.buildMenuItems()});o.jh.getAncestor(this,Yn).handleExemplarToggleChange(e)}onClickScaleOption(e){const{scaleDistribution:t,text:n}=e;(0,C.reportInteraction)("g_pyroscope_app_timeseries_scale_changed",{scale:t.type});o.jh.getAncestor(this,Yn).changeScale(t,n),this.setState({scaleType:t.type,items:this.buildMenuItems()})}onClickExplore(){(0,C.reportInteraction)("g_pyroscope_app_open_in_explore_clicked");const e=function(e,t,n){const r=JSON.stringify({"pyroscope-explore":{range:(0,f.toURLRange)(e),queries:[Mn($n({},t),{datasource:n})],panelsState:{},datasource:n}});var o;const i=null!==(o=C.config.appSubUrl)&&void 0!==o?o:"";return f.urlUtil.renderUrl(`${i}/explore`,{panes:r,schemaVersion:1})}(o.jh.getTimeRange(this).state.value.raw,this.getInterpolatedQuery(),o.jh.interpolate(this,"${dataSource}"));window.open(e,"_blank")}getInterpolatedQuery(){var e;const t=null===(e=o.jh.getAncestor(this,Yn).state.body.state.$data)||void 0===e?void 0:e.state.$data,n=null==t?void 0:t.state.queries[0];return Object.entries(n).map((([e,t])=>[e,"string"==typeof t?o.jh.interpolate(this,t):t])).reduce(((e,[t,n])=>Gn(Un({},e),{[t]:n})),{})}static Component({model:e}){return m().createElement(o.Lw.Component,{model:e})}constructor(e){super(Un({scaleType:ln.L4.Linear},e)),this.addActivationHandler(this.onActivate.bind(this))}}function zn(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Wn(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter((function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable})))),r.forEach((function(t){zn(e,t,n[t])}))}return e}function Hn(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))})),e}class Yn extends o.Bs{onActivate(){const{body:e}=this.state,t=e.state.$data.subscribeToState(this.handleDataStateChange.bind(this)),n=this.subscribeToProfileMetricChanges();return()=>{t.unsubscribe(),null==n||n.unsubscribe()}}handleDataStateChange(e,t){var n;if((null===(n=e.data)||void 0===n?void 0:n.state)!==f.LoadingState.Done)return;this.retainPreviousAnnotations(e,t);const{series:r}=e.data;(null==r?void 0:r.length)&&this.updateBodyConfig(r),this.publishEvent(new b({series:r}),!0)}retainPreviousAnnotations(e,t){var n,r,o,i;const a=null==t||null===(r=t.data)||void 0===r||null===(n=r.annotations)||void 0===n?void 0:n.filter((e=>e instanceof Fn));var s,l;a&&!(null==e||null===(i=e.data)||void 0===i||null===(o=i.annotations)||void 0===o?void 0:o.some((e=>e instanceof Fn)))&&(null==e||null===(l=e.data)||void 0===l||null===(s=l.annotations)||void 0===s||s.push(...a))}updateBodyConfig(e){const{body:t}=this.state,n=this.state.displayAllValues?this.getAllValuesConfig(e):this.getConfig(e);t.setState((0,g.merge)({},t.state,n))}subscribeToProfileMetricChanges(){try{return o.jh.findByKeyAndType(this,"profileMetricId",Lt).subscribeToState(((e,t)=>{e.value!==t.value&&this.handleProfileMetricChange()}))}catch(e){return null}}handleProfileMetricChange(){var e;const{body:t}=this.state,n=t.state.$data.state.data;(null==n||null===(e=n.series)||void 0===e?void 0:e.length)&&this.updateBodyConfig(n.series)}handleExemplarToggleChange(e){var t;const{body:n,item:r,displayAllValues:o,annotations:i}=this.state;if(!e){const{$data:e}=n.state,t=null==e?void 0:e.state.data;if(null==t?void 0:t.annotations){const n=t.annotations.filter((e=>"exemplar"!==e.name));null==e||e.setState({data:Hn(Wn({},t),{annotations:n})})}return}const{queries:a}=hn(r.queryRunnerParams,o?void 0:_n.MAX_TIMESERIES_LABEL_VALUES,i,e).state,s=null===(t=n.state.$data)||void 0===t?void 0:t.state.$data;s&&(s.setState({queries:a}),s.runQueries())}getConfig(e){var t;const{body:n,item:r,legendPlacement:o}=this.state;let i,{title:a}=n.state;return(null===(t=r.queryRunnerParams.groupBy)||void 0===t?void 0:t.label)&&(a=e.length>1?`${r.label} (${e.length})`:r.label,i=this.buildDescription(r.queryRunnerParams.groupBy)),{title:a,description:i,options:{tooltip:{mode:"single",sort:"none"},legend:{showLegend:!0,displayMode:"list",placement:o}},fieldConfig:{defaults:{min:0,custom:{fillOpacity:e.length>=_n.MAX_TIMESERIES_LABEL_VALUES?0:9,gradientMode:1===e.length?ln.on.None:ln.on.Opacity,pointSize:3}},overrides:this.getOverrides(e)}}}buildDescription(e){return e?e.values?e.values.length>_n.MAX_TIMESERIES_LABEL_VALUES?`Showing only ${_n.MAX_TIMESERIES_LABEL_VALUES} out of ~${e.values.length} series to preserve readability. To view all the series for the current filters, click on the expand icon on this panel.`:"":`Showing only ${_n.MAX_TIMESERIES_LABEL_VALUES} series to preserve readability. To view all the series, click on the expand icon on this panel.`:""}getAllValuesConfig(e){const{legendPlacement:t}=this.state;return{options:{tooltip:{mode:i.TooltipDisplayMode.Single,sort:ln.xB.None},legend:{showLegend:!0,displayMode:i.LegendDisplayMode.List,placement:t,calcs:[]}},fieldConfig:{defaults:{min:0,custom:{fillOpacity:0,pointSize:5}},overrides:this.getOverrides(e)}}}getOverrides(e){var t;if(this.state.overrides)return this.state.overrides(e);const{item:n}=this.state,r=null===(t=n.queryRunnerParams.groupBy)||void 0===t?void 0:t.label;return e.map(((e,t)=>{const o=e.fields[1];let i=r?un(o,r):o.name;i=vn(i,e);const a=[{id:"displayName",value:i},{id:"color",value:{mode:"fixed",fixedColor:cn(n.index+t)}}];return{matcher:{id:f.FieldMatcherID.byFrameRefID,options:e.refId},properties:a}}))}updateItem(e){var t,n;const{item:r,headerActions:o,body:i}=this.state,a=(0,g.merge)({},r,e);if((null===(t=e.queryRunnerParams)||void 0===t?void 0:t.hasOwnProperty("groupBy"))&&(void 0===e.queryRunnerParams.groupBy?delete a.queryRunnerParams.groupBy:a.queryRunnerParams.groupBy=e.queryRunnerParams.groupBy),(null===(n=e.queryRunnerParams)||void 0===n?void 0:n.hasOwnProperty("filters"))&&void 0===e.queryRunnerParams.filters&&delete a.queryRunnerParams.filters,this.setState({item:a}),i.setState({title:e.label,description:this.buildDescription(a.queryRunnerParams.groupBy),headerActions:o(a)}),!(0,g.isEqual)(r.queryRunnerParams,a.queryRunnerParams)){var s;const{queries:e}=hn(a.queryRunnerParams,_n.MAX_TIMESERIES_LABEL_VALUES).state,t=null===(s=i.state.$data)||void 0===s?void 0:s.state.$data;null==t||t.setState({queries:e}),null==t||t.runQueries()}}changeScale(e,t){const{body:n}=this.state;n.clearFieldConfigCache(),n.setState({fieldConfig:(0,g.merge)({},n.state.fieldConfig,{defaults:{custom:{scaleDistribution:e,axisLabel:e.type!==ln.L4.Linear?t:""}}})})}static Component({model:e}){const{body:t}=e.useState();return m().createElement(t.Component,{model:t})}constructor({item:e,headerActions:t,displayAllValues:n,legendPlacement:r,data:i,overrides:a,annotations:s,includeExemplars:l}){let c={};if(On.g.exemplars)if(l){const e=t;t=t=>[...e(t),new Pn(!0)]}else c={showExemplars:!1};super({key:"timeseries-label-values",item:e,headerActions:t,displayAllValues:Boolean(n),legendPlacement:r||"bottom",overrides:a,annotations:s,body:o.d0.timeseries().setTitle(e.label).setData(i||new o.Es({$data:hn(e.queryRunnerParams,n?void 0:_n.MAX_TIMESERIES_LABEL_VALUES,s,l&&On.g.exemplars),transformations:[gn,bn]})).setHeaderActions(t(e)).setMenu(new Kn(c)).build()}),this.addActivationHandler(this.onActivate.bind(this))}}function Zn(e,t){switch(e){case an.BARGAUGE:return new yn(t);case an.TABLE:return new Sn(t);case an.HISTOGRAM:return new En(t);case an.TIMESERIES:default:return new Yn(t)}}var Xn=n(1792);const Jn=n.p+"944c737f589d02ecf603.svg",Qn=n.p+"e79edcfbe2068fae2364.svg",er=(e=50)=>{const[t,n]=(0,p.useState)({x:null,y:null});return(0,p.useEffect)((()=>{const t=(0,g.throttle)((e=>{n({x:e.clientX,y:e.clientY})}),e);return window.addEventListener("mousemove",t),()=>{window.removeEventListener("mousemove",t)}}),[e]),t},tr=({width:e="auto",height:t,show404:n=!1})=>{const r=(0,i.useTheme2)(),{x:o,y:a}=er(),s=(0,i.useStyles2)(nr,o,a,n);return m().createElement(Xn.A,{src:r.isDark?Jn:Qn,className:s.svg,height:t,width:e})};tr.displayName="GrotNotFound";const nr=(e,t,n,o)=>{const{innerWidth:i,innerHeight:a}=window,s=n&&n/a,l=t&&t/i,c=null!==s?rr(s,-20,5):0,u=null!==l?rr(l,-5,5):0;return{svg:(0,r.css)({"#grot-404-arm, #grot-404-magnifier":{transform:`rotate(${c}deg) translateX(${u}%)`,transformOrigin:"center",transition:"transform 50ms linear"},"#grot-404-text":{display:o?"block":"none"}})}},rr=(e,t,n)=>e*(n-t)+t,or=({message:e})=>{const t=(0,i.useStyles2)(ir);return m().createElement("div",{className:t.container},m().createElement(i.Box,{paddingY:8},m().createElement(i.Stack,{direction:"column",alignItems:"center",gap:3},m().createElement(tr,{width:300}),m().createElement(i.Text,{variant:"h5"},e))))};function ir(){return{container:(0,r.css)({width:"100%",display:"flex",justifyContent:"space-evenly",flexDirection:"column"})}}or.displayName="EmptyState";class ar extends o.Bs{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(ar,"Component",(({model:e})=>{const{message:t}=e.useState();return m().createElement(or,{message:t})}));class sr extends o.Bs{}function lr(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(sr,"Component",(({model:e})=>{const{message:t}=e.useState();return m().createElement(i.Alert,{title:"Query error!",severity:"error"},t)}));var cr=function(e){return e.GRID="grid",e.ROWS="rows",e}({});class ur extends o.Bs{getUrlState(){return{layout:this.state.layout}}updateFromUrl(e){const t={};"string"==typeof e.layout&&e.layout!==this.state.layout&&(t.layout=Object.values(cr).includes(e.layout)?e.layout:ur.DEFAULT_LAYOUT),this.setState(t)}constructor(){super({key:"layout-switcher",layout:ur.DEFAULT_LAYOUT}),lr(this,"_urlSync",new o.So(this,{keys:["layout"]})),lr(this,"onChange",(e=>{(0,d.r)("g_pyroscope_app_layout_changed",{layout:e}),this.setState({layout:e})}))}}function dr(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}lr(ur,"OPTIONS",[{label:"Grid",value:"grid"},{label:"Rows",value:"rows"}]),lr(ur,"DEFAULT_LAYOUT","grid"),lr(ur,"Component",(({model:e})=>{const{layout:t}=e.useState();return m().createElement(i.RadioButtonGroup,{"aria-label":"Layout switcher",options:ur.OPTIONS,value:t,onChange:e.onChange,fullWidth:!1})}));class pr extends o.Bs{getUrlState(){return{hideNoData:this.state.hideNoData}}updateFromUrl(e){const t={};"string"==typeof e.hideNoData&&e.hideNoData!==this.state.hideNoData&&(t.hideNoData=["on","off"].includes(e.hideNoData)?e.hideNoData:pr.DEFAULT_VALUE),this.setState(t)}constructor(){super({key:"no-data-switcher",hideNoData:pr.DEFAULT_VALUE}),dr(this,"_urlSync",new o.So(this,{keys:["hideNoData"]})),dr(this,"onChange",(e=>{(0,d.r)("g_pyroscope_app_hide_no_data_changed",{hideNoData:e}),this.setState({hideNoData:e})}))}}function mr(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}dr(pr,"DEFAULT_VALUE","off"),dr(pr,"Component",(({model:e})=>{const{hideNoData:t}=e.useState();return m().createElement(i.InlineSwitch,{"data-testid":"noDataSwitcher",showLabel:!0,label:"Hide panels without data",value:"on"===t,onChange:t=>e.onChange(t.target.checked?"on":"off")})}));class fr extends o.Bs{setPlaceholder(e){this.setState({placeholder:e})}setResultsCount(e){this.setState({resultsCount:String(e)})}getUrlState(){return{searchText:this.state.searchText}}updateFromUrl(e){const t={};"string"==typeof e.searchText&&e.searchText!==this.state.searchText&&(t.searchText=e.searchText),this.setState(t)}reset(){this.setState({placeholder:"",searchText:"",resultsCount:""})}constructor({placeholder:e}){super({key:"quick-filter",placeholder:e,searchText:fr.DEFAULT_SEARCH_TEXT,resultsCount:""}),mr(this,"_urlSync",new o.So(this,{keys:["searchText"]})),mr(this,"onChange",(e=>{this.setState({searchText:e.target.value})})),mr(this,"clearSearchText",(()=>{this.setState({searchText:""})})),mr(this,"onFocus",(()=>{(0,d.r)("g_pyroscope_app_quick_filter_focused")}))}}mr(fr,"DEFAULT_SEARCH_TEXT",""),mr(fr,"DEBOUNCE_DELAY",250),mr(fr,"Component",(({model:e})=>{const t=(0,i.useStyles2)(hr),{placeholder:n,searchText:r,resultsCount:o}=e.useState();return m().createElement(i.Input,{type:"text",className:"quick-filter","aria-label":"Quick filter",placeholder:n,value:r,prefix:m().createElement(i.Icon,{name:"search"}),suffix:m().createElement(m().Fragment,null,""!==o&&m().createElement(i.Tag,{className:t.resultsCount,name:o,colorIndex:9,"data-testid":"quick-filter-results-count"}),m().createElement(i.IconButton,{name:"times","aria-label":"Clear search",onClick:e.clearSearchText})),onChange:e.onChange,onKeyDown:t=>{"Escape"===t.key&&e.clearSearchText()},onFocus:e.onFocus})}));const hr=e=>({resultsCount:r.css`
margin-right: ${e.spacing(1)};
border-radius: 11px;
padding: 2px 8px;
color: ${e.colors.text.primary};
background-color: ${e.colors.background.secondary};
`});function gr(e){const t=(0,At.y)(e);return`${t.type} (${t.group})`}function br(e,t,n,r,o,i,a){try{var s=e[i](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function yr(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var i=e.apply(t,n);function a(e){br(i,r,o,a,s,"next",e)}function s(e){br(i,r,o,a,s,"throw",e)}a(void 0)}))}}function vr(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Er(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter((function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable})))),r.forEach((function(t){vr(e,t,n[t])}))}return e}class Sr extends o.UU{static getAllFavorites(){var e;return(null===(e=Bt.x.get(Bt.x.KEYS.PROFILES_EXPLORER))||void 0===e?void 0:e.favorites)||[]}static areFavoritesEqual(e,t){return e.panelType===t.panelType&&(0,g.isEqual)(e.queryRunnerParams,t.queryRunnerParams)}static exists(e){return Sr.getAllFavorites().some((t=>Sr.areFavoritesEqual(t,e)))}static addFavorite(e){const t=Bt.x.get(Bt.x.KEYS.PROFILES_EXPLORER);t.favorites.push(e),Bt.x.set(Bt.x.KEYS.PROFILES_EXPLORER,t)}static removeFavorite(e){const t=Bt.x.get(Bt.x.KEYS.PROFILES_EXPLORER);t.favorites=t.favorites.filter((t=>!Sr.areFavoritesEqual(t,e))),Bt.x.set(Bt.x.KEYS.PROFILES_EXPLORER,t)}query(){return yr((function*(){return{state:f.LoadingState.Done,data:[{name:"Favories",fields:[{name:null,type:f.FieldType.other,values:[],config:{}}],length:0}]}}))()}metricFindQuery(){return yr((function*(){return Sr.getAllFavorites().map((e=>{const{serviceName:t,profileMetricId:n,groupBy:r,filters:o}=e.queryRunnerParams||{},i=[t,gr(n)];return(null==r?void 0:r.label)&&i.push(r.label),(null==o?void 0:o.length)&&i.push(o.map((({key:e,operator:t,value:n})=>`${e}${t}"${n}"`)).join(", ")),{value:JSON.stringify(Er({value:JSON.stringify(e)},e)),text:i.join(" · ")}}))}))()}testDatasource(){return yr((function*(){return{status:"success",message:"OK"}}))()}constructor(){var e;super(Rt.type,Rt.uid);const t=Bt.x.get(Bt.x.KEYS.PROFILES_EXPLORER)||{};(e=t).favorites||(e.favorites=[]),t.favorites=t.favorites.map((e=>Er({panelType:an.TIMESERIES},e))),Bt.x.set(Bt.x.KEYS.PROFILES_EXPLORER,t)}}function wr(e,t){const{queryRunnerParams:n}=t,r=(0,g.defaults)((0,g.clone)(n),{serviceName:rn(e,"serviceName"),profileMetricId:rn(e,"profileMetricId")}),i=o.jh.lookupVariable("filters",e).state.filters.map((({key:e,operator:t,value:n})=>({key:e,operator:t,value:n})));return r.filters=(0,g.uniqBy)([...r.filters||[],...i],(({key:e,operator:t,value:n})=>`${e}${t}${n}`)),r}function Or(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class xr extends o.Bs{update(){this.setState({isFav:this.isStored()})}isStored(){return Sr.exists(this.buildFavorite())}static buildFavorite(e){var t;const{index:n,queryRunnerParams:r,panelType:o}=e,i={index:n,queryRunnerParams:{serviceName:r.serviceName,profileMetricId:r.profileMetricId},panelType:o};return r.groupBy&&(i.queryRunnerParams.groupBy={label:r.groupBy.label}),(null===(t=r.filters)||void 0===t?void 0:t.length)&&(i.queryRunnerParams.filters=r.filters),i}buildFavorite(){const{item:e,skipVariablesInterpolation:t}=this.state;return xr.buildFavorite({index:e.index,queryRunnerParams:t?e.queryRunnerParams:wr(this,e),panelType:e.panelType})}constructor(e){super(e),Or(this,"_variableDependency",new o.Sh(this,{variableNames:["serviceName","profileMetricId","filters"],onReferencedVariableValueChanged:()=>{this.update()}})),Or(this,"onClick",(()=>{(0,d.r)("g_pyroscope_app_fav_action_clicked",{favAfterClick:!this.state.isFav}),this.state.isFav?Sr.removeFavorite(this.buildFavorite()):Sr.addFavorite(this.buildFavorite()),this.setState({isFav:!this.state.isFav})})),this.addActivationHandler((()=>this.update()))}}Or(xr,"Component",(({model:e})=>{const t=(0,i.useStyles2)(Pr),{isFav:n}=e.useState();return m().createElement(i.IconButton,{className:n?t.favedButton:t.notFavedbutton,name:n?"favorite":"star",variant:"secondary",size:"sm","aria-label":n?"Unfavorite":"Favorite",tooltip:n?"Unfavorite":"Favorite",tooltipPlacement:"top",onClick:e.onClick})}));const Pr=()=>({favedButton:r.css`
color: #f2cc0d;
margin: 0;
`,notFavedbutton:r.css`
margin: 0;
`}),Cr=function(e,t){const n=Sr.exists(xr.buildFavorite(e)),r=Sr.exists(xr.buildFavorite(t));return n&&r?Je(e.label,t.label):r?1:n?-1:0},Tr="240px";class Ar extends o.Bs{static buildGridItemKey(e){return`grid-item-${e.index}-${e.value}`}static getGridColumnsTemplate(e){return e===cr.ROWS?"1fr":"repeat(auto-fit, minmax(400px, 1fr))"}onActivate(){const e=o.jh.lookupVariable(this.state.variableName,this),t=e.subscribeToState(((e,t)=>{!e.loading&&t.loading&&this.renderGridItems()}));e.update();const n=this.subscribeToQuickFilterChange(),r=this.subscribeToLayoutChange(),i=this.subscribeToHideNoDataChange(),a=this.subscribeToFiltersChange();return()=>{a.unsubscribe(),i.unsubscribe(),r.unsubscribe(),n.unsubscribe(),t.unsubscribe()}}subscribeToQuickFilterChange(){const e=o.jh.findByKeyAndType(this,"quick-filter",fr);this.subscribeToState(((t,n)=>{t.items.length!==n.items.length&&e.setResultsCount(t.items.length)}));return e.subscribeToState((0,g.debounce)(((e,t)=>{e.searchText!==(null==t?void 0:t.searchText)&&this.renderGridItems()}),fr.DEBOUNCE_DELAY))}subscribeToLayoutChange(){const e=o.jh.findByKeyAndType(this,"layout-switcher",ur),t=this.state.body,n=(e,n)=>{e.layout!==(null==n?void 0:n.layout)&&t.setState({templateColumns:Ar.getGridColumnsTemplate(e.layout)})};return n(e.state),e.subscribeToState(n)}subscribeToHideNoDataChange(){const e=o.jh.findByKeyAndType(this,"no-data-switcher",pr);if(!e.isActive)return this.setState({hideNoData:!1}),{unsubscribe:h.f};const t=(e,t)=>{e.hideNoData!==(null==t?void 0:t.hideNoData)&&(this.setState({hideNoData:"on"===e.hideNoData}),this.renderGridItems(!0))};return t(e.state),e.subscribeToState(t)}subscribeToFiltersChange(){const e=o.jh.findByKeyAndType(this,"filters",nn),t=o.jh.findByKeyAndType(this,"no-data-switcher",pr);return e.subscribeToState((()=>{"on"===t.state.hideNoData&&this.renderGridItems(!0)}))}buildItemsData(e){const{mapOptionToItem:t}=this.state,n={serviceName:rn(this,"serviceName"),profileMetricId:rn(this,"profileMetricId"),panelType:o.jh.findByKeyAndType(this,"panel-type-switcher",sn).state.panelType},r=e.state.options.map(((e,r)=>t(e,r,n))).filter(Boolean);return this.filterItems(r).sort(this.state.sortItemsFn)}shouldRenderItems(e){const{items:t}=this.state;return!e.length||t.length!==e.length||!(0,g.isEqual)(t,e)}renderGridItems(e=!1){const t=o.jh.lookupVariable(this.state.variableName,this);if(t.state.loading)return;if(t.state.error)return void this.renderErrorState(t.state.error);const n=this.buildItemsData(t);if(!e&&!this.shouldRenderItems(n))return;if(this.setState({items:n}),!this.state.items.length)return void this.renderEmptyState();const r=this.state.items.map((e=>{const t=Zn(e.panelType,{item:e,headerActions:this.state.headerActions.bind(null,e,this.state.items)});return this.state.hideNoData&&this.setupHideNoData(t),new o.xK({key:Ar.buildGridItemKey(e),body:t})}));this.state.body.setState({autoRows:Tr,children:r})}setupHideNoData(e){const t=e.subscribeToEvent(b,(t=>{var n;if(null===(n=t.payload.series)||void 0===n?void 0:n.length)return;const r=o.jh.getAncestor(e,o.xK),{key:i}=r.state,a=o.jh.getAncestor(r,o.gF),s=a.state.children.filter((e=>e.state.key!==i));s.length?a.setState({children:s}):this.renderEmptyState()}));e.addActivationHandler((()=>()=>{t.unsubscribe()}))}filterItems(e){const t=o.jh.findByKeyAndType(this,"quick-filter",fr),{searchText:n}=t.state;if(!n)return e;const r=n.split(",").map((e=>e.trim())).filter(Boolean).map((e=>{try{return new RegExp(e)}catch(e){return null}})).filter(Boolean);return e.filter((({label:e})=>r.some((t=>t.test(e)))))}renderEmptyState(){this.state.body.setState({autoRows:"480px",children:[new o.xK({body:new ar({message:"No results"})})]})}renderErrorState(e){this.state.body.setState({autoRows:"480px",children:[new o.xK({body:new sr({message:e.message||e.toString()})})]})}static Component({model:e}){var t;const{body:n,variableName:r}=e.useState(),{loading:a}=null===(t=o.jh.lookupVariable(r,e))||void 0===t?void 0:t.useState();return a?m().createElement(i.Spinner,null):m().createElement(n.Component,{model:n})}constructor({key:e,variableName:t,headerActions:n,mapOptionToItem:r,sortItemsFn:i}){super({key:e,variableName:t,items:[],headerActions:n,mapOptionToItem:r,sortItemsFn:i||Cr,hideNoData:!1,body:new o.gF({templateColumns:Ar.getGridColumnsTemplate(ur.DEFAULT_LAYOUT),autoRows:Tr,isLazy:!0,$behaviors:[new o.Gg.K2({key:"metricCrosshairSync",sync:f.DashboardCursorSync.Crosshair})],children:[]})}),this.addActivationHandler(this.onActivate.bind(this))}}class jr extends f.BusEventWithPayload{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(jr,"type","expand-panel");class kr extends f.BusEventWithPayload{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(kr,"type","select-label");class Nr extends f.BusEventWithPayload{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(Nr,"type","view-service-flame-graph");class Rr extends f.BusEventWithPayload{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(Rr,"type","view-service-labels");class Ir extends f.BusEventWithPayload{}function _r(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Dr(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter((function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable})))),r.forEach((function(t){_r(e,t,n[t])}))}return e}function Lr(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))})),e}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(Ir,"type","view-service-profiles");const Fr=new Map([["expand-panel",Object.freeze({ariaLabel:"Expand panel",icon:"expand-arrows",tooltip:()=>"Expand this panel to view all the data for the current filters",EventConstructor:jr})],["select-label",Object.freeze({label:"Select",tooltip:({queryRunnerParams:e})=>{var t;return`View "${null===(t=e.groupBy)||void 0===t?void 0:t.label}" values breakdown`},EventConstructor:kr})],["view-flame-graph",Object.freeze({label:"Flame graph",tooltip:({queryRunnerParams:e},t)=>{const n=e.serviceName||rn(t,"serviceName"),r=e.profileMetricId||rn(t,"profileMetricId");return`View the "${(0,At.y)(r).type}" flame graph of ${n}`},EventConstructor:Nr})],["view-labels",Object.freeze({label:"Labels",tooltip:({queryRunnerParams:e},t)=>`Explore the labels of ${e.serviceName||rn(t,"serviceName")}`,EventConstructor:Rr})],["view-profiles",Object.freeze({label:"Profile types",tooltip:({queryRunnerParams:e},t)=>`View the profile types of ${e.serviceName||rn(t,"serviceName")}`,EventConstructor:Ir})]]);class Br extends o.Bs{buildEvent(){const{EventConstructor:e,item:t,skipVariablesInterpolation:n}=this.state;return new e({item:Lr(Dr({},t),{queryRunnerParams:n?t.queryRunnerParams:wr(this,t)})})}constructor({type:e,item:t,tooltip:n,skipVariablesInterpolation:r}){const o=Fr.get(e);if(!o)throw new TypeError(`Unknown event type="${e}"!`);super(Dr({type:e,item:t},(0,g.merge)({},o,{tooltip:n,skipVariablesInterpolation:r}))),_r(this,"onClick",(()=>{(0,d.r)("g_pyroscope_app_select_action_clicked",{type:this.state.type}),this.publishEvent(this.buildEvent(),!0)}))}}_r(Br,"Component",(({model:e})=>{const t=(0,i.useStyles2)($r),{ariaLabel:n,label:r,icon:o,tooltip:a,item:s}=e.useState();return m().createElement(i.Button,{className:t.selectButton,"aria-label":n||r,variant:"primary",size:"sm",fill:"text",onClick:e.onClick,icon:o,tooltip:null==a?void 0:a(s,e),tooltipPlacement:"top"},r)}));const $r=()=>({selectButton:r.css`
margin: 0;
padding: 0;
`});class Mr extends o.Bs{onActivate(){o.jh.findByKeyAndType(this,"quick-filter",fr).setPlaceholder("Search services (comma-separated regexes are supported)")}getVariablesAndGridControls(){return{variables:[o.jh.findByKeyAndType(this,"profileMetricId",Lt)],gridControls:[o.jh.findByKeyAndType(this,"quick-filter",fr),o.jh.findByKeyAndType(this,"layout-switcher",ur)]}}static Component({model:e}){const{body:t}=e.useState();return m().createElement(t.Component,{model:t})}constructor(){super({key:"explore-all-services",$variables:new o.Pj({variables:[new Vt({query:Vt.QUERY_PROFILE_METRIC_DEPENDENT,skipUrlSync:!0})]}),body:new Ar({key:"all-services-grid",variableName:"serviceName",mapOptionToItem:(e,t,{profileMetricId:n})=>({index:t,value:e.value,label:e.label,queryRunnerParams:{serviceName:e.value,profileMetricId:n},panelType:an.TIMESERIES}),headerActions:e=>[new Br({type:"view-profiles",item:e}),new Br({type:"view-labels",item:e}),new Br({type:"view-flame-graph",item:e}),new xr({item:e})]})}),this.addActivationHandler(this.onActivate.bind(this))}}function Vr(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Ur(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter((function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable})))),r.forEach((function(t){Vr(e,t,n[t])}))}return e}function Gr(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))})),e}class qr extends o.Bs{constructor(e){super(Ur({key:"drawer",isOpen:!1},e)),Vr(this,"open",(({title:e,subTitle:t,body:n})=>{this.setState(Gr(Ur({},this.state),{isOpen:!0,title:e,subTitle:t,body:n}))})),Vr(this,"close",(()=>{this.setState({isOpen:!1})}))}}function Kr(e,t,n,r,o,i,a){try{var s=e[i](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}Vr(qr,"Component",(({model:e})=>{const{isOpen:t,title:n,subTitle:r,body:o}=e.useState();return m().createElement(m().Fragment,null,o&&t&&m().createElement(i.Drawer,{size:"lg",title:n,subtitle:r,closeOnMaskClick:!0,onClose:e.close},m().createElement(o.Component,{model:o})))}));class zr extends o.fS{update(){var e,t=this;return(e=function*(){if(t.state.loading)return;let e=[],n=null;t.setState({loading:!0,options:[],error:null});try{e=yield(0,jt.lastValueFrom)(t.getValueOptions({}))}catch(e){n=e}finally{t.setState({loading:!1,options:e,error:n})}},function(){var t=this,n=arguments;return new Promise((function(r,o){var i=e.apply(t,n);function a(e){Kr(i,r,o,a,s,"next",e)}function s(e){Kr(i,r,o,a,s,"throw",e)}a(void 0)}))})()}constructor(){super({name:"favorite",label:"🔖 Favorite",datasource:Rt,query:"$dataSource",loading:!0,refresh:f.VariableRefresh.never,skipUrlSync:!0})}}function Wr(e,t,n,r,o,i,a){try{var s=e[i](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}class Hr extends o.Bs{onActivate(){o.jh.findByKeyAndType(this,"quick-filter",fr).setPlaceholder("Search favorites (comma-separated regexes are supported)");var e=this;const t=this.subscribeToEvent(jr,function(){var t,n=(t=function*(t){e.openExpandedPanelDrawer(t.payload.item)},function(){var e=this,n=arguments;return new Promise((function(r,o){var i=t.apply(e,n);function a(e){Wr(i,r,o,a,s,"next",e)}function s(e){Wr(i,r,o,a,s,"throw",e)}a(void 0)}))});return function(e){return n.apply(this,arguments)}}());return()=>{t.unsubscribe()}}getVariablesAndGridControls(){return{variables:[],gridControls:[o.jh.findByKeyAndType(this,"quick-filter",fr),o.jh.findByKeyAndType(this,"layout-switcher",ur),o.jh.findByKeyAndType(this,"no-data-switcher",pr)]}}openExpandedPanelDrawer(e){this.state.drawer.open({title:e.label,body:Zn(e.panelType,{displayAllValues:!0,legendPlacement:"right",item:e,headerActions:()=>[new Br({type:"view-labels",item:e}),new Br({type:"view-flame-graph",item:e})]})})}static Component({model:e}){const{body:t,drawer:n}=e.useState();return m().createElement(m().Fragment,null,m().createElement(t.Component,{model:t}),m().createElement(n.Component,{model:n}))}constructor(){super({key:"explore-favorites",$variables:new o.Pj({variables:[new zr]}),body:new Ar({key:"favorites-grid",variableName:"favorite",mapOptionToItem:e=>{const{index:t,value:n,panelType:r,queryRunnerParams:o}=JSON.parse(e.value);return{index:t,value:n,label:e.label,queryRunnerParams:o,panelType:r}},sortItemsFn:(e,t)=>Je(e.label,t.label),headerActions:e=>{const t=[new Br({type:"view-labels",item:e,skipVariablesInterpolation:!0}),new Br({type:"view-flame-graph",item:e,skipVariablesInterpolation:!0})];return e.queryRunnerParams.groupBy&&t.push(new Br({type:"expand-panel",item:e,tooltip:()=>"Expand panel to view all the data",skipVariablesInterpolation:!0})),t.push(new xr({item:e,skipVariablesInterpolation:!0})),t}}),drawer:new qr}),this.addActivationHandler(this.onActivate.bind(this))}}var Yr=n(5540);function Zr({options:e,mainLabels:t,value:n,onChange:r,onRefresh:o}){const a=(0,i.useStyles2)(Xr),s=(0,i.useTheme2)(),[l,c]=(0,p.useState)(0),[u,d]=(0,p.useState)(0),f=u>l,g=(0,p.useRef)(null);(0,Yr.w)({ref:g,onResize:()=>{const e=g.current;e&&d(e.clientWidth)}});const b=e.filter((e=>t.includes(e.value))),y=e.filter((e=>!t.includes(e.value)));return(0,p.useEffect)((()=>{const{fontSize:e}=s.typography,t=b.map((e=>e.label||e.text||"")).join(" "),n=(0,i.measureText)(t,e).width;c(n+70*b.length)}),[b,s]),m().createElement(i.Field,{label:"Group by labels"},m().createElement("div",{ref:g,className:a.container},f?m().createElement(m().Fragment,null,m().createElement(i.RadioButtonGroup,{"aria-label":"Labels selector",options:b,value:n,onChange:r}),m().createElement(i.Select,{"aria-label":"Other labels selector",className:a.select,placeholder:"Other labels",options:y,value:n&&y.some((e=>e.value===n))?n:null,onChange:e=>{var t;return r(null!==(t=null==e?void 0:e.value)&&void 0!==t?t:"all")},isClearable:!0})):m().createElement(i.Select,{"aria-label":"Labels selector",className:a.select,value:n,placeholder:"Select label",options:e,onChange:e=>r((null==e?void 0:e.value)||to.DEFAULT_VALUE),isClearable:!0}),m().createElement(i.RefreshPicker,{noIntervalPicker:!0,onRefresh:o,isOnCanvas:!1,onIntervalChanged:h.f,tooltip:"Click to refresh all labels"})))}const Xr=e=>({container:r.css`
display: flex;
gap: ${e.spacing(1)};
`,select:r.css`
max-width: ${e.spacing(22)};
`});function Jr(e,t,n,r,o,i,a){try{var s=e[i](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function Qr(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var i=e.apply(t,n);function a(e){Jr(i,r,o,a,s,"next",e)}function s(e){Jr(i,r,o,a,s,"throw",e)}a(void 0)}))}}function eo(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class to extends o.fS{onActivate(){this.state.value||this.setState({value:to.DEFAULT_VALUE})}findCurrentOption(){const{value:e}=this.state,t=this.state.options.filter((e=>"all"!==e.value)).find((t=>JSON.parse(t.value).value===e));if(t){const e=JSON.parse(t.value);return{index:e.index,value:e.value,label:e.value,groupBy:e.groupBy}}return{index:0,value:e,label:e,groupBy:void 0}}constructor(){var e;super({key:"groupBy",name:"groupBy",label:"Group by labels",datasource:It,query:'$dataSource and $profileMetricId{service_name="$serviceName"}',loading:!0}),e=this,eo(this,"update",Qr((function*(){if(e.state.loading)return;let t=[],n=null;e.setState({loading:!0,options:[],error:null});try{t=yield(0,jt.lastValueFrom)(e.getValueOptions({}))}catch(e){n=e}finally{e.setState({loading:!1,options:t,error:n})}}))),eo(this,"onChange",(e=>{(0,d.r)("g_pyroscope_app_group_by_label_clicked"),s(),this.changeValueTo(e)})),this.changeValueTo=this.changeValueTo.bind(this),this.addActivationHandler(this.onActivate.bind(this))}}eo(to,"DEFAULT_VALUE","all"),eo(to,"MAX_MAIN_LABELS",8),eo(to,"Component",(({model:e})=>{const t=(0,i.useStyles2)(no),{loading:n,value:r,options:o,error:a}=e.useState(),s=(0,p.useMemo)((()=>o.map((({label:e,value:t})=>"all"===t?{label:e,value:t}:{label:e,value:JSON.parse(String(t)).value}))),[o]);if(n)return m().createElement(i.Field,{label:"Group by labels"},m().createElement(i.Spinner,{className:t.spinner}));if(a)return m().createElement(i.Field,{label:"Group by labels"},m().createElement("div",{className:t.groupByErrorContainer},m().createElement(i.Tooltip,{theme:"error",content:a.toString()},m().createElement(i.Icon,{className:t.iconError,name:"exclamation-triangle",size:"xl"})),m().createElement(i.RefreshPicker,{noIntervalPicker:!0,onRefresh:e.update,isOnCanvas:!1,onIntervalChanged:h.f})));return m().createElement(Zr,{options:s,value:r,mainLabels:(e=>e.slice(0,to.MAX_MAIN_LABELS).map((({value:e})=>e)))(s),onChange:e.onChange,onRefresh:e.update})}));const no=e=>({spinner:r.css`
height: 32px;
line-height: 32px;
`,groupByErrorContainer:r.css`
display: flex;
`,iconError:r.css`
height: 32px;
align-self: center;
color: ${e.colors.error.text};
`});class ro extends o.Bs{onActivate(e,t,n){e&&this.initVariables(e),this.setState({body:this.buildTimeseries(e,t,n)}),t&&this.subscribeToGroupByStateChanges(e);const r=o.jh.findByKeyAndType(this,"serviceName",Vt),i=o.jh.findByKeyAndType(this,"profileMetricId",Lt);this._subs.add(r.subscribeToState(((e,t)=>{(null==e?void 0:e.value)!==(null==t?void 0:t.value)&&this.resetTimeseries(!0)}))),this._subs.add(i.subscribeToState(((e,t)=>{(null==e?void 0:e.value)!==(null==t?void 0:t.value)&&this.resetTimeseries(!1)})))}initVariables(e){const{serviceName:t,profileMetricId:n,filters:r}=e.queryRunnerParams;if(t){o.jh.findByKeyAndType(this,"serviceName",Vt).changeValueTo(t)}if(n){o.jh.findByKeyAndType(this,"profileMetricId",Lt).changeValueTo(n)}if(r){o.jh.findByKeyAndType(this,"filters",nn).setState({filters:r})}}buildTimeseries(e,t,n){const{headerActions:r}=this.state,i={index:0,value:"",queryRunnerParams:{},label:this.buildTitle(),panelType:an.TIMESERIES};e&&t&&(i.queryRunnerParams.groupBy=e.queryRunnerParams.groupBy);const a=o.jh.findByKeyAndType(this,"groupBy",to).state.value;return new Yn({item:i,headerActions:r,annotations:!0,includeExemplars:n,data:!e&&t&&a&&"all"!==a?new o.Es({$data:new o.dt({datasource:kt,queries:[]}),transformations:[gn,bn]}):void 0})}subscribeToGroupByStateChanges(e){const t=o.jh.findByKeyAndType(this,"groupBy",to);this._subs.add(t.subscribeToState(((n,r)=>{!n.loading&&n.options.length&&(e||!r.loading?n.value!==r.value&&this.onGroupByChanged(t):this.onGroupByChanged(t))})))}onGroupByChanged(e){var t;if(!e.state.value||"all"===e.state.value)return void this.resetTimeseries();const{index:n,value:r,groupBy:o}=e.findCurrentOption();null===(t=this.state.body)||void 0===t||t.updateItem({index:n,label:`${this.buildTitle()}, grouped by ${r}`,queryRunnerParams:{groupBy:o}})}resetTimeseries(e=!1){var t;e&&o.jh.findByKeyAndType(this,"filters",nn).reset(),null===(t=this.state.body)||void 0===t||t.updateItem({index:0,label:this.buildTitle(),queryRunnerParams:{groupBy:void 0}})}buildTitle(){const e=rn(this,"profileMetricId"),{description:t}=(0,At.y)(e);return t||gr(e)}static Component({model:e}){const{body:t}=e.useState();return t&&m().createElement(t.Component,{model:t})}constructor({item:e,headerActions:t,supportGroupBy:n,includeExemplars:r}){super({headerActions:t,body:void 0}),this.addActivationHandler(this.onActivate.bind(this,e,n,r))}}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(ro,"MIN_HEIGHT",240);class oo extends f.BusEventWithPayload{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(oo,"type","view-diff-flame-graph");var io=n(9897);class ao extends f.BusEventWithPayload{}function so({option:e,checked:t,onChange:n}){var o;const a=(0,i.useStyles2)(lo),[s,l]=(0,p.useState)(!1),c=(0,p.useRef)(null),u=null===(o=c.current)||void 0===o?void 0:o.closest("label");return(0,p.useEffect)((()=>{if(!u||t)return void l(!1);const e=()=>{l(!0)},n=()=>{l(!1)};return u.addEventListener("mouseenter",e),u.addEventListener("mouseleave",n),()=>{u.removeEventListener("mouseleave",n),u.removeEventListener("mouseenter",e)}}),[t,u]),m().createElement(m().Fragment,null,m().createElement(i.Tooltip,{content:e.description,show:!t&&s,placement:"top"},m().createElement("span",{className:a.tooltipAnchor})),m().createElement(i.Checkbox,{ref:c,className:(0,r.cx)(a.checkbox,"checkbox",t&&"checked"),checked:t,label:e.label,onChange:()=>n(e.value)}))}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(ao,"type","select-for-compare");const lo=e=>({tooltipAnchor:r.css`
position: relative;
left: 42px;
`,checkbox:r.css`
column-gap: 4px;
&:last-child {
& :nth-child(1) {
grid-column-start: 2;
}
& :nth-child(2) {
grid-column-start: 1;
}
}
span {
color: ${e.colors.text.secondary};
}
span:hover {
color: ${e.colors.text.primary};
}
&.checked span {
color: ${e.colors.text.primary};
}
`});function co({item:e,itemStats:t,statsDescription:n,compareActionChecks:r,onChangeCompareTarget:o}){const a=(0,i.useStyles2)(uo),{index:s,value:l}=e,c=cn(s),u=(0,p.useMemo)((()=>{if(!t)return m().createElement(i.Spinner,{inline:!0});const{allValuesSum:e,unit:n}=t,{text:r,suffix:o}=(0,f.getValueFormat)(n)(e);return`${r}${o}`}),[t]),d=(0,p.useMemo)((()=>[{label:"Baseline",value:io.N.BASELINE,description:r[0]?"":`Click to select "${l}" as baseline for comparison`},{label:"Comparison",value:io.N.COMPARISON,description:r[1]?"":`Click to select "${l}" as target for comparison`}]),[r,l]);return m().createElement("div",{className:a.container,"data-testid":`stats-panel-${l}`},m().createElement("h1",{style:{color:c},className:a.title,title:`${n}: ${u}`},u),m().createElement("div",{className:a.compareActions},m().createElement(so,{option:d[0],checked:r[0],onChange:o}),m().createElement(so,{option:d[1],checked:r[1],onChange:o})))}const uo=e=>({container:r.css`
display: flex;
flex-direction: column;
justify-content: space-between;
width: 100%;
background-color: ${e.colors.background.canvas};
padding: ${e.spacing(1)};
border: 1px solid ${e.colors.border.weak};
border-right: none;
border-radius: 2px 0 0 2px;
`,title:r.css`
font-size: 24px;
width: 100%;
text-align: center;
margin-top: ${e.spacing(5)};
`,compareActions:r.css`
display: flex;
justify-content: space-between;
font-size: 11px;
border-top: 1px solid ${e.colors.border.weak};
padding: ${e.spacing(1)} 0 0 0;
& .checkbox:nth-child(2) {
padding-right: 4px;
border-right: 1px solid ${e.colors.border.strong};
}
& .checkbox:nth-child(4) {
padding-left: 4px;
}
`});function po(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class mo extends o.Bs{onActivate(){const e=o.jh.findByKeyAndType(this,"group-by-labels",No).getCompare();this.updateCompareActions(e.get(io.N.BASELINE),e.get(io.N.COMPARISON)),this.setState({statsDescription:this.getStatsDescription()})}updateCompareActions(e,t){const{item:n}=this.state;this.setState({compareActionChecks:[(null==e?void 0:e.value)===n.value,(null==t?void 0:t.value)===n.value]})}getStatsDescription(){const e=rn(this,"profileMetricId"),{description:t}=(0,At.y)(e);return t||gr(e)}getStats(){return this.state.itemStats}updateStats(e){this.setState({itemStats:e})}static Component({model:e}){const{item:t,itemStats:n,statsDescription:r,compareActionChecks:o}=e.useState();return m().createElement(co,{item:t,itemStats:n,statsDescription:r,compareActionChecks:o,onChangeCompareTarget:e.onChangeCompareTarget})}constructor({item:e}){super({item:e,itemStats:void 0,compareActionChecks:[!1,!1],statsDescription:""}),po(this,"onChangeCompareTarget",(e=>{this.publishEvent(new ao({compareTarget:e,item:this.state.item}),!0)})),this.addActivationHandler(this.onActivate.bind(this))}}po(mo,"WIDTH_IN_PIXELS",186);class fo extends o.Bs{static buildPanelKey(e){return`compare-panel-${e.value}`}onActivate(){const{statsPanel:e,timeseriesPanel:t}=this.state,n=t.subscribeToEvent(b,(t=>{var n,r;const o=null===(n=t.payload.series)||void 0===n?void 0:n[0];if(!o)return void e.updateStats({allValuesSum:0,unit:"short"});const i=dn(o,"allValuesSum")||0;(null===(r=e.getStats())||void 0===r?void 0:r.allValuesSum)!==i&&e.updateStats({allValuesSum:i,unit:o.fields[1].config.unit||"short"})}));return()=>{n.unsubscribe()}}static Component({model:e}){const t=(0,i.useStyles2)(ho),{statsPanel:n,timeseriesPanel:o}=e.useState(),{compareActionChecks:a}=n.useState(),s=a[0]||a[1];return m().createElement("div",{className:(0,r.cx)(t.container,s&&"selected")},m().createElement("div",{className:t.statsPanel},m().createElement(n.Component,{model:n})),m().createElement("div",{className:t.timeseriesPanel},m().createElement(o.Component,{model:o})))}constructor({item:e,headerActions:t}){super({key:"label-value-panel",statsPanel:new mo({item:e}),timeseriesPanel:new Yn({item:e,headerActions:t})}),this.addActivationHandler(this.onActivate.bind(this))}}const ho=e=>({container:r.css`
display: flex;
min-width: 0px;
min-height: ${bo};
flex-flow: row;
box-sizing: border-box;
border: 1px solid transparent;
&.selected {
border: 1px solid ${e.colors.primary.main};
}
& > div {
display: flex;
position: relative;
flex-direction: row;
align-self: stretch;
min-height: ${bo};
}
`,statsPanel:r.css`
width: ${mo.WIDTH_IN_PIXELS}px;
`,timeseriesPanel:r.css`
flex-grow: 1;
& [data-viz-panel-key] > * {
border-top-left-radius: 0;
border-bottom-left-radius: 0;
}
`});function go({label:e}){const t='service_name="$serviceName"';return new o.dt({datasource:kt,queries:[{refId:`$profileMetricId-${t}-${e}`,queryType:"metrics",profileTypeId:"$profileMetricId",labelSelector:`{${t}}`,groupBy:[e]}]})}const bo="160px";class yo extends o.Bs{static buildGridItemKey(e){return`grid-item-${e.index}-${e.value}`}onActivate(){this.subscribeOnceToDataChange();const e=this.subscribeToGroupByChange(),t=this.subscribeToRefreshClick(),n=this.subscribeToQuickFilterChange(),r=this.subscribeToLayoutChange(),o=this.subscribeToHideNoDataChange(),i=this.subscribeToFiltersChange();return()=>{i.unsubscribe(),o.unsubscribe(),r.unsubscribe(),n.unsubscribe(),t.unsubscribe(),e.unsubscribe()}}subscribeOnceToDataChange(e=!1){const t=this.state.$data.subscribeToState((n=>{var r;(null===(r=n.data)||void 0===r?void 0:r.state)!==f.LoadingState.Loading&&(t.unsubscribe(),this.renderGridItems(e),this.setState({isLoading:!1}))}))}subscribeToGroupByChange(){return o.jh.findByKeyAndType(this,"groupBy",to).subscribeToState(((e,t)=>{!e.loading&&t.loading&&this.refetchData()}))}subscribeToRefreshClick(){const e=()=>{this.refetchData()},t=document.querySelector('[data-testid="data-testid RefreshPicker run button"]');return t||be.v.error(new Error("SceneByVariableRepeaterGrid: Refresh button not found! The list of items will never be updated.")),null==t||t.addEventListener("click",e),null==t||t.setAttribute("title","Click to completely refresh all the panels present on the screen"),{unsubscribe(){null==t||t.removeAttribute("title"),null==t||t.removeEventListener("click",e)}}}subscribeToQuickFilterChange(){const e=o.jh.findByKeyAndType(this,"quick-filter",fr);this.subscribeToState(((t,n)=>{t.items.length!==n.items.length&&e.setResultsCount(t.items.length)}));return e.subscribeToState((0,g.debounce)(((e,t)=>{e.searchText!==(null==t?void 0:t.searchText)&&this.renderGridItems()}),fr.DEBOUNCE_DELAY))}subscribeToLayoutChange(){const e=o.jh.findByKeyAndType(this,"layout-switcher",ur),t=this.state.body,n=(e,n)=>{e.layout!==(null==n?void 0:n.layout)&&t.setState({templateColumns:e.layout===cr.ROWS?"1fr":"repeat(auto-fit, minmax(600px, 1fr))"})};return n(e.state),e.subscribeToState(n)}subscribeToHideNoDataChange(){const e=o.jh.findByKeyAndType(this,"no-data-switcher",pr);this.setState({hideNoData:"on"===e.state.hideNoData});return e.subscribeToState(((e,t)=>{e.hideNoData!==(null==t?void 0:t.hideNoData)&&(this.setState({hideNoData:"on"===e.hideNoData}),this.refetchData(!0))}))}subscribeToFiltersChange(){const e=o.jh.findByKeyAndType(this,"filters",nn),t=o.jh.findByKeyAndType(this,"no-data-switcher",pr);return e.subscribeToState((()=>{"on"===t.state.hideNoData&&this.refetchData()}))}refetchData(e=!1){this.setState({isLoading:!0,$data:new o.Es({$data:go({label:this.state.label}),transformations:[gn,bn]})}),this.subscribeOnceToDataChange(e)}shouldRenderItems(e){const{items:t}=this.state;return!e.length||t.length!==e.length||!(0,g.isEqual)(t,e)}buildItemsData(e){const t=rn(this,"serviceName"),n=rn(this,"profileMetricId"),{label:r,startColorIndex:o,sortItemsFn:i}=this.state,a=e.map(((e,i)=>{var a;const s=e.fields[1],l=(null===(a=s.labels)||void 0===a?void 0:a[r])||"",c=un(s,r);return{index:o+i,value:l,label:c,queryRunnerParams:{serviceName:t,profileMetricId:n,filters:[{key:r,operator:"=",value:l}]},panelType:an.TIMESERIES}}));return this.filterItems(a).sort(i)}renderGridItems(e=!1){if(!this.state.$data.state.data)return;const{state:t,series:n,errors:r}=this.state.$data.state.data;if(t===f.LoadingState.Loading)return;if(t===f.LoadingState.Error)return void this.renderErrorState(null==r?void 0:r[0]);const i=this.buildItemsData(n);if(!e&&!this.shouldRenderItems(i))return;if(this.setState({items:i}),!this.state.items.length)return void this.renderEmptyState();const a=i.map((e=>new o.xK({key:yo.buildGridItemKey(e),body:this.buildVizPanel(e)})));this.state.body.setState({autoRows:bo,children:a})}buildVizPanel(e){const t=new fo({item:e,headerActions:this.state.headerActions.bind(null,e,this.state.items)}),n=t.subscribeToEvent(b,(e=>{var n;if(!this.state.hideNoData||(null===(n=e.payload.series)||void 0===n?void 0:n.length))return;const r=o.jh.getAncestor(t,o.xK),{key:i}=r.state,a=o.jh.getAncestor(r,o.gF),s=a.state.children.filter((e=>e.state.key!==i));s.length?a.setState({children:s}):this.renderEmptyState()}));return t.addActivationHandler((()=>()=>{n.unsubscribe()})),t}filterItems(e){const t=o.jh.findByKeyAndType(this,"quick-filter",fr),{searchText:n}=t.state;if(!n)return e;const r=n.split(",").map((e=>e.trim())).filter(Boolean).map((e=>{try{return new RegExp(e)}catch(e){return null}})).filter(Boolean);return e.filter((({label:e})=>r.some((t=>t.test(e)))))}renderEmptyState(){this.state.body.setState({autoRows:"480px",children:[new o.xK({body:new ar({message:"No results"})})]})}renderErrorState(e){this.state.body.setState({autoRows:"480px",children:[new o.xK({body:new sr({message:e.message||e.toString()})})]})}static Component({model:e}){const{body:t,isLoading:n}=e.useState();return n?m().createElement(i.Spinner,null):m().createElement("div",{style:{marginBottom:"2px"}},m().createElement(t.Component,{model:t}))}constructor({key:e,label:t,startColorIndex:n,headerActions:r}){super({key:e,label:t,startColorIndex:n,items:[],isLoading:!0,$data:new o.Es({$data:go({label:t}),transformations:[gn,bn]}),hideNoData:!1,headerActions:r,sortItemsFn:Cr,body:new o.gF({templateColumns:"1fr",autoRows:bo,isLazy:!0,$behaviors:[new o.Gg.K2({key:"metricCrosshairSync",sync:f.DashboardCursorSync.Crosshair})],children:[]})}),this.addActivationHandler(this.onActivate.bind(this))}}class vo extends f.BusEventWithPayload{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(vo,"type","clear-label-from-filters");class Eo extends f.BusEventWithPayload{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(Eo,"type","exclude-label-from-filters");class So extends f.BusEventWithPayload{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(So,"type","include-label-in-filters");const wo=e=>{const t=(0,i.useStyles2)(xo),{include:n,exclude:o}=function({status:e,label:t,onInclude:n,onExclude:r,onClear:o}){const i="included"===e,a="excluded"===e;return{include:{isSelected:i,tooltip:i?`Clear "${t}" from the filters`:`Include "${t}" in the filters`,onClick:i?o:n},exclude:{isSelected:a,tooltip:a?`Clear "${t}" from the filters`:`Exclude "${t}" in the filters`,onClick:a?o:r}}}(e);return m().createElement("div",{className:t.container},m().createElement(i.Button,{size:"sm",fill:"outline",variant:n.isSelected?"primary":"secondary","aria-selected":n.isSelected,className:(0,r.cx)(t.includeButton,n.isSelected&&"selected"),onClick:n.onClick,tooltip:n.tooltip,tooltipPlacement:"top","data-testid":"filter-button-include"},"Include"),m().createElement(i.Button,{size:"sm",fill:"outline",variant:o.isSelected?"primary":"secondary","aria-selected":o.isSelected,className:(0,r.cx)(t.excludeButton,o.isSelected&&"selected"),onClick:o.onClick,tooltip:o.tooltip,tooltipPlacement:"top","data-testid":"filter-button-exclude"},"Exclude"))},Oo=(0,p.memo)(wo),xo=e=>({container:r.css`
display: flex;
justify-content: center;
`,includeButton:r.css`
border-radius: ${e.shape.radius.default} 0 0 ${e.shape.radius.default};
&:not(.selected) {
border-right: none;
}
`,excludeButton:r.css`
border-radius: 0 ${e.shape.radius.default} ${e.shape.radius.default} 0;
&:not(.selected) {
border-left: none;
}
`});function Po(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class Co extends o.Bs{getStatus(e){const{key:t,value:n}=this.state.item.queryRunnerParams.filters[0],r=e.find((e=>e.key===t));return r?Te(r.operator)&&r.value.split("|").includes(n)?"=~"===r.operator?"included":"excluded":r.value===n?"="===r.operator?"included":"excluded":"clear":"clear"}constructor({item:e}){super({item:e}),Po(this,"onInclude",(()=>{(0,d.r)("g_pyroscope_app_include_action_clicked"),this.publishEvent(new So({item:this.state.item}),!0)})),Po(this,"onExclude",(()=>{(0,d.r)("g_pyroscope_app_exclude_action_clicked"),this.publishEvent(new Eo({item:this.state.item}),!0)})),Po(this,"onClear",(()=>{this.publishEvent(new vo({item:this.state.item}),!0)}))}}function To({compare:e,onClickCompare:t,onClickClear:n}){const o=(0,i.useStyles2)(Ao),a=e.size<2,s=e.size>0,l=(0,p.useMemo)((()=>{var t,n,r,o;return 2===e.size?`Compare "${null===(r=e.get(io.N.BASELINE))||void 0===r?void 0:r.label}" vs "${null===(o=e.get(io.N.COMPARISON))||void 0===o?void 0:o.label}"`:0===e.size?"Select both a baseline and a comparison panel to compare their flame graphs":e.has(io.N.BASELINE)?`Select another panel to compare against "${null===(t=e.get(io.N.BASELINE))||void 0===t?void 0:t.label}"`:`Select another panel to compare against "${null===(n=e.get(io.N.COMPARISON))||void 0===n?void 0:n.label}"`}),[e]);return m().createElement("div",{className:o.container},m().createElement(i.Button,{"arial-label":"Compare",className:o.compareButton,variant:"primary",disabled:a,onClick:a?h.f:t,tooltip:l},"Compare (",e.size,"/2)"),m().createElement(i.Button,{"data-testid":"clearComparison",className:(0,r.cx)(o.clearButton,a?void 0:o.clearButtonActive),icon:"times",variant:"secondary",tooltip:s?"Clear comparison selection":"",disabled:!s,onClick:s?n:h.f}))}Po(Co,"Component",(({model:e})=>{const{item:t}=e.useState(),{filters:n}=o.jh.findByKeyAndType(e,"filters",nn).useState(),r=(0,p.useMemo)((()=>e.getStatus(n)),[n,e]);return m().createElement(Oo,{label:t.value,status:r,onInclude:e.onInclude,onExclude:e.onExclude,onClear:e.onClear})}));const Ao=e=>({container:r.css`
display: flex;
align-items: center;
width: ${mo.WIDTH_IN_PIXELS}px;
`,compareButton:r.css`
width: ${mo.WIDTH_IN_PIXELS-32}px;
border-right: none;
border-top-right-radius: 0;
border-bottom-right-radius: 0;
`,clearButton:r.css`
box-sizing: border-box;
width: 32px !important;
height: 32px !important;
color: ${e.colors.text.secondary};
background-color: transparent;
border-left: none !important;
border-top-left-radius: 0;
border-bottom-left-radius: 0;
&:not([disabled]),
&:not([disabled]):hover {
background-color: transparent;
box-shadow: none;
}
`,clearButtonActive:r.css`
border-color: ${e.colors.border.medium};
&:hover {
border-color: ${e.colors.border.medium};
}
`});function jo(e,t,n,r,o,i,a){try{var s=e[i](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function ko(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class No extends o.Bs{onActivate(e){var t,n=this;return(t=function*(){const t=o.jh.findByKeyAndType(n,"groupBy",to);yield t.update(),e&&n.initVariablesAndControls(e),n.renderBody(t);const r=n.subscribeToGroupByChange(),i=n.subscribeToPanelEvents();return()=>{var e;i.unsubscribe(),r.unsubscribe(),null===(e=n.state.panelTypeChangeSub)||void 0===e||e.unsubscribe()}},function(){var e=this,n=arguments;return new Promise((function(r,o){var i=t.apply(e,n);function a(e){jo(i,r,o,a,s,"next",e)}function s(e){jo(i,r,o,a,s,"throw",e)}a(void 0)}))})()}initVariablesAndControls(e){const{queryRunnerParams:t,panelType:n}=e,{groupBy:r}=t;if(null==r?void 0:r.label){o.jh.findByKeyAndType(this,"groupBy",to).changeValueTo(r.label)}if(n){o.jh.findByKeyAndType(this,"panel-type-switcher",sn).setState({panelType:n})}}subscribeToGroupByChange(){const e=o.jh.findByKeyAndType(this,"groupBy",to),t=o.jh.findByKeyAndType(this,"quick-filter",fr);return e.subscribeToState(((n,r)=>{n.value!==(null==r?void 0:r.value)&&(t.clearSearchText(),this.renderBody(e))}))}subscribeToPanelEvents(){const e=this.subscribeToEvent(kr,(e=>{this.selectLabel(e.payload.item)})),t=this.subscribeToEvent(ao,(e=>{const{compareTarget:t,item:n}=e.payload;this.selectForCompare(t,n)})),n=this.subscribeToEvent(So,(e=>{this.includeLabelValueInFilters(e.payload.item)})),r=this.subscribeToEvent(Eo,(e=>{this.excludeLabelValueFromFilters(e.payload.item)})),o=this.subscribeToEvent(vo,(e=>{this.clearLabelValueFromFilters(e.payload.item)}));return{unsubscribe(){o.unsubscribe(),r.unsubscribe(),n.unsubscribe(),t.unsubscribe(),e.unsubscribe()}}}subscribeToPanelTypeChange(){return o.jh.findByKeyAndType(this,"panel-type-switcher",sn).subscribeToState(((e,t)=>{var n;e.panelType!==(null==t?void 0:t.panelType)&&(null===(n=this.state.body)||void 0===n||n.renderGridItems())}))}renderBody(e){var t;null===(t=this.state.panelTypeChangeSub)||void 0===t||t.unsubscribe(),"all"===e.state.value?(this.setState({panelTypeChangeSub:this.subscribeToPanelTypeChange()}),this.switchToLabelNamesGrid()):this.switchToLabelValuesGrid(e)}switchToLabelNamesGrid(){o.jh.findByKeyAndType(this,"quick-filter",fr).setPlaceholder("Search labels (comma-separated regexes are supported)"),this.setState({body:this.buildSceneLabelNamesGrid()})}buildSceneLabelNamesGrid(){return new Ar({key:"service-labels-grid",variableName:"groupBy",mapOptionToItem:(e,t,{serviceName:n,profileMetricId:r,panelType:o})=>{if("all"===e.value)return null;const{value:i,groupBy:a}=JSON.parse(e.value);return{index:t-1,value:i,label:i,queryRunnerParams:{serviceName:n,profileMetricId:r,groupBy:a,filters:[]},panelType:o}},headerActions:e=>[new Br({type:"select-label",item:e}),new Br({type:"expand-panel",item:e}),new xr({item:e})]})}switchToLabelValuesGrid(e){o.jh.findByKeyAndType(this,"quick-filter",fr).setPlaceholder("Search label values (comma-separated regexes are supported)"),this.clearCompare();const{index:t,value:n}=e.findCurrentOption();this.setState({body:this.buildSceneLabelValuesGrid(n,t)})}buildSceneLabelValuesGrid(e,t){return new yo({key:"service-label-values-grid",startColorIndex:t,label:e,headerActions:e=>[new Br({type:"view-flame-graph",item:e,tooltip:(e,t)=>{const{queryRunnerParams:n,label:r}=e,o=n.profileMetricId||rn(t,"profileMetricId"),i=rn(t,"groupBy");return`View the "${(0,At.y)(o).type}" flame graph for "${i}=${r}"`}}),new Co({item:e}),new xr({item:e})]})}selectLabel({queryRunnerParams:e}){const t=e.groupBy.label,n=o.jh.findByKeyAndType(this,"groupBy",to);s(),n.changeValueTo(t)}includeLabelValueInFilters(e){const[t]=e.queryRunnerParams.filters,n=o.jh.findByKeyAndType(this,"filters",nn);n.setState({filters:Xt(n.state.filters,t)})}excludeLabelValueFromFilters(e){const t=o.jh.findByKeyAndType(this,"filters",nn),[n]=e.queryRunnerParams.filters;t.setState({filters:Jt(t.state.filters,n)})}clearLabelValueFromFilters(e){const t=o.jh.findByKeyAndType(this,"filters",nn),[n]=e.queryRunnerParams.filters;t.setState({filters:Qt(t.state.filters,n)})}selectForCompare(e,t){var n;const r=new Map(this.state.compare);(null===(n=r.get(e))||void 0===n?void 0:n.value)===t.value?r.delete(e):r.set(e,t),this.setState({compare:r}),this.updateStatsPanels()}updateStatsPanels(){const{compare:e}=this.state,t=e.get(io.N.BASELINE),n=e.get(io.N.COMPARISON),r=o.jh.findAllObjects(this,(e=>e instanceof mo));for(const e of r)e.updateCompareActions(t,n)}getCompare(){return this.state.compare}clearCompare(){this.setState({compare:new Map})}constructor({item:e}){super({key:"group-by-labels",body:void 0,compare:new Map,panelTypeChangeSub:void 0}),ko(this,"onClickCompareButton",(()=>{(0,d.r)("g_pyroscope_app_compare_link_clicked");const{compare:e}=this.state,{filters:t}=wr(this,e.get(io.N.BASELINE)),{filters:n}=wr(this,e.get(io.N.COMPARISON));this.publishEvent(new oo({useAncestorTimeRange:!0,clearDiffRange:!0,baselineFilters:t,comparisonFilters:n}),!0)})),ko(this,"onClickClearCompareButton",(()=>{this.clearCompare(),this.updateStatsPanels()})),this.addActivationHandler((()=>{this.onActivate(e)}))}}ko(No,"Component",(({model:e})=>{const t=(0,i.useStyles2)(Ro),{body:n,compare:r}=e.useState(),a=o.jh.findByKeyAndType(e,"groupBy",to),{value:s}=a.useState(),l=(0,p.useMemo)((()=>"all"===s?o.jh.findByKeyAndType(e,"profiles-explorer",iu).state.gridControls:[o.jh.findByKeyAndType(e,"quick-filter",fr),o.jh.findByKeyAndType(e,"layout-switcher",ur),o.jh.findByKeyAndType(e,"no-data-switcher",pr)]),[s,e]);return m().createElement("div",{className:t.container,"data-testid":"groupByLabelsContainer"},m().createElement(a.Component,{model:a}),m().createElement("div",{className:t.sceneControls},m().createElement(i.Stack,{wrap:"wrap"},"all"!==s&&m().createElement(To,{compare:r,onClickCompare:e.onClickCompareButton,onClickClear:e.onClickClearCompareButton}),l.map((e=>m().createElement(e.Component,{key:e.state.key,model:e}))))),n&&m().createElement(n.Component,{model:n}))}));const Ro=e=>({container:r.css`
margin-top: ${e.spacing(1)};
`,sceneControls:r.css`
margin-bottom: ${e.spacing(1)};
& .quick-filter {
flex: 1;
min-width: 112px;
}
`});function Io(e,t,n,r,o,i,a){try{var s=e[i](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function _o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Do(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter((function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable})))),r.forEach((function(t){_o(e,t,n[t])}))}return e}function Lo(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))})),e}class Fo extends o.Bs{onActivate(e){e&&this.initVariables(e);const t=o.jh.findByKeyAndType(this,"profileMetricId",Lt);t.setState({query:Lt.QUERY_SERVICE_NAME_DEPENDENT}),t.update(!0);const n=this.subscribeToPanelEvents();return()=>{n.unsubscribe(),t.setState({query:Lt.QUERY_DEFAULT}),t.update(!0)}}initVariables(e){const{queryRunnerParams:t}=e,{serviceName:n,profileMetricId:r,filters:i}=t;if(n){o.jh.findByKeyAndType(this,"serviceName",Vt).changeValueTo(n)}if(r){o.jh.findByKeyAndType(this,"profileMetricId",Lt).changeValueTo(r)}if(i){o.jh.findByKeyAndType(this,"filters",nn).setState({filters:i})}}subscribeToPanelEvents(){var e=this;const t=this.subscribeToEvent(jr,function(){var t,n=(t=function*(t){e.openExpandedPanelDrawer(t.payload.item)},function(){var e=this,n=arguments;return new Promise((function(r,o){var i=t.apply(e,n);function a(e){Io(i,r,o,a,s,"next",e)}function s(e){Io(i,r,o,a,s,"throw",e)}a(void 0)}))});return function(e){return n.apply(this,arguments)}}()),n=this.subscribeToEvent(kr,(()=>{this.state.drawer.close()}));return{unsubscribe(){n.unsubscribe(),t.unsubscribe()}}}getVariablesAndGridControls(){return{variables:[o.jh.findByKeyAndType(this,"serviceName",Vt),o.jh.findByKeyAndType(this,"profileMetricId",Lt),o.jh.findByKeyAndType(this,"filters",nn)],gridControls:[]}}openExpandedPanelDrawer(e){var t;const n=rn(this,"serviceName"),r=rn(this,"profileMetricId"),o=`${(0,At.y)(r).description||gr(r)}, grouped by ${(null===(t=e.queryRunnerParams.groupBy)||void 0===t?void 0:t.label)||"?"}`;this.state.drawer.open({title:n,body:Zn(e.panelType,{displayAllValues:!0,legendPlacement:"right",item:Lo(Do({},e),{label:o}),headerActions:()=>[new Br({type:"select-label",item:e}),new xr({item:e})]})})}static Component({model:e}){const{body:t,drawer:n}=e.useState();return m().createElement(m().Fragment,null,m().createElement(t.Component,{model:t}),m().createElement(n.Component,{model:n}))}constructor({item:e}){super({key:"explore-service-labels",body:new o.G1({direction:"column",$behaviors:[new o.Gg.K2({key:"metricCrosshairSync",sync:f.DashboardCursorSync.Crosshair})],children:[new o.vA({minHeight:ro.MIN_HEIGHT,body:new ro({item:e,headerActions:e=>e.queryRunnerParams.groupBy?[new Br({type:"view-flame-graph",item:e}),new Br({type:"expand-panel",item:e}),new xr({item:e})]:[new Br({type:"view-flame-graph",item:e}),new xr({item:e})],supportGroupBy:!0,includeExemplars:!0})}),new o.vA({body:new No({item:e})})]}),drawer:new qr}),this.addActivationHandler(this.onActivate.bind(this,e))}}class Bo extends o.Bs{onActivate(e){o.jh.findByKeyAndType(this,"quick-filter",fr).setPlaceholder("Search profile types (comma-separated regexes are supported)"),e&&this.initVariables(e)}initVariables(e){if(e.queryRunnerParams.serviceName){o.jh.findByKeyAndType(this,"serviceName",Vt).changeValueTo(e.queryRunnerParams.serviceName)}}getVariablesAndGridControls(){return{variables:[o.jh.findByKeyAndType(this,"serviceName",Vt)],gridControls:[o.jh.findByKeyAndType(this,"quick-filter",fr),o.jh.findByKeyAndType(this,"layout-switcher",ur)]}}static Component({model:e}){const{body:t}=e.useState();return m().createElement(t.Component,{model:t})}constructor({item:e}){super({key:"explore-service-profile-types",$variables:new o.Pj({variables:[new Lt({query:Lt.QUERY_SERVICE_NAME_DEPENDENT,skipUrlSync:!0})]}),body:new Ar({key:"profile-metrics-grid",variableName:"profileMetricId",mapOptionToItem:(e,t,{serviceName:n})=>({index:t,value:e.value,label:e.label,queryRunnerParams:{serviceName:n,profileMetricId:e.value},panelType:an.TIMESERIES}),headerActions:e=>[new Br({type:"view-labels",item:e}),new Br({type:"view-flame-graph",item:e}),new xr({item:e})]})}),this.addActivationHandler(this.onActivate.bind(this,e))}}function $o(e,t){return{from:e,to:t,value:{from:(0,f.dateTimeParse)(e),to:(0,f.dateTimeParse)(t),raw:{from:e,to:t}}}}const Mo=()=>$o("now-30m","now");class Vo extends o.yP{reset(){this.setState({value:void 0})}constructor(){super({key:"spanSelector",name:"spanSelector",label:"Span selector",value:void 0})}}function Uo(e,t){if(t){const n=e.services.get(t)||new Map;return Array.from(n.values()).sort(((e,t)=>Je(t.group,e.group))).map((({id:e,type:t,group:n})=>({value:e,text:`${t} (${n})`})))}return Array.from(e.profileMetrics.keys()).map((e=>(0,At.y)(e))).sort(((e,t)=>Je(t.group,e.group))).map((({id:e,type:t,group:n})=>({value:e,text:`${t} (${n})`})))}function Go(e,t){if(t){const n=e.profileMetrics.get(t)||new Set;return Array.from(n).sort(Je).map((e=>({text:e,value:e})))}return Array.from(e.services.keys()).sort(Je).map((e=>({text:e,value:e})))}class qo{static build(e,t){const n=`${e}-${t.name}`,r=qo.cache.get(n);if(r instanceof t)return r;const o=new t({dataSourceUid:e});return qo.cache.set(n,o),o}}function Ko(e){let t,n;for(const{name:r,value:o}of e)if("service_name"===r&&(t=o),"__profile_type__"===r&&(n=o),t&&n)return[t,n];return[]}function zo(e){const t=new Map,n=new Map;if(!e.labelsSet)return be.v.warn("Pyroscope SeriesApiClient: no data received!"),{services:t,profileMetrics:n};for(const{labels:r}of e.labelsSet){const[e,o]=Ko(r);if(!e||!o){be.v.warn('Pyroscope ServicesApiClient: "service_name" and/or "__profile_type__" are missing in the labels received!',r);continue}const i=t.get(e)||new Map;i.set(o,(0,At.y)(o)),t.set(e,i);const a=n.get(o)||new Set;a.add(e),n.set(o,a)}return{services:t,profileMetrics:n}}function Wo(e,t,n,r,o,i,a){try{var s=e[i](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(qo,"cache",new Map);class Ho extends A{list(e){var t,n=this;return(t=function*(){const{from:t,to:r}=e;return n.fetch("/querier.v1.QuerierService/Series",{method:"POST",body:JSON.stringify({start:t,end:r,labelNames:["service_name","__profile_type__"],matchers:[]})}).then((e=>e.json())).then(zo)},function(){var e=this,n=arguments;return new Promise((function(r,o){var i=t.apply(e,n);function a(e){Wo(i,r,o,a,s,"next",e)}function s(e){Wo(i,r,o,a,s,"throw",e)}a(void 0)}))})()}constructor(e){super(e)}}function Yo(e,t,n,r,o,i,a){try{var s=e[i](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}const Zo=new class extends D{list(e){var t,n=this;return(t=function*(){const{from:t,to:r}=Cn(e.timeRange),o=[n.apiClient.baseUrl,t,r],i=n.cacheClient.get(o);if(i){const{services:e,profileMetrics:t}=yield i;return e.size||t.size||n.cacheClient.delete(o),{services:e,profileMetrics:t}}const a=n.apiClient.list({from:t,to:r});n.cacheClient.set(o,a);try{const{services:e,profileMetrics:t}=yield a;return{services:e,profileMetrics:t}}catch(e){throw n.cacheClient.delete(o),e}},function(){var e=this,n=arguments;return new Promise((function(r,o){var i=t.apply(e,n);function a(e){Yo(i,r,o,a,s,"next",e)}function s(e){Yo(i,r,o,a,s,"throw",e)}a(void 0)}))})()}constructor(e){super(e)}}({cacheClient:new R});function Xo(e,t,n,r,o,i,a){try{var s=e[i](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function Jo(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var i=e.apply(t,n);function a(e){Xo(i,r,o,a,s,"next",e)}function s(e){Xo(i,r,o,a,s,"throw",e)}a(void 0)}))}}class Qo extends o.UU{fetchSeries(e,t,n){return Jo((function*(){Zo.setApiClient(qo.build(e,Ho));try{return yield Zo.list({timeRange:t})}catch(e){throw be.v.error(e,{info:"Error while loading Pyroscope series!",variableName:n||""}),e}}))()}query(){return Jo((function*(){return{state:f.LoadingState.Done,data:[{name:"PyroscopeSeries",fields:[{name:"PyroscopeSeries",type:f.FieldType.other,values:[],config:{}}],length:0}]}}))()}metricFindQuery(e,t){var n=this;return Jo((function*(){var r,o,i;const a=null===(o=t.scopedVars)||void 0===o||null===(r=o.__sceneObject)||void 0===r?void 0:r.valueOf();let s=Tn(a,"$dataSource");const l=Tn(a,"$serviceName"),c=Tn(a,"$profileMetricId");s||(s=L.O.selectDefaultDataSource().uid);const u=yield n.fetchSeries(s,t.range,null===(i=t.variable)||void 0===i?void 0:i.name);switch(e){case"$dataSource and all services":return Go(u);case"$dataSource and all profile metrics":return Uo(u);case"$dataSource and only $profileMetricId services":return Go(u,c);case"$dataSource and only $serviceName profile metrics":return Uo(u,l);default:throw new TypeError(`Unsupported query "${e}"!`)}}))()}testDatasource(){return Jo((function*(){return{status:"success",message:"OK"}}))()}constructor(){super(Nt.type,Nt.uid)}}var ei=n(9215),ti=n(3518),ni=n(4002);function ri(e,t,n,r,o,i,a){try{var s=e[i](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function oi(){const{recordingRules:e,error:t,mutate:n}=(0,ni.e)();return{data:{recordingRules:e,fetchError:t},actions:{save(e){return(t=function*(){try{yield n(e),(0,a.qq)([`Recording rule ${e.metricName} created successfully!`])}catch(t){(0,a.jx)(t,[`Failed to save recording rule ${e.metricName}.`])}},function(){var e=this,n=arguments;return new Promise((function(r,o){var i=t.apply(e,n);function a(e){ri(i,r,o,a,s,"next",e)}function s(e){ri(i,r,o,a,s,"throw",e)}a(void 0)}))})();var t}}}}function ii(e,t,n,r,o,i,a){try{var s=e[i](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function ai(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function si(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter((function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable})))),r.forEach((function(t){ai(e,t,n[t])}))}return e}function li(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))})),e}const ci="profiles_recorded_";class ui extends o.Bs{constructor(){super({})}}ai(ui,"Component",(function({model:e,isModalOpen:t,onDismiss:n,onCreated:a,functionName:s}){const[l,c]=(0,p.useState)([]),{actions:u}=oi(),d=o.jh.findByKeyAndType(e,"profileMetricId",Lt),f=(0,At.y)(d.state.value),h=function(e){const t=o.jh.findByKeyAndType(e,"serviceName",Vt).state.value,n=o.jh.findByKeyAndType(e,"profiles-explorer",iu).useState().explorationType;return n===ou.ALL_SERVICES||n===ou.FAVORITES?void 0:t}(e),g=o.jh.findByKeyAndType(e,"filters",nn).state.filters,b=g.map((e=>`${e.key}${e.operator}"${e.value}"`)).join(", "),y=(null==h?void 0:h.toString())||"",v=!y,{register:E,handleSubmit:S,control:w,formState:{errors:O}}=(0,ei.mN)({mode:"onChange",shouldUnregister:!0,values:{functionName:s,metricName:"",labels:v?[{label:"service_name",value:"service_name"}]:[],serviceName:y,matcher:"",profileType:f.id}}),x=function(){var e,t=(e=function*(e){const t={id:"",metricName:ci+e.metricName,serviceName:e.serviceName,profileType:e.profileType,matchers:b?[`{${b}}`]:[],groupBy:e.labels?e.labels.map((e=>{var t;return null!==(t=e.value)&&void 0!==t?t:""})):[],functionName:e.functionName,readonly:!1};yield u.save(t),a()},function(){var t=this,n=arguments;return new Promise((function(r,o){var i=e.apply(t,n);function a(e){ii(i,r,o,a,s,"next",e)}function s(e){ii(i,r,o,a,s,"throw",e)}a(void 0)}))});return function(e){return t.apply(this,arguments)}}();return(0,ti.A)((()=>{const t=o.jh.getTimeRange(e).state.value;q.listLabels({query:`{${b}}`,from:1e3*t.from.unix(),to:1e3*t.to.unix()}).then((e=>{let t=e.map((e=>e.value));v&&(t=["service_name",...t]),c(t)}))})),m().createElement(i.Modal,{title:"Create recording rule",isOpen:t,onDismiss:n,"data-testid":"Create recording rule modal"},m().createElement("form",{onSubmit:S(x)},m().createElement(i.Field,{label:"Metric name",description:`Prometheus metric name (automatically prefixed with ${ci}).`,error:di(O.metricName),invalid:!!O.metricName},m().createElement("div",{className:(0,r.css)({display:"flex"})},m().createElement("div",{className:(0,r.css)({alignContent:"center",fontFamily:"monospace"})},ci),m().createElement(i.Input,si({className:(0,r.css)({input:{fontFamily:"monospace",paddingLeft:0}}),placeholder:`${f.type}_${(y||"name").toString().replace(/[^a-zA-Z0-9_]/g,"_")}`,"aria-label":"Metric name",required:!0,autoFocus:!0},E("metricName",{required:"Metric name is required.",pattern:{value:/^[a-zA-Z_][a-zA-Z0-9_]*$/,message:"Invalid metric name."}}))))),m().createElement(i.Field,{label:"Additional labels",description:"Additional profiling labels to forward to the metric"},m().createElement(ei.xI,{name:"labels",control:w,render:({field:e})=>m().createElement(i.MultiSelect,li(si({},e),{options:l.map((e=>({label:e,value:e}))),toggleAllOptions:{enabled:!0},closeMenuOnSelect:!1,hideSelectedOptions:!1}))})),m().createElement(i.Divider,null),m().createElement(i.Field,{label:"Service name","data-testid":"Create recording rule modal service name field"},y?m().createElement("div",null,`${y}`):m().createElement(i.Text,{element:"span",color:"secondary"},"All services")),m().createElement("input",si({type:"text",hidden:!0},E("serviceName"))),m().createElement(i.Field,{label:"Profile type"},m().createElement("div",null,`${f.group}/${f.type}`)),m().createElement("input",si({type:"text",hidden:!0},E("profileType"))),m().createElement(i.Field,{label:"Function name",description:"Optional function name to filter the recording rule"},m().createElement(i.Input,si({"aria-label":"Function name",placeholder:"Leave empty for total aggregation"},E("functionName")))),m().createElement(i.Field,{label:"Filters",description:"Filters selected in the main view will be applied to this rule"},m().createElement("div",null,0===g.length?"No filters selected":b)),m().createElement(i.Modal.ButtonRow,null,m().createElement(i.Button,{variant:"secondary",fill:"outline",onClick:n,"aria-label":"Cancel"},"Cancel"),m().createElement(i.Button,{variant:"primary",type:"submit"},"Create"))))}));const di=e=>{const t=(0,i.useStyles2)(pi);if(void 0!==e&&void 0!==e.message)return"pattern"===e.type?m().createElement("span",null,m().createElement("span",null,"Metric name is invalid, it must have the following properties:"),m().createElement("ul",{className:t.errorList},m().createElement("li",null,"Only contain alphanumeric characters or underscores"),m().createElement("li",null,"Must not begin with a number"))):m().createElement("span",null,e.message)},pi=e=>({errorList:r.css`
padding-left: ${e.spacing(2)};
`});class mi extends f.BusEventWithPayload{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(mi,"type","enable-sync-timeranges");class fi extends f.BusEventWithPayload{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(fi,"type","sync-refresh");class hi extends f.BusEventWithPayload{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(hi,"type","sync-timeranges");class gi extends o.KE{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(gi,"Component",(function({model:e}){const{hidePicker:t,isOnCanvas:n}=e.useState(),r=o.jh.getTimeRange(e),a=r.getTimeZone(),s=r.useState();return t?null:m().createElement(i.TimeRangePicker,{isOnCanvas:null==n||n,value:s.value,onChange:r.onTimeRangeChange,timeZone:a,fiscalYearStartMonth:s.fiscalYearStartMonth,onMoveBackward:e.onMoveBackward,onMoveForward:e.onMoveForward,onZoom:e.onZoom,onChangeTimeZone:r.onTimeZoneChange,onChangeFiscalYearStartMonth:e.onChangeFiscalYearStartMonth,isSynced:!1})}));const bi=/^\d+[yYmMsSwWhHdD]$/;function yi(e){if("string"!=typeof e)return null;if(-1!==e.indexOf("now"))return e;if(bi.test(e))return e;if(8===e.length){const t=(0,f.toUtc)(e,"YYYYMMDD");if(t.isValid())return t.toISOString()}else if(15===e.length){const t=(0,f.toUtc)(e,"YYYYMMDDTHHmmss");if(t.isValid())return t.toISOString()}else if(24===e.length){return(0,f.toUtc)(e).toISOString()}const t=parseInt(e,10);return isNaN(t)?null:(0,f.toUtc)(t).toISOString()}function vi(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Ei(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter((function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable})))),r.forEach((function(t){vi(e,t,n[t])}))}return e}function Si(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))})),e}var wi=function(e){return e.ANNOTATIONS="annotations",e.DEFAULT="default",e}({});const Oi={from:(0,f.dateTime)(0),to:(0,f.dateTime)(0),raw:{from:"",to:""}};class xi extends o.Bs{onActivate(){var e;this.setState((0,g.omit)(this.getAncestorTimeRange().state,"key")),this._subs.add(this.getAncestorTimeRange().subscribeToState((e=>{this.setState((0,g.omit)(e,"key"))}))),this._subs.add(null===(e=this.getTimeseries().state.$data)||void 0===e?void 0:e.subscribeToState(((e,t)=>{var n,r,o,i,a,s;e.data&&e.data.state===f.LoadingState.Done&&((null===(n=e.data.annotations)||void 0===n?void 0:n.length)||(null===(o=t.data)||void 0===o||null===(r=o.annotations)||void 0===r?void 0:r.length)?!(null===(i=e.data.annotations)||void 0===i?void 0:i.length)&&(null===(s=t.data)||void 0===s||null===(a=s.annotations)||void 0===a?void 0:a.length)&&(e.data.annotations=t.data.annotations):this.updateTimeseriesAnnotation())})))}getAncestorTimeRange(){if(!this.parent||!this.parent.parent)throw new Error(typeof this+" must be used within $timeRange scope");return o.jh.getTimeRange(this.parent.parent)}getTimeseries(){try{const e=o.jh.getAncestor(this,o.Eb);if("timeseries"!==e.state.pluginId)throw new TypeError("Incorrect VizPanel type!");return e}catch(e){throw new Error("Ancestor timeseries panel not found!")}}updateTimeseriesAnnotation(){const{annotationTimeRange:e,annotationColor:t,annotationTitle:n}=this.state,{$data:r}=this.getTimeseries().state,o=null==r?void 0:r.state.data;if(!o)return;const i=new Fn;i.addRange({color:t,text:n,time:1e3*e.from.unix(),timeEnd:1e3*e.to.unix()}),null==r||r.setState({data:Si(Ei({},o),{annotations:[i]})})}setAnnotationTimeRange(e,t=!1){this.setState({annotationTimeRange:e}),t&&this.updateTimeseriesAnnotation()}nullifyAnnotationTimeRange(){this.setAnnotationTimeRange(Oi)}getUrlState(){const{annotationTimeRange:e}=this.state;return{diffFrom:"string"==typeof e.raw.from?e.raw.from:e.raw.from.toISOString(),diffTo:"string"==typeof e.raw.to?e.raw.to:e.raw.to.toISOString()}}updateFromUrl(e){const{diffFrom:t,diffTo:n}=e;if(!n&&!t)return;const{annotationTimeRange:r}=this.state;var o,i;this.setAnnotationTimeRange(this.buildAnnotationTimeRange(null!==(o=yi(t))&&void 0!==o?o:r.from,null!==(i=yi(n))&&void 0!==i?i:r.to))}buildAnnotationTimeRange(e,t){return function(e,t,n,r,o){const i=o&&"now"===t;return{from:f.dateMath.parse(e,!1,n,r),to:f.dateMath.parse(i?"now-"+o:t,!0,n,r),raw:{from:e,to:t}}}(e,t,this.getTimeZone(),this.state.fiscalYearStartMonth,this.state.UNSAFE_nowDelay)}onTimeRangeChange(e){const{mode:t}=this.state;"default"!==t?this.setAnnotationTimeRange(e,!0):this.getAncestorTimeRange().onTimeRangeChange(e)}onTimeZoneChange(e){this.getAncestorTimeRange().onTimeZoneChange(e)}getTimeZone(){return this.getAncestorTimeRange().getTimeZone()}onRefresh(){this.getAncestorTimeRange().onRefresh()}constructor(e){super(Ei({from:Oi.raw.from,to:Oi.raw.to,value:Oi,annotationTimeRange:Oi},e)),vi(this,"_variableDependency",new o.Sh(this,{variableNames:["dataSource","serviceName"],onReferencedVariableValueChanged:()=>{this.nullifyAnnotationTimeRange(),this.updateTimeseriesAnnotation()}})),vi(this,"_urlSync",new o.So(this,{keys:["diffFrom","diffTo"]})),this.addActivationHandler(this.onActivate.bind(this))}}class Pi extends f.BusEventWithPayload{}function Ci(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(Pi,"type","switch-timerange-selection-mode");var Ti=function(e){return e.TIMEPICKER="timepicker",e.FLAMEGRAPH="flame-graph",e}({});class Ai extends o.Bs{constructor(){super({mode:"flame-graph"}),Ci(this,"onChange",(e=>{this.setState({mode:e}),this.publishEvent(new Pi({mode:e}),!0)}))}}Ci(Ai,"OPTIONS",[{label:"Time picker",value:"timepicker"},{label:"Flame graph",value:"flame-graph"}]),Ci(Ai,"Component",(({model:e})=>{const t=(0,i.useStyles2)(ji),{mode:n}=e.useState();return m().createElement("div",{className:t.container},m().createElement(i.RadioButtonGroup,{size:"sm",options:Ai.OPTIONS,value:n,onChange:e.onChange,"aria-label":"Range selection mode"}),m().createElement("div",null,m().createElement(i.Tooltip,{content:m().createElement("div",{className:t.tooltip},m().createElement("div",null,"Use these buttons to change the behaviour when selecting a range with the mouse on the time series:"),m().createElement("dl",null,m().createElement("dt",null,"Time picker"),m().createElement("dd",null,"Time range zoom in (default behaviour)"),m().createElement("dt",null,"Flame graph"),m().createElement("dd",null,"Time range for building the flame graph (the stack traces will be retrieved only for the selected range)"))),placement:"top"},m().createElement(i.Icon,{name:"question-circle"}))))}));const ji=e=>({container:r.css`
display: flex;
flex-direction: row;
gap: ${e.spacing(1)};
`,tooltip:r.css`
padding: ${e.spacing(1)};
& dl {
margin-top: ${e.spacing(2)};
display: grid;
grid-gap: ${e.spacing(1)} ${e.spacing(2)};
grid-template-columns: max-content;
}
& dt {
font-weight: bold;
}
& dd {
margin: 0;
grid-column-start: 2;
}
`,label:r.css`
font-size: 12px;
text-align: right;
margin-bottom: 2px;
color: ${e.colors.text.secondary};
`});function ki({filterKey:e}){return mn(new o.dt({datasource:kt,queries:[{refId:`$profileMetricId-$serviceName-${e}}`,queryType:"metrics",profileTypeId:"$profileMetricId",labelSelector:`{service_name="$serviceName",$${e}}`}]}))}var Ni=n(4308),Ri=n.n(Ni);const Ii={COLOR:Ri()("#d066d4"),OVERLAY:Ri()("#d066d4").alpha(.3)},_i={COLOR:Ri()("#1398f6"),OVERLAY:Ri()("#1398f6").alpha(.3)};function Di(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Li(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter((function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable})))),r.forEach((function(t){Di(e,t,n[t])}))}return e}function Fi(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))})),e}class Bi extends o.Bs{onActivate(e,t,n){const{$timeRange:r,timeseriesPanel:i,filterKey:a}=this.state;if(t&&this.setDiffRange(null),e&&r.setState((0,g.omit)(this.getAncestorTimeRange().state,"key")),n.length){o.jh.findByKey(this,a).setState({filters:n})}i.updateItem({label:this.buildTimeseriesTitle()});const s=this.subscribeToEvents();return()=>{s.unsubscribe()}}static buildTimeSeriesPanel({target:e,filterKey:t,title:n,color:r}){const i=new Yn({item:{index:0,value:e,label:"",queryRunnerParams:{},panelType:an.TIMESERIES},data:new o.Es({$data:ki({filterKey:t}),transformations:[gn,bn]}),overrides:e=>Bi.buildSeriesOverrides(e,r),headerActions:()=>[new Ai]});return Bi.configureTimeRange(i,e,n),i}static buildSeriesOverrides(e,t){return e.map((e=>{const n=e.fields[1],r=dn(e,"allValuesSum")||0,o=[{id:"displayName",value:`${Bi.getProperLabel(e)} = ${Bi.formatTotalValue(r,n.config.unit||"short")}`},{id:"color",value:{mode:"fixed",fixedColor:t}}];return{matcher:{id:f.FieldMatcherID.byFrameRefID,options:e.refId},properties:o}}))}static getProperLabel(e){const t=vn("",e).match(/^(avg|total)/);return t?t[1]:"total"}static formatTotalValue(e,t){const n=t||"short",r=(0,f.getValueFormat)(n)(e);return`${r.text}${r.suffix}`}static configureTimeRange(e,t,n){e.state.body.setState({$timeRange:new xi({key:`${t}-annotation-timerange`,mode:wi.ANNOTATIONS,annotationColor:t===io.N.BASELINE?Ii.OVERLAY.toString():_i.OVERLAY.toString(),annotationTitle:`${n} flame graph range`})})}static getDiffRange(e){var t,n,r,o;let i,a;const s=null===(r=e.state.body.state.$data)||void 0===r||null===(n=r.state.data)||void 0===n||null===(t=n.annotations)||void 0===t?void 0:t[0];return null==s||s.fields.some((({name:e,values:t})=>(i="time"===e?t[0]:i,a="timeEnd"===e?t[0]:a,i&&a))),[i,a,null===(o=e.state.$timeRange)||void 0===o?void 0:o.state.timeZone]}getAncestorTimeRange(){if(!this.parent||!this.parent.parent)throw new Error(typeof this+" must be used within $timeRange scope");return o.jh.getTimeRange(this.parent.parent)}subscribeToEvents(){var e;const{target:t,timeseriesPanel:n,$timeRange:r}=this.state,o=n.state.body.state.$timeRange,i=this.subscribeToEvent(Pi,(e=>{o.setState({mode:e.payload.mode===Ti.FLAMEGRAPH?wi.ANNOTATIONS:wi.DEFAULT})})),a=o.subscribeToState(((e,n)=>{this.state.timeRangeSyncEnabled&&e.annotationTimeRange!==n.annotationTimeRange&&this.publishEvent(new hi({source:t,annotationTimeRange:e.annotationTimeRange}),!0)})),s=r.subscribeToState(((e,n)=>{e.from===n.from&&e.to===n.to||(this.updateTitle(""),this.state.timeRangeSyncEnabled&&this.publishEvent(new hi({source:t,timeRange:e}),!0))})),l=null===(e=n.state.body.state.$data)||void 0===e?void 0:e.subscribeToState((e=>{var t,n;"Done"===(null===(t=e.data)||void 0===t?void 0:t.state)&&(null===(n=e.data.series)||void 0===n?void 0:n.length)&&this.syncStepSizeWithSibling(e.data.series)}));return{unsubscribe(){s.unsubscribe(),a.unsubscribe(),i.unsubscribe(),null==l||l.unsubscribe()}}}buildTimeseriesTitle(){const e=rn(this,"profileMetricId"),{description:t}=(0,At.y)(e);return t||gr(e)}useDiffTimeRange(){return this.state.timeseriesPanel.state.body.state.$timeRange.useState()}applyPreset({from:e,to:t,diffFrom:n,diffTo:r,label:o}){this.setDiffRange({from:n,to:r}),this.setTimeRange($o(e,t)),this.updateTitle(o)}setTimeRange(e){const{from:t,to:n}=this.state.$timeRange.state.value;t.isSame(e.value.from)&&n.isSame(e.value.to)||this.state.$timeRange.setState({from:e.from,to:e.to,value:e.value})}setDiffRange(e){const t=this.state.timeseriesPanel.state.body.state.$timeRange;if(null===e)return void t.nullifyAnnotationTimeRange();const{annotationTimeRange:n}=t.state,r=t.buildAnnotationTimeRange(e.from,e.to);n.from.isSame(r.from)&&n.to.isSame(r.to)||t.setAnnotationTimeRange(r,!0)}autoSelectDiffRange(e){const{$timeRange:t,target:n}=this.state,{from:r,to:o}=t.state.value;if(this.updateTitle(""),e)return void this.setDiffRange({from:r.toISOString(),to:o.toISOString()});const i=o.diff(r),a=Math.min(Math.round(.25*i),864e5);n===io.N.BASELINE?this.setDiffRange({from:r.toISOString(),to:(0,f.dateTime)(r).add(a).toISOString()}):this.setDiffRange({from:(0,f.dateTime)(o).subtract(a).toISOString(),to:o.toISOString()})}updateTitle(e=""){const t=this.state.target===io.N.BASELINE?"Baseline":"Comparison",n=e?`${t} (${e})`:t;this.setState({title:n})}toggleTimeRangeSync(e){this.setState({timeRangeSyncEnabled:e})}refreshTimeseries(){this.state.$timeRange.onRefresh()}syncStepSizeWithSibling(e){const t=this.getSiblingPanel();if(!t)return;const n=this.getSiblingData(t);(null==n?void 0:n.length)&&this.performStepSynchronization(e,n)}getSiblingPanel(){if(!this.parent)return null;const e="state"in this.parent?this.parent.state:this.parent;return"baselinePanel"in e&&"comparisonPanel"in e?this.state.target===io.N.BASELINE?e.comparisonPanel:e.baselinePanel:null}getSiblingData(e){var t,n;return(null===(n=e.state.timeseriesPanel.state.body.state.$data)||void 0===n||null===(t=n.state.data)||void 0===t?void 0:t.series)||null}performStepSynchronization(e,t){const n=this.extractStepDuration(e),r=this.extractStepDuration(t);if(n&&r&&Math.abs(n-r)>.001){const e=Math.max(n,r);this.state.lastSyncedStepSec!==e&&(this.setState({lastSyncedStepSec:e}),this.updateQueryStep(e))}}extractStepDuration(e){var t;if(!(null==e?void 0:e.length))return null;const n=e[0].fields.find((e=>"time"===e.type));if(!(null==n||null===(t=n.values)||void 0===t?void 0:t.length)||n.values.length<2)return null;const r=n.values;return(r[1]-r[0])/1e3}updateQueryStep(e){var t;const n=null===(t=this.state.timeseriesPanel.state.body.state.$data)||void 0===t?void 0:t.state.$data;if(!(null==n?void 0:n.setState)||!(null==n?void 0:n.runQueries))return;const r=n.state.queries.map((t=>Fi(Li({},t),{step:e})));n.setState({queries:r}),n.runQueries()}constructor({target:e,useAncestorTimeRange:t,clearDiffRange:n,filters:r}){const i=e===io.N.BASELINE?"filtersBaseline":"filtersComparison",a=e===io.N.BASELINE?"Baseline":"Comparison",s=e===io.N.BASELINE?Ii.COLOR.toString():_i.COLOR.toString();super({key:`${e}-panel`,target:e,filterKey:i,title:a,color:s,$timeRange:new o.JZ(Li({key:`${e}-panel-timerange`},$o("now-1h","now"))),timePicker:new gi({isOnCanvas:!0}),refreshPicker:new o.WM({isOnCanvas:!0}),timeseriesPanel:Bi.buildTimeSeriesPanel({target:e,filterKey:i,title:a,color:s}),timeRangeSyncEnabled:!1}),Di(this,"_variableDependency",new o.Sh(this,{variableNames:["profileMetricId"],onReferencedVariableValueChanged:()=>{this.state.timeseriesPanel.updateItem({label:this.buildTimeseriesTitle()})}})),Di(this,"onClickTimeRangeSync",(()=>{const{target:e,timeRangeSyncEnabled:t,$timeRange:n,timeseriesPanel:r}=this.state,o=r.state.body.state.$timeRange;this.publishEvent(new mi({source:e,enable:!t,timeRange:n.state,annotationTimeRange:o.state.annotationTimeRange}),!0)})),Di(this,"onClickRefresh",(()=>{this.publishEvent(new fi({source:this.state.target}),!0)})),this.addActivationHandler(this.onActivate.bind(this,t,n,r))}}Di(Bi,"Component",(({model:e})=>{const{target:t,color:n,title:a,timeseriesPanel:s,timePicker:l,refreshPicker:c,filterKey:u,timeRangeSyncEnabled:d}=e.useState(),p=(0,i.useStyles2)($i,n),f=o.jh.findByKey(e,u);return m().createElement("div",{className:p.panel,"data-testid":`panel-${t}`},m().createElement("div",{className:p.panelHeader},m().createElement("h6",null,m().createElement("div",{className:p.colorCircle}),a),m().createElement("div",{className:p.timeControls},m().createElement(l.Component,{model:l}),m().createElement("div",{onClick:e.onClickRefresh},m().createElement(c.Component,{model:c})),m().createElement(i.IconButton,{className:(0,r.cx)(p.syncButton,d&&"active"),name:"link","aria-label":d?"Unsync time ranges":"Sync time ranges",tooltip:d?"Unsync time ranges":"Sync time ranges",onClick:e.onClickTimeRangeSync}))),m().createElement("div",{className:p.filter},m().createElement(f.Component,{model:f})),m().createElement("div",{className:p.timeseries},s&&m().createElement(s.Component,{model:s})))}));const $i=(e,t)=>({panel:r.css`
background-color: ${e.colors.background.primary};
padding: ${e.spacing(1)} ${e.spacing(1)} 0 ${e.spacing(1)};
border: 1px solid ${e.colors.border.weak};
border-radius: 2px;
`,panelHeader:r.css`
display: flex;
justify-content: space-between;
align-items: flex-start;
margin-bottom: ${e.spacing(2)};
flex-wrap: wrap;
& > h6 {
font-size: 15px;
height: 32px;
line-height: 32px;
margin: 0 ${e.spacing(1)} 0 0;
}
`,colorCircle:r.css`
display: inline-block;
background-color: ${t};
border-radius: 50%;
width: 9px;
height: 9px;
margin-right: 6px;
`,timeControls:r.css`
display: flex;
justify-content: flex-end;
gap: 4px;
`,syncButton:r.css`
z-index: unset;
padding: ${e.spacing(0,1)};
margin: 0;
background: ${e.colors.secondary.main};
border: 1px solid ${e.colors.secondary.border};
border-radius: ${e.shape.radius.default};
&:hover {
background: ${e.colors.secondary.shade};
}
&.active {
color: ${e.colors.primary.text};
border: 1px solid ${e.colors.primary.text};
}
`,filter:r.css`
display: flex;
margin-bottom: ${e.spacing(3)};
`,timeseries:r.css`
height: 200px;
& [data-viz-panel-key] > * {
border: 0 none;
}
& [data-viz-panel-key] [data-testid='uplot-main-div'] {
cursor: crosshair;
}
`});var Mi=n(8629);function Vi(){const[e,t]=(0,p.useState)(null),[n,r]=(0,p.useState)();return{onOpen(e){r((()=>e))},isOpen:t=>t===e,open(e){t(e),null==n||n()},close(){t(null)}}}var Ui=n(8873),Gi=n(8536),qi=n(7945);function Ki({children:e,delay:t}){const[n,r]=(0,p.useState)(!1);return(0,p.useEffect)((()=>{window.setTimeout((()=>{r(!0)}),t)}),[e,t]),m().createElement(m().Fragment,null,n?e:null)}function zi({menu:e,title:t,placement:n="bottom",offset:o,dragClassCancel:a,menuButtonClass:s,onVisibleChange:l,onOpenMenu:c}){const u=t?qi.Tp.components.Panels.Panel.menu(t):"panel-menu-button",d=(0,p.useCallback)((e=>(e&&c&&c(),l)),[c,l]),f=t?`Menu for panel with title ${t}`:"Menu for panel with no title";return m().createElement(i.Dropdown,{overlay:e,placement:n,offset:o,onVisibleChange:d},m().createElement(i.ToolbarButton,{"aria-label":f,title:"Menu",icon:"ellipsis-v",iconSize:"md",narrow:!0,"data-testid":u,className:(0,r.cx)(s,a)}))}function Wi({menu:e,title:t,dragClass:n,children:o,offset:a=-32,onOpenMenu:s}){const l=(0,i.useStyles2)(Hi),c=(0,p.useRef)(null),u=qi.Tp.components.Panels.Panel.HoverWidget,d=(0,p.useCallback)((e=>{var t;null===(t=c.current)||void 0===t||t.setPointerCapture(e.pointerId)}),[]),f=(0,p.useCallback)((e=>{var t;null===(t=c.current)||void 0===t||t.releasePointerCapture(e.pointerId)}),[]),[h,g]=(0,p.useState)(!1);return void 0===o||0===m().Children.count(o)?null:m().createElement("div",{className:(0,r.cx)(l.container,{"show-on-hover":!h}),style:{top:`${a}px`},"data-testid":u.container},n&&m().createElement("div",{className:(0,r.cx)(l.square,l.draggable,n),onPointerDown:d,onPointerUp:f,ref:c,"data-testid":u.dragIcon},m().createElement(i.Icon,{name:"expand-arrows",className:l.draggableIcon})),!t&&m().createElement("h6",{className:(0,r.cx)(l.untitled,{[l.draggable]:!!n},n)},"Untitled"),o,e&&m().createElement(zi,{menu:e,title:t,placement:"bottom",menuButtonClass:l.menuButton,onVisibleChange:g,onOpenMenu:s}))}function Hi(e){return{hidden:(0,r.css)({visibility:"hidden",opacity:"0"}),container:(0,r.css)({label:"hover-container-widget",transition:"all .1s linear",display:"flex",position:"absolute",zIndex:1,right:0,boxSizing:"content-box",alignItems:"center",background:e.colors.background.secondary,color:e.colors.text.primary,border:`1px solid ${e.colors.border.weak}`,borderRadius:e.shape.radius.default,height:e.spacing(4),boxShadow:e.shadows.z1}),square:(0,r.css)({display:"flex",justifyContent:"center",alignItems:"center",width:e.spacing(4),height:"100%"}),draggable:(0,r.css)({cursor:"move",[e.breakpoints.down("md")]:{display:"none"}}),menuButton:(0,r.css)({background:"inherit",border:"none","&:hover":{background:e.colors.secondary.main}}),untitled:(0,r.css)({color:e.colors.text.disabled,fontStyle:"italic",padding:e.spacing(0,1),marginBottom:0}),draggableIcon:(0,r.css)({transform:"rotate(45deg)",color:e.colors.text.secondary,"&:hover":{color:e.colors.text.primary}})}}function Yi(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Zi(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter((function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable})))),r.forEach((function(t){Yi(e,t,n[t])}))}return e}function Xi(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))})),e}function Ji(e,t){if(null==e)return{};var n,r,o=function(e,t){if(null==e)return{};var n,r,o={},i=Object.keys(e);for(r=0;r<i.length;r++)n=i[r],t.indexOf(n)>=0||(o[n]=e[n]);return o}(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r<i.length;r++)n=i[r],t.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(o[n]=e[n])}return o}const Qi=(0,p.forwardRef)(((e,t)=>{var{className:n,children:o,href:a,onClick:s,target:l,title:c}=e,u=Ji(e,["className","children","href","onClick","target","title"]);const d=(0,i.useStyles2)(ea);return a?m().createElement("a",Zi({ref:t,href:a,onClick:s,target:l,title:c,className:(0,r.cx)(d.linkItem,n)},u),o):s?m().createElement(i.Button,{ref:t,className:(0,r.cx)(d.item,n),variant:"secondary",fill:"text",onClick:s},o):m().createElement("span",Zi({ref:t,className:(0,r.cx)(d.item,n)},u),o)}));Qi.displayName="TitleItem";const ea=e=>{const t=(0,r.css)({color:`${e.colors.text.secondary}`,label:"panel-header-item",cursor:"auto",border:"none",borderRadius:`${e.shape.radius.default}`,padding:`${e.spacing(0,1)}`,height:`${e.spacing(e.components.panel.headerHeight)}`,display:"flex",alignItems:"center",justifyContent:"center","&:focus, &:focus-visible":Xi(Zi({},ta(e)),{zIndex:1}),"&: focus:not(:focus-visible)":{outline:"none",boxShadow:"none"},"&:hover ":{boxShadow:`${e.shadows.z1}`,background:`${e.colors.background.secondary}`,color:`${e.colors.text.primary}`}});return{item:t,linkItem:(0,r.cx)(t,(0,r.css)({cursor:"pointer"}))}};function ta(e){return{outline:"2px dotted transparent",outlineOffset:"2px",boxShadow:`0 0 0 2px ${e.colors.background.canvas}, 0 0 0px 4px ${e.colors.primary.main}`,transitionTimingFunction:"cubic-bezier(0.19, 1, 0.22, 1)",transitionDuration:"0.2s",transitionProperty:"outline, outline-offset, box-shadow"}}function na({description:e,className:t}){const n=(0,i.useStyles2)(ra);return""!==e?m().createElement(i.Tooltip,{interactive:!0,content:()=>{const t="function"==typeof e?e():e;return m().createElement("div",{className:"panel-info-content markdown-html"},m().createElement("div",{dangerouslySetInnerHTML:{__html:t}}))}},m().createElement(Qi,{className:(0,r.cx)(t,n.description)},m().createElement(i.Icon,{name:"info-circle",size:"md"}))):null}const ra=()=>({description:(0,r.css)({code:{whiteSpace:"normal",wordWrap:"break-word"},"pre > code":{display:"block"}})});function oa({message:e,onClick:t,ariaLabel:n="status"}){const r=(0,i.useStyles2)(ia);return m().createElement(i.ToolbarButton,{className:r.buttonStyles,onClick:t,variant:"destructive",icon:"exclamation-triangle",iconSize:"md",tooltip:e||"","aria-label":n})}const ia=e=>{const{headerHeight:t,padding:n}=e.components.panel;return{buttonStyles:(0,r.css)({label:"panel-header-state-button",display:"flex",alignItems:"center",justifyContent:"center",padding:e.spacing(n),width:e.spacing(t),height:e.spacing(t),borderRadius:e.shape.radius.default})}};function aa({children:e,padding:t="md",title:n="",description:o="",displayMode:a="default",titleItems:s,menu:l,dragClass:c,dragClassCancel:u,hoverHeader:d=!1,hoverHeaderOffset:h,loadingState:g,statusMessage:b,statusMessageOnClick:y,actions:v,onCancelQuery:E,onOpenMenu:S}){const w=(0,i.useTheme2)(),O=(0,i.useStyles2)(ua),[x,P]=(0,p.useState)(0),C=(0,p.useRef)(null);(0,p.useEffect)((()=>{C.current&&P(C.current.offsetWidth)}),[C]);const T=!d,A=la(w,T),{contentStyle:j}=ca(t,w),k={height:A,cursor:c?"move":"auto"},N={};"transparent"===a&&(N.backgroundColor="transparent",N.border="none");const R=n?qi.Tp.components.Panels.Panel.title(n):"Panel",I=m().createElement(m().Fragment,null,n&&m().createElement("h6",{title:n,className:O.title},n),m().createElement("div",{className:(0,r.cx)(O.titleItems,u),"data-testid":"title-items-container"},m().createElement(na,{description:o,className:u}),s),g===f.LoadingState.Streaming&&m().createElement(i.Tooltip,{content:E?"Stop streaming":"Streaming"},m().createElement(Qi,{className:u,"data-testid":"panel-streaming",onClick:E},m().createElement(i.Icon,{name:"circle-mono",size:"md",className:O.streaming}))),g===f.LoadingState.Loading&&E&&m().createElement(Ki,{delay:2e3},m().createElement(i.Tooltip,{content:"Cancel query"},m().createElement(Qi,{className:(0,r.cx)(u,O.pointer),"data-testid":"panel-cancel-query",onClick:E},m().createElement(i.Icon,{name:"sync-slash",size:"md"})))),m().createElement("div",{className:O.rightAligned},v&&m().createElement("div",{className:O.rightActions},sa(v,(e=>e)))));return m().createElement("div",{className:O.container,style:N,"data-testid":R},m().createElement("div",{className:O.loadingBarContainer},g===f.LoadingState.Loading?m().createElement(i.LoadingBar,{width:x,ariaLabel:"Panel loading bar"}):null),d&&m().createElement(m().Fragment,null,m().createElement(Wi,{menu:l,title:n,offset:h,dragClass:c,onOpenMenu:S},I),b&&m().createElement("div",{className:O.errorContainerFloating},m().createElement(oa,{message:b,onClick:y,ariaLabel:"Panel status"}))),T&&m().createElement("div",{className:(0,r.cx)(O.headerContainer,c),style:k,"data-testid":"header-container"},b&&m().createElement("div",{className:u},m().createElement(oa,{message:b,onClick:y,ariaLabel:"Panel status"})),I,l&&m().createElement(zi,{menu:l,title:n,placement:"bottom-end",menuButtonClass:(0,r.cx)(O.menuItem,u,"show-on-hover"),onOpenMenu:S})),m().createElement("div",{className:O.content,style:j,ref:C},e))}const sa=(e,t)=>{const n=m().Children.toArray(e).filter(Boolean);return n.length>0?t(n):null},la=(e,t)=>t?e.spacing.gridSize*e.components.panel.headerHeight:0,ca=(e,t)=>({contentStyle:{padding:("md"===e?t.components.panel.padding:0)*t.spacing.gridSize}}),ua=e=>{const{background:t,borderColor:n,padding:o}=e.components.panel;return{container:(0,r.css)({label:"panel-container",backgroundColor:t,border:`1px solid ${n}`,position:"relative",borderRadius:e.shape.radius.default,height:"100%",display:"flex",flexDirection:"column",".show-on-hover":{visibility:"hidden",opacity:"0"},"&:focus-visible, &:hover":{".show-on-hover":{visibility:"visible",opacity:"1"}},"&:focus-visible":{outline:`1px solid ${e.colors.action.focus}`},"&:focus-within":{".show-on-hover":{visibility:"visible",opacity:"1"}}}),loadingBarContainer:(0,r.css)({label:"panel-loading-bar-container",position:"absolute",top:0,width:"100%",overflow:"hidden"}),content:(0,r.css)({label:"panel-content",flexGrow:1}),headerContainer:(0,r.css)({label:"panel-header",display:"flex",alignItems:"center"}),pointer:(0,r.css)({cursor:"pointer"}),streaming:(0,r.css)({label:"panel-streaming",marginRight:0,color:e.colors.success.text,"&:hover":{color:e.colors.success.text}}),title:(0,r.css)({label:"panel-title",marginBottom:0,padding:e.spacing(0,o),textOverflow:"ellipsis",overflow:"hidden",whiteSpace:"nowrap",fontSize:e.typography.h6.fontSize,fontWeight:e.typography.h6.fontWeight}),items:(0,r.css)({display:"flex"}),item:(0,r.css)({display:"flex",justifyContent:"center",alignItems:"center"}),hiddenMenu:(0,r.css)({visibility:"hidden"}),menuItem:(0,r.css)({label:"panel-menu",border:"none",background:e.colors.secondary.main,"&:hover":{background:e.colors.secondary.shade}}),errorContainerFloating:(0,r.css)({label:"error-container",position:"absolute",left:0,top:0,zIndex:e.zIndex.tooltip}),rightActions:(0,r.css)({display:"flex",padding:e.spacing(0,o),gap:e.spacing(1)}),rightAligned:(0,r.css)({label:"right-aligned-container",marginLeft:"auto",display:"flex",alignItems:"center"}),titleItems:(0,r.css)({display:"flex",height:"100%"})}},da=e=>({panelWrap:r.css`
margin-bottom: ${e.spacing(1)};
`});function pa({isLoading:e,title:t,description:n,children:r,className:o="",headerActions:a,dataTestId:s}){const l=(0,i.useStyles2)(da),c=e?f.LoadingState.Loading:f.LoadingState.Done;return m().createElement("div",{className:`${o} ${l.panelWrap}`,"data-testid":s||"panel"},m().createElement(aa,{loadingState:c,title:t,description:n,actions:a},r))}var ma=n(9660),fa=n(219);const ha=()=>{const{isAvailable:e}=(0,fa.useAssistant)();return{hideAIButton:On.g.grafanaAssistantInProfilesDrilldown&&e&&!localStorage.getItem("grafana-pyroscope-app.forceShowAIButton"),isAvailable:e}};function ga(e,t,n,r,o,i,a){try{var s=e[i](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function ba(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var i=e.apply(t,n);function a(e){ga(i,r,o,a,s,"next",e)}function s(e){ga(i,r,o,a,s,"throw",e)}a(void 0)}))}}function ya(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function va(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter((function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable})))),r.forEach((function(t){ya(e,t,n[t])}))}return e}function Ea(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))})),e}function Sa(e){const{isAvailable:t,openAssistant:n}=(0,fa.useAssistant)();return t&&n?m().createElement(wa,Ea(va({},e),{openAssistant:n})):null}function wa({contextProvider:e,origin:t,autoSend:n=!0,title:r="Analyze with Assistant",size:o="sm",openAssistant:a,onClick:s}){const l=(0,i.useStyles2)(Oa);return m().createElement(i.Button,{icon:"ai-sparkle",onClick:ba((function*(){const r=yield e();if(!r)return;const{prompt:o,context:i}=r;null==s||s(),a({prompt:o,context:i,autoSend:n,origin:t})})),variant:"secondary",fill:"solid",size:o,title:r,"aria-label":r,className:l.button,"data-testid":"assistant-button"},r)}const Oa=e=>{const t=e.colors.secondary.main,n=e.colors.emphasize(t,.05),o=e.colors.background.canvas,i=e.shape.radius.default,a=`max(calc(${i} - 1px), 1px)`,s={content:'""',position:"absolute",inset:0,borderRadius:i,cornerShape:"squircle",background:"linear-gradient(90deg, rgb(168, 85, 247), rgb(249, 115, 22))",zIndex:-2,pointerEvents:"none"},l=e=>({content:'""',position:"absolute",inset:"1px",borderRadius:a,cornerShape:"squircle",background:`linear-gradient(${e}, ${e}), ${o}`,zIndex:-1,transition:"none",pointerEvents:"none"});return{button:(0,r.css)({label:"assistant-button",position:"relative",isolation:"isolate",border:"none",transition:"none !important","&::before":s,"&::after":Ea(va({},l(t)),{transition:"none"}),"&:hover":{transition:"none !important"},"&:hover::after":{background:`linear-gradient(${n}, ${n}), ${o}`}}),icon:(0,r.css)({label:"assistant-icon",position:"relative",isolation:"isolate",border:"none",background:"none",padding:e.spacing(.5),"&::before":Ea(va({},s),{transition:"background 0.1s ease"}),"&:hover::after":Ea(va({},l(t)),{background:`linear-gradient(${n}, ${n}), ${o}`})})}};const xa={system:{empty:()=>"\n You are a performance profiling expert and excel at analyzing profiles in the DOT format.\n In the DOT format, a row like N47 -> N61 means the function from N47 called the function from N61.\n"},user:{single:(e,t)=>`\n Analyze this flamegraph in DOT format and address these key aspects:\n - **Performance Bottleneck**: Identify the primary factors slowing down the process, consuming excessive memory, or causing a bottleneck in the system.\n - **Root Cause**: Explain clearly why these bottlenecks are occurring.\n - **Recommended Fix**: Suggest practical solutions for these issues.\n\n Guidelines:\n - Always use full function names without splitting them from package names.\n - Exclude numeric values, percentages, and node names (e.g., N1, N3, Node 1, Node 2).\n - Focus on user code over low-level runtime optimizations.\n - For standard library or runtime functions, explain their presence/function and link them to user code functions calling them. Avoid repetitive mentions from the same call chain.\n - Do not mention that the flamegraph profile is in DOT format.\n - Only use h5 and h6 markdown headers (e.g., ##### Performance Bottleneck, ###### Recommended Fix)\n - Do not use h1,h2,h3,h4 headers (e.g., ## Bottleneck, ### Root Cause, #### Recommended Fix)\n\n Format the response using markdown headers for each section corresponding to the key aspects.\n\n The profile type is: ${e}\n Profile in DOT format:\n ${t[0]}\n`,anton:(e,t)=>`\nGive me actionable feedback and suggestions on how I improve the application performance.\n\nDo not break function names.\nDo not show any numeric values, absolute or percents.\nDo not show node names like N1, N3, or Node 1, Node 2.\nDo not suggest low-level runtime optimisations, focus on the user code.\n\nAlways use full function names.\nNever split function and package name.\n\nRemove any numeric values, absolute or percents, from the output.\nRemove node names like N1, N3, or Node 1, Node 2 from the output.\n\nIf the function is widely known (e.g., a runtime or stdlib function), provide me concise explanation why the function is present in the profile and what could be the cause.\nIf a function is defined in the runtime or in the standard library, tell me which function in the user code calls it.\nAvoid mentioning functions from the same call-chain.\n\n5 suggestions is enough.\nThe profile type is ${e}\nBelow is the performance profile in DOT format:\n${t[0]}\n`,diff:(e,t)=>`\nAnalyze the differences between these two performance profiles presented in DOT format. Provide a detailed comparison focusing on the following aspects:\n\n- Performance Change: Determine how the performance has changed from the first profile to the second. Identify if there are new bottlenecks, improved or worsened performance areas, or significant changes in resource consumption.\n- Function Impact: Highlight no more than 3 specific functions that have undergone notable changes in their performance impact. Discuss any new functions that have appeared in the second profile or any existing functions that have significantly increased or decreased in resource usage.\n- Potential Causes: Discuss the possible reasons for these changes in performance, linking them to the differences in function execution or resource usage between the two profiles.\n\nGuidelines for Analysis:\n- Use full function names without separating them from their package names\n- Focus on user code rather than low-level runtime optimizations or standard library functions unless they are directly relevant to the user code's performance changes\n- Exclude numeric values, percentages, and node names (e.g., N1, N3, Node 1, Node 2) from the analysis\n- Format the response using markdown headers for each section to structure the analysis clearly\n\nThe profile type is: ${e}\n\nFirst performance profile in DOT format:\n${t[0]}\n\nSecond performance profile in DOT format:\n${t[1]}\n`}},Pa=({system:e,user:t,profileType:n,profiles:r})=>{const o=xa.system[e];if("function"!=typeof o)throw new Error(`Cannot find system prompt "${e}"!`);const i=xa.user[t];if("function"!=typeof i)throw new Error(`Cannot find user prompt "${t}"!`);return{system:o(n,r),user:i(n,r)}};var Ca=n(4164),Ta=n(7616);function Aa(e,t,n,r,o,i,a){try{var s=e[i](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}class ja extends A{get(e){var t,n=this;return(t=function*(){const t=new URLSearchParams({query:e.query,from:String(1e3*e.timeRange.from.unix()),until:String(1e3*e.timeRange.to.unix()),format:e.format});e.maxNodes&&t.set("max-nodes",String(e.maxNodes));const r=yield n.fetch(`/pyroscope/render?${t.toString()}`);switch(e.format){case"dot":return r.text();case"json":return r.json();default:throw new TypeError(`Unknown format "${e.format}"!`)}},function(){var e=this,n=arguments;return new Promise((function(r,o){var i=t.apply(e,n);function a(e){Aa(i,r,o,a,s,"next",e)}function s(e){Aa(i,r,o,a,s,"throw",e)}a(void 0)}))})()}constructor(e){super(e)}}function ka(e,t,n,r,o,i,a){try{var s=e[i](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function Na(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const Ra=100;function Ia(e,t,n,r){const{params:o,error:i}=Da(e,t),{error:a,isFetching:s,profiles:l}=function(e,t){const n=qo.build(e,ja);let r=La(e,t,n);const{isFetching:o,error:i,data:a}=(0,Ta.I)(function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter((function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable})))),r.forEach((function(t){Na(e,t,n[t])}))}return e}({},r));return{isFetching:o,error:i,profiles:a||[]}}(n,o);return{profileType:(0,At.y)(r).type,profiles:l,validationError:i,fetchError:a,isFetching:s}}function _a(){var e;return e=function*(e,t,n,r){const o=qo.build(n,ja),{params:i,error:a}=Da(e,t);if(a)throw a;const s=La(n,i,o);return{profiles:(yield Ca.q.fetchQuery(s))||[],profileType:(0,At.y)(r).type}},_a=function(){var t=this,n=arguments;return new Promise((function(r,o){var i=e.apply(t,n);function a(e){ka(i,r,o,a,s,"next",e)}function s(e){ka(i,r,o,a,s,"throw",e)}a(void 0)}))},_a.apply(this,arguments)}function Da(e,t){let n,r=t;e&&2!==t.length?(n=new Error(`Invalid number of fetch parameters for analyzing the diff flame graph (${t.length})!`),r=[]):e||1===t.length||(n=new Error(`Invalid number of fetch parameters for analyzing the flame graph (${t.length})!`),r=[]);return r.some((({timeRange:e})=>0===e.from.unix()||0===e.to.unix()))&&(n=new Error("Invalid time range: from and to values must be non-zero"),r=[]),{params:r,error:n}}function La(e,t,n){return{queryKey:["dot-profiles",e,...t.flatMap((({query:e,timeRange:t})=>[e,t.from.unix(),t.to.unix()])),Ra],enabled:t.length>0,queryFn:()=>Promise.all(t.map((({query:e,timeRange:t})=>n.get({query:e,timeRange:t,format:"dot",maxNodes:Ra}).then((e=>e.replace(/fontsize=\d+ /g,"").replace(/id="node\d+" /g,"").replace(/labeltooltip=".*\)" /g,"").replace(/tooltip=".*\)" /g,"").replace(/(N\d+ -> N\d+).*/g,"$1").replace(/N\d+ \[label="other.*\n/,"").replace(/shape=box /g,"").replace(/fillcolor="#\w{6}"/g,"").replace(/color="#\w{6}" /g,""))))))}}function Fa(e,t,n,r,o,i,a){try{var s=e[i](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function Ba(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var i=e.apply(t,n);function a(e){Fa(i,r,o,a,s,"next",e)}function s(e){Fa(i,r,o,a,s,"throw",e)}a(void 0)}))}}function $a({dataSourceUid:e,profileMetricId:t,isDiff:n,fetchParams:o}){const{isAvailable:i}=(0,fa.useAssistant)();if(!i)return null;const{error:s}=Da(!0,o);return s?null:m().createElement("div",{className:(0,r.css)({marginTop:"10px"})},m().createElement(Sa,{origin:"grafana-pyroscope-app/diff-flame-graph",contextProvider:Ba((function*(){try{const{profiles:r,profileType:i}=yield function(e,t,n,r){return _a.apply(this,arguments)}(n,o,e,t),a=Pa({system:"empty",user:"diff",profileType:i,profiles:r});return{prompt:"Analyze the differences between these two performance profiles.",context:[(0,fa.createAssistantContextItem)("datasource",{datasourceUid:e}),(0,fa.createAssistantContextItem)("structured",{title:"DOT Profiles and instructions",data:{stringifiedData:`${a.system}\n${a.user}`}})]}}catch(e){return void(0,a.jx)(e,["Failed to fetch DOT profiles for analysis"])}}))}))}var Ma=n(3604);function Va({children:e,onClick:t,disabled:n,interactionName:r}){const o=(0,i.useStyles2)(Ua),{isEnabled:a,error:s,isFetching:l}=function(){const{data:e,isFetching:t,error:n}=(0,Ta.I)({queryKey:["llm"],queryFn:()=>Ma.Sn()});return n&&be.v.error(n,{info:"Error while checking the status of the Grafana LLM plugin!"}),{isEnabled:Boolean(e),isFetching:t,error:n}}();let c="ai",u="";return l?(c="fa fa-spinner",u="Checking the status of the Grafana LLM plugin..."):s?(c="exclamation-triangle",u="Error while checking the status of the Grafana LLM plugin!"):a||(c="shield-exclamation",u="Grafana LLM plugin missing or not configured! Please check the plugins administration page."),m().createElement(i.Button,{className:o.aiButton,size:"md",fill:"text",icon:c,disabled:!a||n,tooltip:u,tooltipPlacement:"top",onClick:e=>{(0,d.r)(r),t(e)}},e)}const Ua=()=>({aiButton:r.css`
padding: 0 4px;
`});var Ga=n(7879);const qa=e=>{const t=document.querySelector('[placeholder^="Search"]');if(null===t)return void be.v.error(new Error("Cannot find search input element!"));((e,t)=>{const n=Object.getOwnPropertyDescriptor(e,"value").set,r=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(e),"value").set;n&&n!==r?r.call(e,t):n.call(e,t)})(t,e.target.textContent.trim()),t.dispatchEvent(new Event("input",{bubbles:!0}))},Ka={overrides:{code:{component:({children:e})=>{const t=(0,i.useStyles2)(Wa);return"string"==typeof e&&e.includes("\n")?m().createElement("code",null,e):m().createElement("code",{className:t.searchLink,title:"Search for this node",onClick:qa},e)}}}};function za({reply:e}){var t;const n=(0,i.useStyles2)(Wa);return m().createElement("div",{className:n.container},null==e||null===(t=e.messages)||void 0===t?void 0:t.filter((e=>"system"!==e.role)).map((e=>m().createElement(m().Fragment,null,m().createElement("div",{className:n.reply},m().createElement(Ga.Ay,{options:Ka},e.content||"")),m().createElement("hr",null)))),m().createElement("div",{className:n.reply},m().createElement(Ga.Ay,{options:Ka},e.text)))}const Wa=()=>({container:r.css`
width: 100%;
height: 100%;
`,reply:r.css`
font-size: 13px;
& ol,
& ul {
margin: 0 0 16px 24px;
}
`,searchLink:r.css`
color: rgb(255, 136, 51);
border: 1px solid transparent;
padding: 2px 4px;
cursor: pointer;
font-size: 13px;
&:hover,
&:focus,
&:active {
box-sizing: border-box;
border: 1px solid rgb(255, 136, 51, 0.8);
border-radius: 4px;
}
`}),Ha=()=>({textarea:r.css`
margin-bottom: 8px;
`,sendButton:r.css`
float: right;
border-top-left-radius: 0;
border-bottom-left-radius: 0;
`});function Ya({onSubmit:e}){const t=(0,i.useStyles2)(Ha),{question:n,onChangeInput:r,onClickSend:o}=function(e){const[t,n]=(0,p.useState)(""),r=(0,p.useCallback)((e=>{n(e.target.value)}),[]),o=(0,p.useCallback)((()=>{const r=t.trim();r&&(e(r),n(""))}),[t,e]);return{question:t,onChangeInput:r,onClickSend:o}}(e);return m().createElement("div",null,m().createElement(i.TextArea,{className:t.textarea,placeholder:"Ask a follow-up question...",value:n,onChange:r,onKeyDown:e=>{"Enter"!==e.code||e.shiftKey||o()}}),m().createElement(i.Button,{className:t.sendButton,onClick:o},"Send"))}var Za=n(9239);function Xa(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class Ja extends o.Bs{constructor(){super({key:"ai-panel"}),Xa(this,"useSceneAiPanel",((e,t)=>{const n=o.jh.findByKeyAndType(this,"dataSource",qt).useState().value,r=rn(this,"profileMetricId"),{profileType:i,profiles:a,validationError:s,fetchError:l,isFetching:c}=Ia(e,t,n,r),{reply:u,error:d,retry:m}=function(e,t){const[n,r]=(0,p.useState)(""),[o,i]=(0,p.useState)(!1),[a,s]=(0,p.useState)(!1),[l,c]=(0,p.useState)([]),[u,d]=(0,p.useState)(null),[m,f]=(0,p.useState)(),h=(0,p.useCallback)((e=>{c(e),d(null),r(""),i(!0),s(!1);const t=Za.qH({model:"gpt-4-1106-preview",messages:e}).pipe(Za.qA()).subscribe({next:r,error(e){d(e),i(!1),s(!0),f(void 0)},complete(){i(!1),s(!0),f(void 0)}});f(t)}),[]),g=(0,p.useCallback)((e=>{const t=[{role:"assistant",content:n},{role:"user",content:e}];try{h([...l,...t])}catch(e){d(e)}}),[l,n,h]);return(0,p.useEffect)((()=>{if(!t.length||l.length>0)return;const n=Pa({system:"empty",user:2===t.length?"diff":"single",profileType:e,profiles:t});try{h([{role:"system",content:n.system},{role:"system",content:n.user}])}catch(e){d(e)}}),[l.length,e,t,t.length,h]),(0,p.useEffect)((()=>()=>{m&&(m.unsubscribe(),f(void 0))}),[m]),{reply:{text:n,hasStarted:o,hasFinished:a,messages:l,askFollowupQuestion:g},retry(){if(l.length>0)try{h(l)}catch(e){d(e)}},error:u}}(i,a);return{data:{validationError:s,isLoading:c||!c&&!l&&!d&&!u.text.trim(),fetchError:l,llmError:d,reply:u,shouldDisplayReply:Boolean((null==u?void 0:u.hasStarted)||(null==u?void 0:u.hasFinished)),shouldDisplayFollowUpForm:!l&&!d&&Boolean(null==u?void 0:u.hasFinished)},actions:{retry:m,submitFollowupQuestion(e){u.askFollowupQuestion(e)}}}}))}}Xa(Ja,"Component",(({model:e,isDiff:t,fetchParams:n,onClose:r})=>{const o=(0,i.useStyles2)(Qa),{data:a,actions:s}=e.useSceneAiPanel(t,n);return m().createElement(pa,{className:o.sidePanel,title:"Flame graph analysis",isLoading:a.isLoading,headerActions:m().createElement(i.IconButton,{title:"Close panel",name:"times-circle",variant:"secondary","aria-label":"close",onClick:r}),dataTestId:"ai-panel"},m().createElement("div",{className:o.content},a.validationError&&m().createElement(Gi._,{severity:"error",title:"Validation error!",error:a.validationError}),a.fetchError&&m().createElement(Gi._,{severity:"error",title:"Error while loading profile data!",message:"Sorry for any inconvenience, please try again later.",error:a.fetchError}),a.shouldDisplayReply&&m().createElement(za,{reply:a.reply}),a.isLoading&&m().createElement(m().Fragment,null,m().createElement(i.Spinner,{inline:!0})," Analyzing..."),a.llmError&&m().createElement(i.Alert,{title:"An error occured while generating content using OpenAI!",severity:"warning"},m().createElement("div",null,m().createElement("div",null,m().createElement("p",null,a.llmError.message),m().createElement("p",null,"Sorry for any inconvenience, please retry or if the problem persists, contact your organization admin."))),m().createElement(i.Button,{className:o.retryButton,variant:"secondary",fill:"outline",onClick:()=>s.retry()},"Retry")),a.shouldDisplayFollowUpForm&&m().createElement(Ya,{onSubmit:s.submitFollowupQuestion})))}));const Qa=e=>({sidePanel:r.css`
flex: 1 0 50%;
margin-left: 8px;
max-width: calc(50% - 4px);
`,title:r.css`
margin: -4px 0 4px 0;
`,content:r.css`
padding: ${e.spacing(1)};
`,retryButton:r.css`
float: right;
`});class es extends f.BusEventWithPayload{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(es,"type","diff-auto-select");class ts extends f.BusEventWithPayload{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(ts,"type","diff-choose-preset");var ns=n(9993);function rs(e,t,n,r,o,i,a){try{var s=e[i](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}class os extends A{get(e){var t,n=this;return(t=function*(){const t=new URLSearchParams({leftQuery:e.leftQuery,leftFrom:String(1e3*e.leftTimeRange.from.unix()),leftUntil:String(1e3*e.leftTimeRange.to.unix()),rightQuery:e.rightQuery,rightFrom:String(1e3*e.rightTimeRange.from.unix()),rightUntil:String(1e3*e.rightTimeRange.to.unix())});e.maxNodes&&t.set("max-nodes",String(e.maxNodes));const r=yield n.fetch(`/pyroscope/render-diff?${t.toString()}`);return yield r.json()},function(){var e=this,n=arguments;return new Promise((function(r,o){var i=t.apply(e,n);function a(e){rs(i,r,o,a,s,"next",e)}function s(e){rs(i,r,o,a,s,"throw",e)}a(void 0)}))})()}constructor(e){super(e)}}function is(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function as(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))})),e}function ss({enabled:e,dataSourceUid:t,baselineTimeRange:n,baselineQuery:r,comparisonTimeRange:o,comparisonQuery:i}){const[a]=(0,ns.I)(),s=qo.build(t,os),{isFetching:l,error:c,data:u,refetch:d}=(0,Ta.I)({placeholderData:e=>e,enabled:Boolean(e&&a),queryKey:["diff-profile",t,r,n.from.unix(),n.to.unix(),i,o.from.unix(),o.to.unix(),a],queryFn:()=>{s.abort();const e={leftQuery:r,leftTimeRange:n,rightQuery:i,rightTimeRange:o,maxNodes:a};return s.get(e).then((e=>({profile:{version:e.version,flamebearer:e.flamebearer,metadata:e.metadata}})))}});return as(function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter((function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable})))),r.forEach((function(t){is(e,t,n[t])}))}return e}({isFetching:l,error:s.isAbortError(c)?null:c},u),{refetch:d})}function ls({onClickAutoSelect:e,onClickChoosePreset:t,onOpenLearnHow:n}){const r=(0,i.useStyles2)(cs),[o,a]=(0,p.useState)(!1);return m().createElement(Gi._,{severity:"info",title:"Select both the baseline and the comparison flame graph ranges to view the diff flame graph",message:m().createElement("div",{className:r.infoMsg},m().createElement("p",null,"How?"),m().createElement("p",null,m().createElement(i.Button,{variant:"primary",onClick:e},"Auto-select")," ","or"," ",m().createElement(i.Button,{variant:"primary",fill:"text",className:r.textButton,onClick:t},"choose a preset")),m().createElement("p",null,"Alternatively:"),m().createElement(i.Collapse,{label:"Click here to learn how to select the flame graph ranges with the mouse",collapsible:!0,className:r.collapse,isOpen:o,onToggle:()=>{o||n(),a(!o)}},m().createElement("div",{className:r.collapseContent},m().createElement("ol",null,m().createElement("li",null,"Ensure that the “Flame graph” range selection mode is selected"),m().createElement("li",null,"Use your mouse to select the desired time ranges on both the baseline and the comparison time series")),m().createElement("img",{src:"public/plugins/grafana-pyroscope-app/img/8cdf4d2e2df8326311ab.gif",alt:"How to view the diff flame graph"}))))})}const cs=e=>({infoMsg:r.css`
padding: ${e.spacing(2)} 0 0 0;
`,textButton:r.css`
padding: 0;
`,collapse:r.css`
background: transparent;
border: 0;
`,collapseContent:r.css`
padding: 0 ${e.spacing(5)};
& img {
max-width: 100%;
width: auto;
margin-top: ${e.spacing(2)};
}
`});function us(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class ds extends o.Bs{buildTitle(){const e=rn(this,"serviceName"),t=rn(this,"profileMetricId"),n=(0,At.y)(t).type;return m().createElement(m().Fragment,null,m().createElement(ma.S,{size:"small"}),"Diff flame graph for ",e," (",n,")")}constructor(){super({key:"diff-flame-graph",aiPanel:new Ja}),us(this,"useSceneDiffFlameGraph",(()=>{const{aiPanel:e}=this.useState(),{baselineTimeRange:t,comparisonTimeRange:n}=this.parent.useDiffTimeRanges(),r=Gt(this,"filtersBaseline"),i=Gt(this,"filtersComparison"),{settings:a,error:s}=(0,Ui._)(),l=o.jh.findByKeyAndType(this,"dataSource",qt).useState().value,c=Boolean(r&&i&&t.from.unix()&&t.to.unix()&&n.from.unix()&&n.to.unix()),{isFetching:u,error:d,profile:p}=ss({enabled:c,dataSourceUid:l,baselineTimeRange:t,baselineQuery:r,comparisonTimeRange:n,comparisonQuery:i}),m=c&&!u&&!d&&0===(null==p?void 0:p.flamebearer.numTicks),f=Boolean(c&&!d&&!m&&p),h=!c;return{data:{title:this.buildTitle(),isLoading:u,fetchProfileError:d,noProfileDataAvailable:m,shouldDisplayFlamegraph:f,hasMissingSelections:h,profile:p,settings:a,fetchSettingsError:s,ai:{panel:e,fetchParams:[{query:r,timeRange:t},{query:i,timeRange:n}]}},actions:{}}})),us(this,"onClickAutoSelect",(()=>{(0,d.r)("g_pyroscope_app_diff_auto_select_clicked"),this.publishEvent(new es({wholeRange:!1}),!0)})),us(this,"onClickChoosePreset",(()=>{(0,d.r)("g_pyroscope_app_diff_choose_preset_clicked"),this.publishEvent(new ts({}),!0)})),us(this,"onOpenLearnHow",(()=>{(0,d.r)("g_pyroscope_app_diff_learn_how_clicked")}))}}us(ds,"Component",(({model:e})=>{var t,n;const r=(0,i.useStyles2)(ps),{data:s}=e.useSceneDiffFlameGraph(),l=Vi(),{hideAIButton:c}=ha(),u=s.isLoading||s.hasMissingSelections||s.noProfileDataAvailable;(0,p.useEffect)((()=>{u&&l.close()}),[u,l]),s.fetchSettingsError&&(0,a.HA)(["Error while retrieving the plugin settings!","Some features might not work as expected (e.g. flamegraph export options). Please try to reload the page, sorry for the inconvenience."]);const d=(0,p.useMemo)((()=>m().createElement(m().Fragment,null,s.title,s.isLoading&&m().createElement(i.Spinner,{inline:!0,className:r.spinner}))),[s.isLoading,s.title,r.spinner]),f=o.jh.findByKeyAndType(e,"dataSource",qt).useState().value,h=rn(e,"profileMetricId"),g=c?m().createElement($a,{dataSourceUid:f,profileMetricId:h,isDiff:!0,fetchParams:s.ai.fetchParams}):m().createElement(Va,{disabled:u||l.isOpen("ai"),onClick:()=>l.open("ai"),interactionName:"g_pyroscope_app_explain_flamegraph_clicked"},"Explain Diff Flame Graph");return m().createElement("div",{className:r.flex},m().createElement(pa,{dataTestId:"diff-flame-graph-panel",className:r.flamegraphPanel,title:d,isLoading:s.isLoading,headerActions:g},s.hasMissingSelections&&m().createElement(ls,{onClickAutoSelect:e.onClickAutoSelect,onClickChoosePreset:e.onClickChoosePreset,onOpenLearnHow:e.onOpenLearnHow}),s.fetchProfileError&&m().createElement(Gi._,{severity:"error",title:"Error while loading profile data!",error:s.fetchProfileError}),s.noProfileDataAvailable&&m().createElement(Gi._,{severity:"warning",title:"No profile data available",message:"Please verify that you've selected adequate filters and time ranges."}),s.shouldDisplayFlamegraph&&m().createElement(Mi.C,{diff:!0,profile:s.profile,enableFlameGraphDotComExport:null===(t=s.settings)||void 0===t?void 0:t.enableFlameGraphDotComExport,collapsedFlamegraphs:null===(n=s.settings)||void 0===n?void 0:n.collapsedFlamegraphs,showAnalyzeWithAssistant:!1})),l.isOpen("ai")&&m().createElement(s.ai.panel.Component,{model:s.ai.panel,isDiff:!0,fetchParams:s.ai.fetchParams,onClose:l.close}))}));const ps=e=>({flex:r.css`
display: flex;
`,flamegraphPanel:r.css`
min-width: 0;
flex-grow: 1;
`,sidePanel:r.css`
flex: 1 0 50%;
margin-left: 8px;
max-width: calc(50% - 4px);
`,spinner:r.css`
margin-left: ${e.spacing(1)};
`,aiButton:r.css`
margin-top: ${e.spacing(1)};
`}),ms="https://grafana.qualtrics.com/jfe/form/SV_6Gav4IUU6jcYfd4",fs=()=>{const e=(0,i.useStyles2)(hs);return m().createElement("div",{className:e.wrapper},m().createElement("a",{href:ms,className:e.feedback,title:"Share your thoughts about Profiles in Grafana.",target:"_blank",rel:"noreferrer noopener"},m().createElement(i.Icon,{name:"comment-alt-message"})," Give feedback"))},hs=e=>({wrapper:(0,r.css)({display:"flex",gap:e.spacing(1),justifyContent:"flex-end",paddingTop:"4px"}),feedback:(0,r.css)({alignSelf:"center",color:e.colors.text.secondary,fontSize:e.typography.bodySmall.fontSize,"&:hover":{color:e.colors.text.link}})});function gs(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class bs extends o.Bs{onActivate(){[io.N.BASELINE,io.N.COMPARISON].forEach((e=>{this._subs.add(o.jh.findByKeyAndType(this,`${e}-panel`,Bi).state.$timeRange.subscribeToState(((e,t)=>{e.from===t.from&&e.to===t.to||this.setState({value:null})})))}))}openSelect(){this.setState({isSelectOpen:!0})}closeSelect(){this.setState({isSelectOpen:!1})}reset(){this.setState({value:null,isSelectOpen:!1,isModalOpen:!1})}static Component({model:e}){const t=(0,i.useStyles2)(ys),{value:n,isSelectOpen:r,isModalOpen:o}=e.useState();return m().createElement(m().Fragment,null,m().createElement("div",{className:t.presetsContainer},m().createElement(i.Select,{className:t.select,placeholder:"Choose a preset",value:n,options:bs.PRESETS,onChange:e.onChangePreset,isOpen:r,onOpenMenu:e.onOpenSelect,onCloseMenu:e.onCloseSelect}),m().createElement(i.Button,{icon:"save",variant:"secondary",tooltip:"Save the current time ranges and filters as a custom preset",onClick:e.onClickSave})),m().createElement(i.Modal,{title:"Custom user presets",isOpen:o,closeOnEscape:!0,closeOnBackdropClick:!0,onDismiss:e.closeModal},m().createElement("p",null,"This feature, which would allow you to save the current time ranges and filters, is currently not implemented."),m().createElement("p",null,"Please let us know if you would be interested to use it by"," ",m().createElement("a",{href:ms,target:"_blank",rel:"noreferrer noopener",className:t.link},"leaving us your feedback.")),m().createElement("p",null,"Thank you!"),m().createElement(i.Modal.ButtonRow,null,m().createElement(i.Button,{variant:"secondary",fill:"outline",onClick:e.closeModal},"Cancel"),m().createElement(i.Button,{onClick:e.closeModal,disabled:!0},"Save"))))}constructor(){super({name:"compare-presets",label:"Comparison presets",value:null,isModalOpen:!1,isSelectOpen:!1}),gs(this,"_variableDependency",new o.Sh(this,{variableNames:["dataSource","serviceName"],onReferencedVariableValueChanged:()=>{this.reset()}})),gs(this,"onChangePreset",(e=>{var t;if((0,d.r)("g_pyroscope_app_diff_preset_selected",{value:e.value}),this.closeSelect(),"dummy"!==e.value){if(null===(t=e.value)||void 0===t?void 0:t.startsWith("auto-select-"))return this.setState({value:null}),void this.publishEvent(new es({wholeRange:"auto-select-whole"===e.value}),!0);[io.N.BASELINE,io.N.COMPARISON].forEach((t=>{const n=o.jh.findByKeyAndType(this,`${t}-panel`,Bi);n.toggleTimeRangeSync(!1),n.applyPreset(e[t])})),this.setState({value:e.value})}else this.setState({value:null,isModalOpen:!0})})),gs(this,"onClickSave",(()=>{(0,d.r)("g_pyroscope_app_diff_preset_save_clicked"),this.setState({isModalOpen:!0})})),gs(this,"closeModal",(()=>{this.setState({isModalOpen:!1})})),gs(this,"onOpenSelect",(()=>{setTimeout((()=>this.openSelect()),0)})),gs(this,"onCloseSelect",(()=>{this.closeSelect()})),this.addActivationHandler(this.onActivate.bind(this))}}gs(bs,"PRESETS",[{label:"Built-in presets",value:"built-in",options:[{value:"last hour (30m-window)",label:"Last hour (30m-window)",baseline:{from:"now-1h",to:"now",diffFrom:"now-1h",diffTo:"now-30m",label:"last hour"},comparison:{from:"now-1h",to:"now",diffFrom:"now-30m",diffTo:"now",label:"last hour"}},{value:"last hour (1h-window)",label:"Last hour (1h-window)",baseline:{from:"now-1h",to:"now",diffFrom:"now-1h",diffTo:"now",label:"last hour"},comparison:{from:"now-1h",to:"now",diffFrom:"now-1h",diffTo:"now",label:"last hour"}},{value:"6h ago vs now",label:"6h ago vs now (30m-window)",baseline:{from:"now-375m",to:"now-315m",diffFrom:"now-375m",diffTo:"now-345m",label:"6h ago"},comparison:{from:"now-1h",to:"now",diffFrom:"now-30m",diffTo:"now",label:"last hour"}},{value:"24h ago vs now",label:"24h ago vs now (30m-window)",baseline:{from:"now-1455m",to:"now-1395m",diffFrom:"now-1455m",diffTo:"now-1425m",label:"24h ago"},comparison:{from:"now-1h",to:"now",diffFrom:"now-30m",diffTo:"now",label:"last hour"}},{value:"auto-select-25",label:"Auto-select (25% range)"},{value:"auto-select-whole",label:"Auto-select (whole range)"}]},{label:"My presets",value:"custom",options:[{label:"Dummy preset saved earlier",value:"dummy"}]}]);const ys=e=>({presetsContainer:r.css`
display: flex;
`,select:r.css`
min-width: ${e.spacing(24)};
text-align: left;
`,link:r.css`
color: ${e.colors.text.link};
`});function vs(){return e=>{const t=new Map,n=e.subscribeToEvent(b,(n=>{var r;const i=null===(r=n.payload.series)||void 0===r?void 0:r[0];(null==i?void 0:i.refId)?(t.set(i.refId,Math.max(...i.fields[1].values)),function(e,t){const n=o.jh.findAllObjects(e,(e=>e instanceof o.Eb&&"timeseries"===e.state.pluginId));for(const e of n)e.clearFieldConfigCache(),e.setState({fieldConfig:(0,g.merge)((0,g.cloneDeep)(e.state.fieldConfig),{defaults:{max:t}})})}(e,Math.max(...t.values()))):be.v.warn("Missing refId! Cannot sync y-axis on the timeseries.",n.payload.series)}));return()=>{n.unsubscribe()}}}class Es extends o.Bs{onActivate(){C.locationService.partial({},!0);const e=o.jh.findByKeyAndType(this,"profileMetricId",Lt);return e.setState({query:Lt.QUERY_SERVICE_NAME_DEPENDENT}),e.update(!0),this.subscribeToEvents(),()=>{e.setState({query:Lt.QUERY_DEFAULT}),e.update(!0)}}subscribeToEvents(){this._subs.add(this.subscribeToEvent(es,(e=>{const t=e.payload.wholeRange,{baselinePanel:n,comparisonPanel:r}=this.state;n.toggleTimeRangeSync(!1),r.toggleTimeRangeSync(!1),n.autoSelectDiffRange(t),r.autoSelectDiffRange(t)}))),this._subs.add(this.subscribeToEvent(ts,(()=>{this.state.presetsPicker.openSelect()}))),this._subs.add(this.subscribeToEvent(mi,(e=>{const{source:t,enable:n,timeRange:r,annotationTimeRange:o}=e.payload,{baselinePanel:i,comparisonPanel:a}=this.state,s=t===io.N.BASELINE?a:i;n&&this.syncTimeRanges(s,r,o),a.toggleTimeRangeSync(n),i.toggleTimeRangeSync(n)}))),this._subs.add(this.subscribeToEvent(hi,(e=>{const{source:t,timeRange:n,annotationTimeRange:r}=e.payload,{baselinePanel:o,comparisonPanel:i}=this.state,a=t===io.N.BASELINE?i:o;this.syncTimeRanges(a,n,r)}))),this._subs.add(this.subscribeToEvent(fi,(e=>{const{source:t}=e.payload,{baselinePanel:n,comparisonPanel:r}=this.state;(t===io.N.BASELINE?r:n).refreshTimeseries()})))}syncTimeRanges(e,t,n){t&&e.setTimeRange(t),n&&e.setDiffRange({from:n.from.toISOString(),to:n.to.toISOString()})}getVariablesAndGridControls(){return{variables:[o.jh.findByKeyAndType(this,"serviceName",Vt),o.jh.findByKeyAndType(this,"profileMetricId",Lt),this.state.presetsPicker],gridControls:[]}}static Component({model:e}){const t=(0,i.useStyles2)(Ss),{baselinePanel:n,comparisonPanel:r,body:o}=e.useState();return m().createElement("div",{className:t.container},m().createElement("div",{className:t.columns},m().createElement(n.Component,{model:n}),m().createElement(r.Component,{model:r})),m().createElement(o.Component,{model:o}))}constructor({useAncestorTimeRange:e,clearDiffRange:t,baselineFilters:n,comparisonFilters:r}){super({key:"explore-diff-flame-graph",baselinePanel:new Bi({target:io.N.BASELINE,useAncestorTimeRange:Boolean(e),clearDiffRange:Boolean(t),filters:n||[]}),comparisonPanel:new Bi({target:io.N.COMPARISON,useAncestorTimeRange:Boolean(e),clearDiffRange:Boolean(t),filters:r||[]}),$behaviors:[new o.Gg.K2({key:"metricCrosshairSync",sync:f.DashboardCursorSync.Crosshair}),vs()],body:new ds,presetsPicker:new bs}),function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(this,"useDiffTimeRanges",(()=>{const{baselinePanel:e,comparisonPanel:t}=this.state,{annotationTimeRange:n}=e.useDiffTimeRange(),{annotationTimeRange:r}=t.useDiffTimeRange();return{baselineTimeRange:n,comparisonTimeRange:r}})),this.addActivationHandler(this.onActivate.bind(this))}}const Ss=e=>({container:r.css`
width: 100%;
display: flex;
flex-direction: column;
`,columns:r.css`
display: flex;
flex-direction: row;
gap: ${e.spacing(1)};
margin-bottom: ${e.spacing(1)};
& > div {
flex: 1 1 0;
}
`});function ws(e,t,n,r,o,i,a){try{var s=e[i](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function Os(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var i=e.apply(t,n);function a(e){ws(i,r,o,a,s,"next",e)}function s(e){ws(i,r,o,a,s,"throw",e)}a(void 0)}))}}class xs extends A{githubLogin(e){var t=this;return Os((function*(){const n=yield t.fetch("/vcs.v1.VCSService/GithubLogin",{method:"POST",body:JSON.stringify({authorizationCode:e})});return yield n.json()}))()}githubApp(){var e=this;return Os((function*(){const t=yield e.fetch("/vcs.v1.VCSService/GithubApp",{method:"POST",body:JSON.stringify({})});return yield t.json()}))()}}function Ps(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class Cs{isUserTokenExpired(e=0){return Date.now()>=this.expiry.getTime()-e}static decode(e){if(void 0===e||""===e)return;let t;try{t=atob(e)}catch(e){return void be.v.error(e,{info:"Failed to base64 decode GitSession value"})}const{payload:n,isLegacy:r}=Cs.tryDecode(t);return r?new Cs(e,864e13):new Cs(n.metadata,Number(n.expiry))}static tryDecode(e){try{return{payload:JSON.parse(e),isLegacy:!1}}catch(e){return{payload:void 0,isLegacy:!0}}}constructor(e,t){Ps(this,"oauthTokenMetadata",void 0),Ps(this,"expiry",void 0),this.oauthTokenMetadata=e,this.expiry=new Date(t)}}function Ts(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const As="pyroscope_git_session";class js{getCookie(){return this.syncCookieWithBrowser(),this.sessionCookie}setCookie(e){e.startsWith(`${As}=`)||(e=`${As}=${e}`);const t=js.getCookieFromJar(e,As);void 0!==t&&(this.deleteLegacyCookie(),this.rawCookie=t,this.sessionCookie=Cs.decode(t.value),document.cookie=`${e}; path=/`)}deleteCookie(){document.cookie=`${As}=; Path=/; expires=Thu, 01 Jan 1970 00:00:00 UTC;`,this.deleteLegacyCookie(),this.rawCookie=void 0,this.sessionCookie=void 0}deleteLegacyCookie(){document.cookie="GitSession=; Path=/; expires=Thu, 01 Jan 1970 00:00:00 UTC;"}syncCookieWithBrowser(){var e,t;const n=js.getCookieFromJar(document.cookie,As);(null==n?void 0:n.key)===(null===(e=this.rawCookie)||void 0===e?void 0:e.key)&&(null==n?void 0:n.value)===(null===(t=this.rawCookie)||void 0===t?void 0:t.value)||(void 0===n?this.deleteCookie():(this.rawCookie=n,this.sessionCookie=Cs.decode(n.value)))}static getCookieFromJar(e,t){return e.split(";").map((e=>{const[t,...n]=e.trim().split("="),r=n.join("=");return{key:t.trim(),value:null==r?void 0:r.trim()}})).find((({key:e})=>e===t))}constructor(){Ts(this,"rawCookie",void 0),Ts(this,"sessionCookie",void 0)}}const ks=new js;var Ns=n(4137);const Rs=800,Is=950;function _s(e,t,n){const r=function(e,t,n){const r=(o=C.config.appSubUrl||"/").endsWith("/")?o.slice(0,-1):o;var o;const i=`${window.location.origin}${r}${Ns.Gy}${Ns.bw.GITHUB_CALLBACK}`,a=new URL("/login/oauth/authorize","https://github.com");return a.searchParams.set("client_id",e),n&&a.searchParams.set("redirect_uri",n),a.searchParams.set("scope","repo"),a.searchParams.set("state",btoa(JSON.stringify({redirect_uri:i,nonce:t}))),a.toString()}(e,t,n),{top:o}=window;var i,a;const s=(null!==(i=null==o?void 0:o.outerWidth)&&void 0!==i?i:0)/2+(null!==(a=null==o?void 0:o.screenX)&&void 0!==a?a:0)-Rs/2;var l,c;const u=(null!==(l=null==o?void 0:o.outerHeight)&&void 0!==l?l:0)/2+(null!==(c=null==o?void 0:o.screenY)&&void 0!==c?c:0)-Is/2;return window.open(r,"GitHub Login",`toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=${Rs}, height=${Is}, top=${u}, left=${s}`)}function Ds(e,t,n,r,o,i,a){try{var s=e[i](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function Ls(){var e;return e=function*(e,t,n,r,o){if(r&&r.close(),null==n?void 0:n.isUserTokenExpired())try{return void(yield t.refresh())}catch(e){be.v.error(e,{info:"Failed to refresh GitHub user token"}),ks.deleteCookie()}try{const{clientID:t,callbackURL:n}=yield e.githubApp();o(_s(t,Js,n))}catch(e){(0,a.jx)(e,["Failed to start login flow.",e.message])}},Ls=function(){var t=this,n=arguments;return new Promise((function(r,o){var i=e.apply(t,n);function a(e){Ds(i,r,o,a,s,"next",e)}function s(e){Ds(i,r,o,a,s,"throw",e)}a(void 0)}))},Ls.apply(this,arguments)}function Fs(e,t,n,r,o,i,a){try{var s=e[i](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function Bs(){var e;return e=function*(e,t,n){const r=t.get("code");if(!r)return"";const o=t.get("state");if(!o)throw new Error("Invalid state parameter!");let i;try{i=JSON.parse(atob(o))}catch(e){throw new Error("Invalid state parameter!")}if(i.nonce!==n)throw new Error("Invalid nonce parameter!");return(yield e.githubLogin(r)).cookie},Bs=function(){var t=this,n=arguments;return new Promise((function(r,o){var i=e.apply(t,n);function a(e){Fs(i,r,o,a,s,"next",e)}function s(e){Fs(i,r,o,a,s,"throw",e)}a(void 0)}))},Bs.apply(this,arguments)}function $s(e,t,n,r,o,i,a){try{var s=e[i](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function Ms({vcsClient:e,externalWindow:t,setExternalWindow:n,setSessionCookie:r,nonce:o}){(0,p.useEffect)((()=>{const i=function(){var s,l=(s=function*(){if(t&&!t.closed){try{const i=function(e){try{return new URL(e.location.href).searchParams}catch(e){return null}}(t);if(null!==i){const a=yield function(e,t,n){return Bs.apply(this,arguments)}(e,i,o);if(a)return r(a),t.close(),void n(null)}}catch(e){return(0,a.jx)(e,["Error while login in with GitHub!",e.message]),t.close(),void n(null)}window.setTimeout(i,700)}else n(null)},function(){var e=this,t=arguments;return new Promise((function(n,r){var o=s.apply(e,t);function i(e){$s(o,n,r,i,a,"next",e)}function a(e){$s(o,n,r,i,a,"throw",e)}i(void 0)}))});return function(){return l.apply(this,arguments)}}();return t&&i(),()=>{t&&(t.close(),n(null))}}),[t,n,r,o,e])}function Vs(e,t,n,r,o,i,a){try{var s=e[i](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function Us(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var i=e.apply(t,n);function a(e){Vs(i,r,o,a,s,"next",e)}function s(e){Vs(i,r,o,a,s,"throw",e)}a(void 0)}))}}const Gs={isLoginInProgress:!1,isLoggedIn:!1,isSessionExpired:!1,login:Us((function*(){})),logout:()=>{}},qs=(0,p.createContext)(Gs);function Ks(e,t,n,r,o,i,a){try{var s=e[i](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function zs(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var i=e.apply(t,n);function a(e){Ks(i,r,o,a,s,"next",e)}function s(e){Ks(i,r,o,a,s,"throw",e)}a(void 0)}))}}function Ws(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const Hs=Object.freeze({sha:"<unknown>",date:void 0,author:{login:"unknown author",avatarURL:""},message:"",URL:""});class Ys extends A{getFile(e,t,n,r,o){var i=this;return zs((function*(){return(yield i.postWithRefresh("/vcs.v1.VCSService/GetFile",JSON.stringify({repositoryURL:e,ref:t,localPath:n,rootPath:r,functionName:o}))).json()}))()}getCommits(e){var t=this;return zs((function*(){return yield Promise.all(e.map((({repositoryUrl:e,gitRef:n})=>e&&n?t.getCommit(e,n).catch((t=>(be.v.error(t,{info:`Error while fetching commit from repo "${e}" (${n})!'`}),Hs))):Hs)))}))()}refresh(){var e=this;return zs((function*(){return e.refreshSession()}))()}getCommit(e,t){var n=this;return zs((function*(){var r;const o=yield n.postWithRefresh("/vcs.v1.VCSService/GetCommit",JSON.stringify({repositoryURL:e,ref:t})),i=yield o.json();return(r=i).date&&(r.date=new Date(i.date)),i}))()}postWithRefresh(e,t){var n=this;return zs((function*(){var r;if(n.isRefreshing)return n.queueRequest(e,t);if(null===(r=n.sessionManager.getCookie())||void 0===r?void 0:r.isUserTokenExpired(Ys.BIAS_MS)){n.isRefreshing=!0;try{yield n.refreshSession()}catch(e){n.sessionManager.deleteCookie(),n.flushQueue(e)}n.flushQueue(),n.isRefreshing=!1}return n.post(e,t)}))()}post(e,t){var n=this;return zs((function*(){return n.fetch(e,{method:"POST",body:t})}))()}refreshSession(){var e=this;return zs((function*(){const t=yield e.fetch("/vcs.v1.VCSService/GithubRefresh",{method:"POST",body:JSON.stringify({})}),n=yield t.json();e.sessionManager.setCookie(n.cookie)}))()}queueRequest(e,t){var n=this;return zs((function*(){return new Promise(((r,o)=>{n.pendingQueue.push((i=>{i?o(i):r(n.post(e,t))}))}))}))()}flushQueue(e=void 0){this.pendingQueue.forEach((t=>t(e))),this.pendingQueue=[]}constructor(e){super(e),Ws(this,"sessionManager",void 0),Ws(this,"pendingQueue",void 0),Ws(this,"isRefreshing",void 0),this.sessionManager=ks,this.isRefreshing=!1,this.pendingQueue=[]}}function Zs(e,t,n,r,o,i,a){try{var s=e[i](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function Xs(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var i=e.apply(t,n);function a(e){Zs(i,r,o,a,s,"next",e)}function s(e){Zs(i,r,o,a,s,"throw",e)}a(void 0)}))}}Ws(Ys,"BIAS_MS",3e5);const Js=btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(32)))),Qs="grafana-pyroscope-app.gitHubIntegration.dataSourceUid";function el({dataSourceUid:e,children:t}){const n=qo.build(e,xs),r=qo.build(e,Ys),[o,i]=(0,p.useState)(Gs.isLoginInProgress),[s,l]=function(){const[e,t]=(0,p.useState)(ks.getCookie());return[e,e=>{e?(ks.setCookie(e),t(ks.getCookie())):(ks.deleteCookie(),t(void 0))}]}(),[c,u]=(0,p.useState)();(0,p.useEffect)((()=>{localStorage.getItem(Qs)!==e&&(l(""),localStorage.setItem(Qs,e||""))}),[e]),Ms({vcsClient:n,externalWindow:c,setExternalWindow:u,setSessionCookie:l,nonce:Js});const d=!!c&&!c.closed;d!==o&&i(d);const f=(0,p.useCallback)(Xs((function*(){try{yield function(e,t,n,r,o){return Ls.apply(this,arguments)}(n,r,s,c,u)}catch(e){(0,a.jx)(e,["Failed to login to GitHub",e.message])}})),[n,r,s,c]);return m().createElement(qs.Provider,{value:{isLoginInProgress:o,isLoggedIn:Boolean(s&&!s.isUserTokenExpired()),isSessionExpired:Boolean(null==s?void 0:s.isUserTokenExpired()),login:f,logout:()=>l("")}},t)}var tl=n(9105);function nl(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var rl=function(e){return e.USER="user",e.LABELS="labels",e}({});const ol=(0,p.createContext)(void 0);function il({children:e}){const[t,n]=(0,tl.A)("grafana-pyroscope-app.functionDetailsOverrides",{}),r={saveOverride:(e,t,r)=>{n((n=>(n||(n={}),n[e]||(n[e]={}),n[e][t]=function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter((function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable})))),r.forEach((function(t){nl(e,t,n[t])}))}return e}({},r),n)))},deleteOverride:(e,t)=>{n((n=>n&&n[e]&&n[e][t]?(delete n[e][t],n):n))},deleteAllOverrides:()=>{n({})},getFunctionVersion:(e,n,r)=>{var o;const i=null==t||null===(o=t[e])||void 0===o?void 0:o[n];let a;return i?a="user":r&&(a="labels"),{functionVersion:i||r,functionVersionOrigin:a}}};return m().createElement(ol.Provider,{value:r},e)}function al(e,t,n){const{saveOverride:r,deleteOverride:o,deleteAllOverrides:i,getFunctionVersion:a}=function(){const e=(0,p.useContext)(ol);if(void 0===e)throw new Error("useFunctionVersionContext must be used within a FunctionVersionProvider");return e}(),{functionVersion:s,functionVersionOrigin:l}=a(e,t,n);return{saveOverride:r,deleteOverride:o,deleteAllOverrides:i,functionVersion:s,functionVersionOrigin:l}}class sl extends f.BusEventWithPayload{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(sl,"type","remove-span-selector");function ll({scene:e}){const{component:t}=(0,C.usePluginComponent)("grafana-adaptiveprofiles-app/resolution-boost/v1");if(!t)return;const n=o.jh.interpolate(e,"${serviceName}");return"${serviceName}"===n?void 0:m().createElement(t,{serviceName:n})}var cl=n(9318);function ul(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function dl(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter((function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable})))),r.forEach((function(t){ul(e,t,n[t])}))}return e}function pl({filters:e,maxNodes:t,spanSelector:n}){const r=e?[...e]:[];r.unshift({key:"service_name",operator:"=",value:"$serviceName"});const i=r.map((({key:e,operator:t,value:n})=>`${e}${t}"${n}"`)).join(",");return mn(new o.dt({datasource:kt,queries:[dl({refId:"profile",queryType:"profile",profileTypeId:"$profileMetricId",labelSelector:`{${i},$filters}`,maxNodes:t},n&&{spanSelector:[n]})]}))}var ml=n(9326),fl=(n(8727),n(2249)),hl=n.n(fl),gl=n(585);function bl(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function yl(e,t,n,r){var o,i=arguments.length,a=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}class vl extends gl.Message{constructor(e,t,n,r,o){super(),bl(this,"profile_typeID",void 0),bl(this,"label_selector",void 0),bl(this,"start",void 0),bl(this,"end",void 0),bl(this,"max_nodes",void 0),this.profile_typeID=e,this.label_selector=t,this.start=n,this.end=r,this.max_nodes=o}}function El(e,t,n,r,o,i,a){try{var s=e[i](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function Sl(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var i=e.apply(t,n);function a(e){El(i,r,o,a,s,"next",e)}function s(e){El(i,r,o,a,s,"throw",e)}a(void 0)}))}}yl([gl.Field.d(1,"string")],vl.prototype,"profile_typeID",void 0),yl([gl.Field.d(2,"string")],vl.prototype,"label_selector",void 0),yl([gl.Field.d(3,"int64")],vl.prototype,"start",void 0),yl([gl.Field.d(4,"int64")],vl.prototype,"end",void 0),yl([gl.Field.d(5,"int64")],vl.prototype,"max_nodes",void 0);class wl extends A{static buildPprofRequest(e,t,n){const{profileMetricId:r,labelsSelector:o}=(0,pn.m)(e),i=1e3*t.from.unix(),a=1e3*t.to.unix(),s=new vl(r,o,i,a,n);return vl.encode(s).finish()}selectMergeProfile({query:e,timeRange:t,maxNodes:n}){var r=this;return Sl((function*(){return(yield r.fetch("/querier.v1.QuerierService/SelectMergeProfile",{method:"POST",headers:{"content-type":"application/proto"},body:new Blob([wl.buildPprofRequest(e,t,n)])})).blob()}))()}selectMergeProfileJson({profileMetricId:e,labelsSelector:t,start:n,end:r,stackTrace:o,maxNodes:i}){var a=this;return Sl((function*(){return(yield a.fetch("/querier.v1.QuerierService/SelectMergeProfile",{method:"POST",body:JSON.stringify({profile_typeID:e,label_selector:t,start:1e3*n,end:1e3*r,stackTraceSelector:{call_site:o.map((e=>({name:e})))},maxNodes:i})})).json()}))()}}function Ol(e,t){const{serviceId:n,profileMetricId:r}=(0,pn.m)(e),o=`${t.from.format("YYYY-MM-DD_HHmm")}-to-${t.to.format("YYYY-MM-DD_HHmm")}`;return`${n.replace(/\//g,"-")}_${r}_${o}`}function xl(e,t,n,r,o,i,a){try{var s=e[i](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}class Pl extends T.Q{upload(e,t){var n,r=this;return(n=function*(){const n=yield r.fetch("/upload/v1",{method:"POST",body:JSON.stringify({name:e,profile:btoa(JSON.stringify(t)),fileTypeData:{units:t.metadata.units,spyName:t.metadata.spyName},type:"json"})});return yield n.json()},function(){var e=this,t=arguments;return new Promise((function(r,o){var i=n.apply(e,t);function a(e){xl(i,r,o,a,s,"next",e)}function s(e){xl(i,r,o,a,s,"throw",e)}a(void 0)}))})()}constructor(){super("https://flamegraph.com/api",{"content-type":"application/json"})}}const Cl=new Pl;function Tl(e,t,n,r,o,i,a){try{var s=e[i](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function Al(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var i=e.apply(t,n);function a(e){Tl(i,r,o,a,s,"next",e)}function s(e){Tl(i,r,o,a,s,"throw",e)}a(void 0)}))}}function jl(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class kl extends o.Bs{fetchFlamebearerProfile({dataSourceUid:e,query:t,timeRange:n,maxNodes:r}){return Al((function*(){const o=qo.build(e,ja);let i;try{i=yield o.get({query:t,timeRange:n,format:"json",maxNodes:r||ml.a.maxNodes})}catch(e){return(0,a.jx)(e,["Error while loading flamebearer profile data!",e.message]),null}return i}))()}fetchPprofProfile({dataSourceUid:e,query:t,timeRange:n,maxNodes:r}){return Al((function*(){const o=qo.build(e,wl);let i;try{const e=yield o.selectMergeProfile({query:t,timeRange:n,maxNodes:r||ml.a.maxNodes});i=yield new Response(e.stream().pipeThrough(new CompressionStream("gzip"))).blob()}catch(e){return(0,a.jx)(e,["Failed to export to pprof!",e.message]),null}return i}))()}constructor(){super({key:"export-flame-graph-menu"}),jl(this,"useSceneExportMenu",(({query:e,timeRange:t})=>{const n=o.jh.findByKeyAndType(this,"dataSource",qt).useState().value,[r]=(0,ns.I)(),{settings:i}=(0,Ui._)();var s=this;const l=function(){var o=Al((function*(){(0,d.r)("g_pyroscope_app_export_profile",{format:"json"});const o=yield s.fetchFlamebearerProfile({dataSourceUid:n,query:e,timeRange:t,maxNodes:r});if(!o)return;const i=`${Ol(e,t)}.json`,a=`data:text/json;charset=utf-8,${encodeURIComponent(JSON.stringify(o))}`;hl()(a,i)}));return function(){return o.apply(this,arguments)}}();var c=this;const u=function(){var o=Al((function*(){(0,d.r)("g_pyroscope_app_export_profile",{format:"pprof"});const o=yield c.fetchPprofProfile({dataSourceUid:n,query:e,timeRange:t,maxNodes:r});if(!o)return;const i=`${Ol(e,t)}.pb.gz`;hl()(o,i)}));return function(){return o.apply(this,arguments)}}();var p=this;const m=function(){var o=Al((function*(){(0,d.r)("g_pyroscope_app_export_profile",{format:"flamegraph.com"});const o=yield p.fetchFlamebearerProfile({dataSourceUid:n,query:e,timeRange:t,maxNodes:r});if(o)try{const n=yield Cl.upload(Ol(e,t),o);if(!n.url)throw new Error("Empty URL received.");const r=document.createElement("a");r.target="_blank",r.href=n.url,document.body.appendChild(r),r.click(),document.body.removeChild(r)}catch(e){return void(0,a.jx)(e,["Failed to export to flamegraph.com!",e.message])}}));return function(){return o.apply(this,arguments)}}();return{data:{shouldDisplayFlamegraphDotCom:Boolean(null==i?void 0:i.enableFlameGraphDotComExport)},actions:{downloadPng:()=>{(0,d.r)("g_pyroscope_app_export_profile",{format:"png"});const n=`${Ol(e,t)}.png`;document.querySelector('canvas[data-testid="flameGraph"]').toBlob((e=>{if(e)hl()(e,n);else{const e=new Error("Error while creating the image, no blob.");(0,a.jx)(e,["Failed to export to png!",e.message])}}),"image/png")},downloadJson:l,downloadPprof:u,uploadToFlamegraphDotCom:m}}}))}}function Nl(){return(0,p.useContext)(qs)}function Rl(e){const{login:t,isSessionExpired:n}=Nl(),{settings:r}=(0,Ui._)(),o=null==r?void 0:r.enableFunctionDetails,[i,a]=(0,p.useState)([]),s=(0,p.useCallback)((({item:r},i)=>o&&0!==r.level?[{label:"Function details",icon:"info-circle",onClick:()=>{(0,d.r)("g_pyroscope_app_function_details_clicked"),a(function(e,t){let n=[];const r=t.fields.find((({name:e})=>"label"===e));if(!r)return n;const o=(0,f.getDisplayProcessor)({field:r,theme:(0,f.createTheme)()});let i=e;for(;i&&i.level>0;){var a;for(const e of i.itemIndexes)n.unshift(o(r.values[e]).text);i=null===(a=i.parents)||void 0===a?void 0:a[0]}return n}(r,i)),e.open("function-details"),n&&t()}}]:[]),[o,n,t,e]);return{data:{stacktrace:i},actions:{getExtraFlameGraphMenuItems:s}}}jl(kl,"Component",(({model:e,query:t,timeRange:n})=>{const{actions:r}=e.useSceneExportMenu({query:t,timeRange:n});return m().createElement(i.Dropdown,{overlay:m().createElement(i.Menu,null,m().createElement(i.Menu.Item,{label:"png",onClick:r.downloadPng}),m().createElement(i.Menu.Item,{label:"json",onClick:r.downloadJson}),m().createElement(i.Menu.Item,{label:"pprof",onClick:r.downloadPprof}))},m().createElement(i.Button,{icon:"download-alt",size:"sm",variant:"secondary",fill:"outline","aria-label":"Export profile data",tooltip:"Export profile data"}))}));const Il="gpt-4-1106-preview",_l=({functionDetails:e,lines:t})=>{const n=`\nYou are a code optimization expert. I will give you source code file where each line is annotated with profiling information. The annotation has the following format:\n\n\`\`\`\n(<cost>) <source code line>\n\`\`\`\n\nThe \`\`\`<source code line>\`\`\` is the exact line of source code.\n\nThe \`\`\`<cost>\`\`\` field will contain the resource cost of the given resource cost. This field will also contain the unit of the cost (e.g. seconds, bytes, etc). If \`\`\`<cost>\`\`\` is \`-\` that means there is no profiling data available.\n\nI want you to write back a new improved code for this function and explain why you made changes.\n\nMake sure to take annotations into strong consideration. If a suggested performance improvement isn't backed up by information from the annotations, do not include it. Prioritize lines annotated with a higher cost.\n\nDo not mention the actual numbers from the annotations, users can already see how much time was spent on each line. Do not list various lines and their time spent. When you mention functions or lines, do not mention the time spent on them.\n\nIf you can't find any meaningful performance optimizations, say so. Ask for context if you think other context might help make decisions. If you think the problem is with user input and not the actual code itself, say so.\n\nWhen you output code in markdown, please don't specify language after 3 backticks (e.g instead of saying "\`\`\`go" say "\`\`\`"), and always add a new line after 3 backticks.\n\nFunction name is \`${e.name}\`. Do not mention the function name, users can already see it.\n\nWhen posting a response, follow the outline below:\n* give a brief explanation of things that could be improve\n* print new code if it's possible\n* explain each change in more details\n\n\nAnnotated code is below:\n\`\`\`\n${function(e,t){return t.map((t=>0===t.cum?`(-) ${t.line}`:`(${t.cum} ${e.unit}) ${t.line}`)).join("\n")}(e,t)}\n\`\`\`\n`;return{user:n}};function Dl(e){const{reply:t,error:n}=function(e){const[t,n]=(0,p.useState)(""),[r,o]=(0,p.useState)(!1),[i,a]=(0,p.useState)(!1),[s,l]=(0,p.useState)([]),[c,u]=(0,p.useState)(null),d=(0,p.useCallback)((e=>{l(e),u(null),n(""),o(!0),a(!1),Za.qH({model:Il,messages:e}).pipe(Za.qA()).subscribe({next:n,error(e){u(e),o(!1),a(!0)},complete(){o(!1),a(!0)}})}),[]),m=(0,p.useCallback)((e=>{const n=[{role:"assistant",content:t},{role:"user",content:e}];try{d([...s,...n])}catch(e){u(e)}}),[s,t,d]);return(0,p.useEffect)((()=>{if(s.length>0)return;const t=_l(e);try{d([{role:"system",content:t.user}])}catch(e){u(e)}}),[s.length,e,d]),{reply:{text:t,hasStarted:r,hasFinished:i,messages:s,askFollowupQuestion:m},error:c}}(e);return{data:{isLoading:!n&&!t.text.trim(),llmError:n,reply:t,shouldDisplayReply:Boolean((null==t?void 0:t.hasStarted)||(null==t?void 0:t.hasFinished)),shouldDisplayFollowUpForm:!n&&Boolean(null==t?void 0:t.hasFinished)},actions:{submitFollowupQuestion(e){t.askFollowupQuestion(e)}}}}const Ll=()=>({title:r.css`
margin: -4px 0 4px 0;
`,content:r.css``});function Fl({suggestionPromptInputs:e}){const t=(0,i.useStyles2)(Ll),{data:n,actions:r}=Dl(e);return m().createElement(m().Fragment,null,m().createElement("h6",{className:t.title},"Code Optimization Suggestions"),m().createElement("div",{className:t.content},n.isLoading&&m().createElement(m().Fragment,null,m().createElement(i.Spinner,{inline:!0})," Analyzing..."),n.fetchError&&m().createElement(Gi._,{severity:"error",title:"Error while fetching profiles!",message:"Sorry for any inconvenience, please try again later."}),n.llmError&&m().createElement(Gi._,{severity:"error",title:"Failed to generate content using OpenAI!",error:n.llmError,message:"Sorry for any inconvenience, please try again later or if the problem persists, contact your organization admin."}),n.shouldDisplayReply&&m().createElement(za,{reply:n.reply}),n.shouldDisplayFollowUpForm&&m().createElement(Ya,{onSubmit:r.submitFollowupQuestion})))}const Bl=5;function $l(e,t){let n=e;const r=e.match(/raw\.githubusercontent\.com\/([^/]+)\/([^/]+)\/(.+)/);if(r){const[,e,t,o]=r;n=`https://github.com/${e}/${t}/blob/${o}`}return void 0===t||e.includes("#")||(n+=`#L${t}`),n}function Ml(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Vl(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter((function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable})))),r.forEach((function(t){Ml(e,t,n[t])}))}return e}function Ul(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))})),e}function Gl(e,t){const{isLoggedIn:n}=Nl(),{version:r}=t,[o,i]=(0,p.useState)(!1);var a,s,l,c;const{fileInfo:u,error:d,isFetching:m}=function({enabled:e,dataSourceUid:t,repository:n,gitRef:r,localPath:o,rootPath:i,functionName:a}){const s=qo.build(t,Ys),{isFetching:l,error:c,data:u}=(0,Ta.I)({enabled:Boolean(e&&n&&(o||a)),queryKey:["vcs-file",n,r,o,i,a],queryFn:()=>s.getFile(n,r,o,i,a).then((e=>({content:e.content,URL:e.URL}))).then((e=>({URL:e.URL,content:atob(e.content)})))});return{isFetching:l,error:s.isAbortError(c)?null:c,fileInfo:u}}({enabled:n,dataSourceUid:e,localPath:t.fileName,repository:null!==(a=null==r?void 0:r.repository)&&void 0!==a?a:"",gitRef:null!==(s=null==r?void 0:r.git_ref)&&void 0!==s?s:"",rootPath:null!==(l=null==r?void 0:r.root_path)&&void 0!==l?l:"",functionName:null!==(c=t.name)&&void 0!==c?c:""}),{snippetLines:f,allLines:h}=(0,p.useMemo)((()=>(null==u?void 0:u.content)?function(e,t){const n=Array.from(t.values()).sort(((e,t)=>e.line-t.line)),r=e.split("\n"),o=r.map(((e,n)=>{const r=n+1,o=t.get(r);var i,a;return{line:e,number:r,cum:null!==(i=null==o?void 0:o.cum)&&void 0!==i?i:0,flat:null!==(a=null==o?void 0:o.flat)&&void 0!==a?a:0}}));if(0===t.size)return{snippetLines:[],allLines:o};const i=Math.max(0,n[0].line-Bl-1),a=Math.min(r.length,n[n.length-1].line+Bl);return{snippetLines:o.slice(i,a),allLines:o}}(u.content,t.callSites):function(e){if(!e.size)return{snippetLines:[],allLines:[]};const t=Array.from(e.values()).sort(((e,t)=>e.line-t.line)),n=Math.max(0,t[0].line-Bl-1),r=t[t.length-1].line+Bl+1,o=[];for(let t=n+1;t<r;t++){const n=e.get(t);var i,a;o.push({line:void 0,number:t,cum:null!==(i=null==n?void 0:n.cum)&&void 0!==i?i:0,flat:null!==(a=null==n?void 0:n.flat)&&void 0!==a?a:0})}return{snippetLines:o,allLines:[]}}(t.callSites)),[null==u?void 0:u.content,t.callSites]);return{data:{fetchError:d,openAiSuggestions:o,isLoadingCode:m,unit:t.unit,githubUrl:(null==u?void 0:u.URL)?$l(u.URL,t.startLine):void 0,snippetLines:f.map((e=>{var t;return Ul(Vl({},e),{line:null!==(t=e.line)&&void 0!==t?t:"???"})})),allLines:h.map((e=>{var t;return Ul(Vl({},e),{line:null!==(t=e.line)&&void 0!==t?t:"???"})})),noCodeAvailable:Boolean(d)||!h.some((e=>e.line))},actions:{setOpenAiSuggestions:i}}}function ql(e){switch(e){case"nanoseconds":return(0,f.getValueFormat)("ns");case"microseconds":return(0,f.getValueFormat)("µs");case"milliseconds":return(0,f.getValueFormat)("ms");case"seconds":return(0,f.getValueFormat)("s");case"count":return(0,f.getValueFormat)("short");default:return(0,f.getValueFormat)(e)}}const Kl=({lines:e,unit:t,githubUrl:n,isLoadingCode:o,noCodeAvailable:a,onOptimizeCodeClick:s})=>{const l=(0,i.useStyles2)(Zl),c=ql(t),u=e=>{if(e<=0)return".";const t=c(e);return t.suffix?t.text+t.suffix:t.text};Wl(e);const[d,p]=e.reduce((([e,t],{flat:n,cum:r})=>[e+n,t+r]),[0,0]);return m().createElement("div",{"data-testid":"function-details-code-container"},m().createElement("div",{className:l.container},m().createElement("div",{className:l.header},m().createElement("div",{className:l.breakdownLabel},m().createElement("h6",null,"Breakdown per line"),m().createElement("span",null,o&&m().createElement(i.Spinner,{inline:!0}),!o&&a&&"(file information unavailable)")),m().createElement("div",{className:l.buttons},m().createElement(i.LinkButton,{disabled:Boolean(o||!n),href:n,target:"_blank",icon:"github",fill:"text"},"View on GitHub"),m().createElement(Va,{onClick:s,disabled:o||a,interactionName:"g_pyroscope_app_optimize_code_clicked"},"Optimize Code")))),m().createElement("pre",{className:l.codeBlock,"data-testid":"function-details-code"},m().createElement("div",{className:(0,r.cx)(l.highlighted,l.codeBlockHeader)},zl("Total:",u(d),u(p)," (self, total)")),e.map((({line:e,number:t,cum:n,flat:r})=>m().createElement("div",{key:e+t+n+r,className:r+n>0?l.highlighted:""},zl(`${t} `,u(r),u(n),e))))))},zl=(e,t,n,r)=>{const o=e.padStart(7," ")+t.padStart(12," ")+n.padStart(12," ");return r?`${o} ${r}`:o},Wl=e=>{if(0===e.length)return;let t=Hl(e[0].line);for(let n=1;n<e.length;n++){const{line:r}=e[n];if(""===r.trim())continue;const o=Hl(r);t=Yl(t,o)}if(t)for(let n=0;n<e.length;n++)e[n].line=e[n].line.substring(t.length)},Hl=e=>{const t=e.match(/^[ \t]*/);var n;return null!==(n=null==t?void 0:t[0])&&void 0!==n?n:""},Yl=(e,t)=>{let n=0;for(let r=0;r<Math.min(e.length,t.length)&&e[r]===t[r];r++)n++;return e.substring(0,n)},Zl=e=>({container:r.css`
display: flex;
flex-direction: row;
align-items: flex-start;
width: 100%;
`,header:r.css`
display: flex;
justify-content: space-between;
align-items: end;
width: 100%;
`,breakdownLabel:r.css`
& > h6 {
display: inline-block;
margin-top: ${e.spacing(1)};
}
& > span {
margin-left: ${e.spacing(1)};
font-size: ${e.typography.bodySmall.fontSize};
}
& > svg {
margin-left: ${e.spacing(1)};
}
`,buttons:r.css`
display: flex;
flex-wrap: no-wrap;
`,codeBlock:r.css`
position: relative;
min-height: 240px;
font-size: 12px;
overflow-x: auto;
white-space: pre;
color: ${e.colors.text.secondary};
`,highlighted:r.css`
color: ${e.colors.text.maxContrast};
`,codeBlockHeader:r.css`
margin-bottom: 8px;
`});function Xl({dataSourceUid:e,functionDetails:t}){var n,r;const{data:o,actions:i}=Gl(e,t);return o.fetchError&&404!==(null===(r=o.fetchError)||void 0===r||null===(n=r.response)||void 0===n?void 0:n.status)&&(0,a.jx)(o.fetchError,["Failed to fetch file information!",o.fetchError.message]),m().createElement(m().Fragment,null,m().createElement(Kl,{lines:o.snippetLines,unit:o.unit,githubUrl:o.githubUrl,isLoadingCode:o.isLoadingCode,noCodeAvailable:o.noCodeAvailable,onOptimizeCodeClick:()=>{var e;i.setOpenAiSuggestions(!0),null===(e=document.getElementById("ai-suggestions-panel"))||void 0===e||e.scrollIntoView({behavior:"smooth"})}}),m().createElement("h6",{id:"ai-suggestions-panel",style:{height:0,marginBottom:0}}),o.openAiSuggestions?m().createElement(Fl,{suggestionPromptInputs:{functionDetails:t,lines:o.allLines}}):null)}const Jl=e=>({ellipsis:r.css`
color: ${e.colors.primary.text};
text-overflow: ellipsis;
overflow: hidden;
direction: rtl;
white-space: nowrap;
`}),Ql=({enableIntegration:e,repository:t})=>{const n=(0,i.useStyles2)(Jl),{isLoginInProgress:r,isLoggedIn:o,login:a,logout:s}=Nl();return e?r?m().createElement(m().Fragment,null,m().createElement(i.Spinner,null),m().createElement("span",null,"Connecting to GitHub...")):o?m().createElement(m().Fragment,null,m().createElement(i.Icon,{name:"github",size:"lg"}),m().createElement("a",{className:n.ellipsis,href:t.commitUrl,target:"_blank",rel:"noreferrer",title:"View commit"},m().createElement(i.Icon,{name:"external-link-alt"})," ",t.commitName),m().createElement(i.IconButton,{name:"signout",onClick:()=>s(),"aria-label":"Disconnect from GitHub",title:"Disconnect from GitHub"})):m().createElement(i.Button,{icon:"github",variant:"primary",onClick:a,tooltip:"Once connected, the GitHub code will be accessible only from this browser session.",tooltipPlacement:"top"},"Connect to ",t.name):m().createElement(m().Fragment,null,"-")};function ec(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function tc(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))})),e}function nc(e,t){const n=e.map((e=>{var n;return tc(function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter((function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable})))),r.forEach((function(t){ec(e,t,n[t])}))}return e}({},e.commit),{samples:{unit:null!==(n=e.unit)&&void 0!==n?n:"count",current:Array.from(e.callSites.values()).reduce(((e,{cum:t})=>e+t),0),total:t}})}));return n}const rc="https://github.com/";function oc(e,t){if(!(null==t?void 0:t.repository))return null;const n=t.repository,r=n.replace(rc,""),o=t.git_ref;return{isGitHub:e,url:n,name:r,commitUrl:o?`${n}/commit/${o}`:n,commitName:o?`${r}@${o.substring(0,7)}`:r}}const ic=(e,t,n)=>{let r;try{r=n?JSON.parse(e.stringTable[Number(n.buildId)]):void 0}catch(e){}return{name:e.stringTable[Number(t.name)],version:r,startLine:Number.isNaN(Number(t.startLine))?void 0:Number(t.startLine),fileName:e.stringTable[Number(t.filename)],callSites:new Map,unit:e.stringTable[Number(e.sampleType[0].unit)],commit:Hs}};function ac(e,t,n,r,o,i,a){const s=new Set;i.locationId.forEach(((l,c)=>{var u;const d=n.get(l);null==d||null===(u=d.line)||void 0===u||u.forEach((n=>{const u=r.get(n.functionId);if(!u)return;if(t.stringTable[Number(u.name)]!==e)return;if(s.has(l))return;s.add(l);const p=a.get(d.mappingId)||ic(t,u,o.get(d.mappingId));a.set(d.mappingId,function(e,t,n,r){const o=Number(t.line),i=e.callSites.get(o)||{line:Number(t.line),flat:0,cum:0},a=0===r?n:0,s=n;return i.flat+=a,i.cum+=s,e.callSites.set(o,i),e}(p,n,Number(i.value[0]),c))}))}))}function sc(e,t,n,r,o,i,a){try{var s=e[i](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function lc(){var e;return e=function*(e,t,n){const r=qo.build(e,Ys),o=t.map((e=>{var t,r,o;return{repositoryUrl:(null==e||null===(t=e.version)||void 0===t?void 0:t.repository)||n.repository,gitRef:(null==e||null===(r=e.version)||void 0===r?void 0:r.git_ref)||n.git_ref,rootPath:(null==e||null===(o=e.version)||void 0===o?void 0:o.root_path)||n.root_path}}));return(yield r.getCommits(o)).forEach(((e,n)=>{t[n].commit=e})),t},lc=function(){var t=this,n=arguments;return new Promise((function(r,o){var i=e.apply(t,n);function a(e){sc(i,r,o,a,s,"next",e)}function s(e){sc(i,r,o,a,s,"throw",e)}a(void 0)}))},lc.apply(this,arguments)}const cc=e=>Array.from(e.callSites.values()).reduce(((e,{cum:t})=>e+t),0),uc=(e,t)=>cc(t)-cc(e);function dc(e,t,n,r,o,i,a){try{var s=e[i](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function pc(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var i=e.apply(t,n);function a(e){dc(i,r,o,a,s,"next",e)}function s(e){dc(i,r,o,a,s,"throw",e)}a(void 0)}))}}const mc={repository:"",git_ref:"HEAD",root_path:""};function fc({dataSourceUid:e,query:t,timeRange:n,stackTrace:r}){const{profileMetricId:o,labelsSelector:i,serviceId:a}=(0,pn.m)(t),[s,l]=[n.from.unix(),n.to.unix()],{isLoggedIn:c}=Nl(),u=qo.build(e,wl),{functionVersion:d}=al(e,a,mc),{isFetching:m,error:f,data:h}=(0,Ta.I)({enabled:Boolean(o&&i&&r.length>0&&s>0&&l>0),queryKey:["function-details",o,i,s,l,r,c,d],queryFn:pc((function*(){const t=yield u.selectMergeProfileJson({profileMetricId:o,labelsSelector:i,start:s,end:l,stackTrace:r,maxNodes:500}),n=function(e,t){var n,r,o,i;const a=new Map,s=new Map(null===(n=t.location)||void 0===n?void 0:n.map((e=>[e.id,e]))),l=new Map(null===(r=t.function)||void 0===r?void 0:r.map((e=>[e.id,e]))),c=new Map(null===(o=t.mapping)||void 0===o?void 0:o.map((e=>[e.id,e])));return null===(i=t.sample)||void 0===i||i.filter((e=>void 0!==e.locationId)).forEach((n=>ac(e,t,s,l,c,n,a))),Array.from(a.values())}(r[r.length-1],t).sort(uc);return c?function(e,t,n){return lc.apply(this,arguments)}(e,n,d||mc):n}))}),g=(0,p.useMemo)((()=>(null==h?void 0:h.length)?h:[{name:r.at(-1),startLine:void 0,fileName:"",callSites:new Map,unit:"",commit:Hs}]),[h,r]);return{isFetching:m,error:u.isAbortError(f)?null:f,functionsDetails:g}}const hc=[60,3600,86400,604800,2592e3,31536e3,1/0],gc=["second","minute","hour","day","week","month","year"],bc=new Intl.RelativeTimeFormat("en-US",{numeric:"auto"});const yc=new Intl.DateTimeFormat("en-US",{year:"numeric",month:"long",day:"2-digit"});function vc(e){return e?`${yc.format(e)} (${function(e){const t=e.getTime(),n=Math.round((t-Date.now())/1e3),r=hc.findIndex((e=>e>Math.abs(n))),o=r?hc[r-1]:1;return bc.format(Math.floor(n/o),gc[r])}(e)})`:"?"}const Ec=e=>({container:r.css`
display: flex;
flex-direction: column;
justify-content: flex-start;
`,firstLine:r.css`
display: flex;
flex-direction: row;
align-items: center;
gap: 1em;
`,sha:r.css`
font-family: monospace;
`,sample:r.css`
font-size: 12px;
`,secondLine:r.css`
display: flex;
flex-direction: row;
align-items: center;
font-size: 12px;
color: ${e.colors.text.secondary};
`,avatar:r.css`
display: inline-block;
margin-right: 4px;
border-radius: 50%;
background: grey;
width: 16px;
height: 16px;
`,message:r.css`
font-size: 12px;
color: ${e.colors.text.secondary};
`});function Sc({commit:e}){const t=(0,i.useStyles2)(Ec),{author:n,samples:r}=e,o=n.login,a=n.avatarURL,s=ql(r.unit)(r.current),l=Math.round(r.current/r.total*100);return m().createElement("div",{className:t.container},m().createElement("div",{className:t.firstLine},m().createElement("span",{className:t.sha},Cc(e.sha)),m().createElement("span",{className:t.sample},s.text,s.suffix," (",l,"%)")),m().createElement("div",{className:t.secondLine},a&&m().createElement("img",{className:t.avatar,src:a,alt:o}),m().createElement("span",null,o," on ",vc(e.date))),m().createElement("span",{className:t.message},Tc(e.message)))}const wc=e=>({container:r.css`
display: flex;
flex-direction: row;
justify-content: flex-start;
align-items: center;
gap: 1em;
`,sha:r.css`
font-family: monospace;
`,message:r.css`
color: ${e.colors.text.secondary};
`});function Oc({commit:e}){const t=(0,i.useStyles2)(wc);return m().createElement("div",{className:t.container},m().createElement("span",{className:t.sha},Cc(e.sha)),m().createElement("div",{className:t.message},m().createElement("span",null,Tc(e.message))))}function xc({commits:e,selectedCommit:t,onChange:n}){return m().createElement(i.Select,{options:e.map((e=>({label:e.sha,value:e}))),value:{label:t.sha,value:t},hideSelectedOptions:!0,isSearchable:!1,noOptionsMessage:"No commits found",formatOptionLabel:Pc,onChange:e=>{e.value&&n(e.value)}})}function Pc(e,t){var n;const{value:r}=e;if(!r)return null;return(null===(n=t.selectValue[0])||void 0===n?void 0:n.value)===r?m().createElement(Oc,{commit:r}):m().createElement(Sc,{commit:r})}const Cc=e=>e===Hs.sha?e:e.substring(0,7),Tc=e=>e.split("\n")[0],Ac=({onDismiss:e})=>m().createElement(i.Alert,{severity:"info",title:"Integrate with Github",buttonContent:"Dismiss",onRemove:e},m().createElement("p",null,"This language supports integration with ",m().createElement(i.Icon,{name:"github"})," GitHub."),m().createElement("p",null,"To activate this feature, you will need to add two new labels when sending profiles"," ",m().createElement("code",null,"service_repository")," and ",m().createElement("code",null,"service_git_ref"),"."," "),m().createElement("p",null,"They should respectively be set to the full repository GitHub URL and the current"," ",m().createElement(i.TextLink,{href:"https://docs.github.com/en/rest/git/refs?apiVersion=2022-11-28#about-git-references",external:!0},"git ref")," ","of the running service."),m().createElement(i.Icon,{name:"document-info"})," ",m().createElement(i.TextLink,{href:"https://grafana.com/docs/grafana-cloud/monitor-applications/profiles/pyroscope-github-integration/",external:!0},"Learn more"));function jc({isLoading:e,children:t}){return e?m().createElement(i.Spinner,{inline:!0}):m().createElement(m().Fragment,null,t)}const kc=(0,p.memo)(jc);function Nc(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Rc(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter((function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable})))),r.forEach((function(t){Nc(e,t,n[t])}))}return e}function Ic(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))})),e}const _c=e=>{var t,n,r,o;const{serviceName:a,version:s,datasourceUid:l,saveOverrides:c,functionVersionOrigin:u}=e,[d,p]=m().useState(!1),{register:f,handleSubmit:h,formState:{errors:g},reset:b}=(0,ei.mN)({mode:"onChange"});return m().createElement(m().Fragment,null,m().createElement(i.Button,{"aria-label":"override repository settings",variant:"secondary",fill:"text",size:"sm",icon:"pen",onClick:()=>{p(!0),b(s)}},u===rl.USER?m().createElement(i.Text,{element:"span",color:"secondary"},"(user set)"):""),d&&m().createElement(i.Modal,{title:u===rl.USER?"Edit repository details override":"Add new repository details override",isOpen:d,onDismiss:()=>p(!1)},m().createElement("form",{onSubmit:h((e=>{c(l,a,{repository:e.repository,git_ref:e.git_ref||"HEAD",root_path:e.root_path||""}),p(!1)}))},m().createElement(i.Alert,{severity:"info",title:"Github Integration labels"},m().createElement("p",null,"To activate GitHub Integration feature, you will need to add two new labels when sending profiles:",m().createElement("code",null,"service_repository")," and ",m().createElement("code",null,"service_git_ref"),"."),m().createElement("p",null,"For debugging purposes, you can manually provide repository details using this form. The custom value is saved in your browser local storage for given data source and service name.")),m().createElement(i.Field,{label:"Data source"},m().createElement(C.DataSourcePicker,{current:l,disabled:!0})),m().createElement(i.Field,{label:"Service name"},m().createElement(i.Input,{disabled:!0,value:a})),m().createElement(i.Field,{label:"service_repository (repository URL) - required",invalid:!!g.repository,error:null==g||null===(n=g.repository)||void 0===n||null===(t=n.message)||void 0===t?void 0:t.toString()},m().createElement(i.Input,Ic(Rc({},f("repository",{required:"Repository name is required"})),{placeholder:"Enter GitHub repo name, https://github.com/org/repo"}))),m().createElement(i.Field,{label:"service_git_ref (commit reference)",invalid:!!g.git_ref,error:null==g||null===(o=g.git_ref)||void 0===o||null===(r=o.message)||void 0===r?void 0:r.toString()},m().createElement(i.Input,Ic(Rc({},f("git_ref")),{placeholder:"HEAD"}))),m().createElement(i.Field,{label:"Path to root"},m().createElement(i.Input,Ic(Rc({},f("root_path")),{placeholder:"Enter root path"}))),m().createElement(i.Stack,{direction:"row"},m().createElement(i.Button,{type:"submit"},u===rl.USER?"Edit":"Add"),u===rl.USER&&m().createElement(i.Button,{type:"button",variant:"destructive",onClick:()=>{e.deleteOverride(l,a),b(),p(!1)}},"Delete override"),m().createElement(i.ConfirmButton,{confirmVariant:"destructive",confirmText:"Remove all",onConfirm:()=>{e.deleteAllOverrides(),b(),p(!1)}},"Remove all overrides")))))};function Dc(e,t,n,r,o,i,a){try{var s=e[i](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function Lc(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Fc(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter((function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable})))),r.forEach((function(t){Lc(e,t,n[t])}))}return e}function Bc(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))})),e}class $c extends o.Bs{constructor(){super({key:"function-details-panel"}),Lc(this,"useSceneFunctionDetailsPanel",((e,t)=>{const n=o.jh.findByKeyAndType(this,"dataSource",qt).useState().value,r=o.jh.findByKeyAndType(this,"dataSource",qt).useState().text,i=rn(this,"serviceName"),s=Gt(this,"filters"),{functionsDetails:l,error:c,isFetching:u}=fc({dataSourceUid:n,query:s,timeRange:t,stackTrace:e}),{saveOverride:d,deleteOverride:m,functionVersion:f,deleteAllOverrides:h,functionVersionOrigin:g}=al(n,i,l[0].version),[b,y]=(0,p.useState)(),[v,E]=(0,p.useState)(l[0]),[S,w]=(0,p.useState)(Bt.x.has(Bt.x.KEYS.GITHUB_INTEGRATION));l&&b!==l&&(y(l),v!==l[0]&&E(l[0]));const O=((null==f?void 0:f.repository)||"").startsWith(rc);const x=function(e){const t=Boolean((null==e?void 0:e.name)||(null==e?void 0:e.fileName)),n=Boolean((null==e?void 0:e.callSites)&&Array.from(e.callSites.values()).some((e=>e.line>0)));return t&&n}(v),P=!S&&!O&&x,C=(0,p.useMemo)((()=>l.map((e=>Array.from(e.callSites.values()).reduce(((e,{cum:t})=>e+t),0))).reduce(((e,t)=>e+t),0)),[l]),T=nc(l,C),A=T.find((({sha:e})=>{var t;return e===(null==v||null===(t=v.commit)||void 0===t?void 0:t.sha)}));return{data:{serviceName:i,dataSourceName:r,isLoading:u,fetchFunctionDetailsError:c,functionDetails:Bc(Fc({},v),{version:Fc({},null==v?void 0:v.version,f)}),functionVersionOrigin:g,repository:oc(O,f),commits:T,selectedCommit:A,isGitHubSupported:x,shouldDisplayGitHubBanner:P,dataSourceUid:n},actions:{deleteFunctionOverride(e,t){m(e,t)},deleteFunctionAllOverrides(){h()},saveFunctionDetails(e,t,n){d(e,t,n)},selectCommit(e){const t=l.find((({commit:t})=>t.sha===e.sha));E(t)},copyFilePathToClipboard(){return(e=function*(){try{(null==v?void 0:v.fileName)&&(yield navigator.clipboard.writeText(v.fileName),(0,a.qq)(["File path copied to clipboard!"]))}catch(e){}},function(){var t=this,n=arguments;return new Promise((function(r,o){var i=e.apply(t,n);function a(e){Dc(i,r,o,a,s,"next",e)}function s(e){Dc(i,r,o,a,s,"throw",e)}a(void 0)}))})();var e},dismissGitHubBanner(){Bt.x.set(Bt.x.KEYS.GITHUB_INTEGRATION,{}),w(!0)}}}}))}}Lc($c,"LABEL_WIDTH",16),Lc($c,"Component",(({model:e,timeRange:t,stackTrace:n,onClose:r})=>{const o=(0,i.useStyles2)(Mc),{data:a,actions:s}=e.useSceneFunctionDetailsPanel(n,t);return m().createElement(pa,{className:o.sidePanel,title:"Function Details",isLoading:!1,headerActions:m().createElement(i.IconButton,{name:"times-circle",variant:"secondary","aria-label":"close",onClick:r}),dataTestId:"function-details-panel"},m().createElement("div",{className:o.content},a.fetchFunctionDetailsError&&m().createElement(Gi._,{severity:"error",title:"Error while fetching function details!",error:a.fetchFunctionDetailsError}),m().createElement("div",{className:o.container},m().createElement("div",{className:o.row,"data-testid":"row-function-name"},m().createElement(i.InlineLabel,{width:$c.LABEL_WIDTH},"Function name"),m().createElement(i.Tooltip,{content:a.functionDetails.name,placement:"top"},m().createElement("span",{className:o.textValue},a.functionDetails.name))),m().createElement("div",{className:o.row,"data-testid":"row-start-line"},m().createElement(i.InlineLabel,{tooltip:"The line where this function definition starts",width:$c.LABEL_WIDTH},"Start line"),m().createElement("span",{className:o.textValue},m().createElement(kc,{isLoading:a.isLoading},void 0!==a.functionDetails.startLine?a.functionDetails.startLine:"-"))),m().createElement("div",{className:o.row,"data-testid":"row-file-path"},m().createElement(i.InlineLabel,{tooltip:"File path where that function is defined",width:$c.LABEL_WIDTH},"File"),m().createElement(kc,{isLoading:a.isLoading},a.functionDetails.fileName?m().createElement(m().Fragment,null,m().createElement(i.Tooltip,{content:a.functionDetails.fileName,placement:"top"},m().createElement("span",{className:o.textValue},"","/"===(null==(l=a.functionDetails.fileName)?void 0:l[0])?l.substring(1)+"/":l)),m().createElement(i.IconButton,{name:"clipboard-alt",tooltip:"Copy to clipboard",onClick:s.copyFilePathToClipboard})):"-")),a.shouldDisplayGitHubBanner&&m().createElement("div",{className:o.row,"data-testid":"row-github-banner"},m().createElement(Ac,{onDismiss:s.dismissGitHubBanner})),m().createElement("div",{className:o.row,"data-testid":"row-repository"},m().createElement(i.InlineLabel,{tooltip:"The repository configured for the selected service",width:$c.LABEL_WIDTH},"Repository"),m().createElement(kc,{isLoading:a.isLoading},a.repository?a.repository.isGitHub?m().createElement(Ql,{enableIntegration:a.isGitHubSupported,repository:a.repository}):m().createElement(i.TextLink,{href:a.repository.url,external:!0},a.repository.url):"-"),!a.isLoading&&m().createElement(_c,{serviceName:a.serviceName,datasourceName:a.dataSourceName,datasourceUid:a.dataSourceUid,version:a.functionDetails.version,functionVersionOrigin:a.functionVersionOrigin,saveOverrides:s.saveFunctionDetails,deleteAllOverrides:s.deleteFunctionAllOverrides,deleteOverride:s.deleteFunctionOverride})),m().createElement("div",{className:o.row,"data-testid":"row-commit"},m().createElement(i.InlineLabel,{width:$c.LABEL_WIDTH,tooltip:"The version of the application (commit) where the function is defined. Use the dropdown menu to target a specific commit."},"Commit"),m().createElement(kc,{isLoading:a.isLoading},m().createElement(xc,{commits:a.commits,selectedCommit:a.selectedCommit,onChange:s.selectCommit})))),m().createElement(Xl,{dataSourceUid:a.dataSourceUid,functionDetails:a.functionDetails})));var l}));const Mc=e=>({sidePanel:r.css`
flex: 1 0 50%;
margin-left: 8px;
max-width: calc(50% - 4px);
`,title:r.css`
margin: -4px 0 4px 0;
`,content:r.css`
padding: ${e.spacing(1)};
`,container:r.css`
width: 100%;
display: flex;
flex-direction: column;
align-items: flex-start;
`,row:r.css`
width: 100%;
display: flex;
flex-direction: row;
align-items: center;
padding-bottom: 10px;
> * {
margin-right: 10px !important;
}
`,textValue:r.css`
// hack to have the ellipsis appear at the start of the string
direction: rtl;
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
`});function Vc(e){const{spanSelector:t,removeSpanSelector:n}=e,r=(0,i.useStyles2)(Uc);return m().createElement("div",{className:r.container},m().createElement(i.Tooltip,{content:`You have added a span selector to the flamegraph query (${t}).`,placement:"top"},m().createElement("span",null,"Span selector added")),m().createElement(i.Button,{size:"md",fill:"text",variant:"secondary",icon:"times",tooltip:"Remove span selector from query",tooltipPlacement:"top",onClick:()=>{n()}}))}const Uc=()=>({container:r.css`
padding: 0 4px;
`});function Gc(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class qc extends o.Bs{onActivate(){let e;const t=this.subscribeToState(((t,n)=>{var r;t.$data!==n.$data&&(e&&e.unsubscribe(),e=null===(r=t.$data)||void 0===r?void 0:r.subscribeToState((e=>{var t;(null===(t=e.data)||void 0===t?void 0:t.state)===f.LoadingState.Done&&this.setState({lastTimeRange:e.data.timeRange})})))}));return()=>{t.unsubscribe(),null==e||e.unsubscribe()}}buildTitle(){const e=rn(this,"serviceName"),t=rn(this,"profileMetricId"),n=(0,At.y)(t).type;return m().createElement(m().Fragment,null,m().createElement(ma.S,{size:"small"}),"Flame graph for ",e," (",n,")")}removeSpanSelector(){this.publishEvent(new sl({}),!0)}constructor(){super({key:"flame-graph",$data:new o.dt({datasource:kt,queries:[]}),lastTimeRange:void 0,exportMenu:new kl,aiPanel:new Ja,functionDetailsPanel:new $c,createRecordingRuleModal:new ui}),Gc(this,"useSceneFlameGraph",(e=>{var t,n,r,o,s;const{isLight:l}=(0,i.useTheme2)(),c=(0,p.useMemo)((()=>()=>(0,f.createTheme)({colors:{mode:l?"light":"dark"}})),[l]),[u]=(0,ns.I)(),{settings:d,error:m}=(0,Ui._)(),{$data:h,lastTimeRange:g,exportMenu:b,aiPanel:y,functionDetailsPanel:v,createRecordingRuleModal:E}=this.useState();m&&(0,a.HA)(["Error while retrieving the plugin settings!","Some features might not work as expected (e.g. collapsed flame graphs). Please try to reload the page, sorry for the inconvenience."]),(0,p.useEffect)((()=>{u&&this.setState({$data:pl({maxNodes:u,spanSelector:e})})}),[u,e]);const S=h.useState(),w=null==S||null===(t=S.data)||void 0===t?void 0:t.state,O=w===f.LoadingState.Error?(null==S||null===(r=S.data)||void 0===r||null===(n=r.errors)||void 0===n?void 0:n[0])||new Error("Unknown error!"):null,x=w===f.LoadingState.Loading,P=null==S||null===(s=S.data)||void 0===s||null===(o=s.series)||void 0===o?void 0:o[0],C=Number(null==P?void 0:P.length)>1,T=Gt(this,"filters");return{data:{title:this.buildTitle(),isLoading:x,isFetchingProfileData:x,hasProfileData:C,profileData:P,spanSelector:e,fetchProfileError:O,settings:d,export:{menu:b,query:T,timeRange:g},ai:{panel:y,fetchParams:[{query:T,timeRange:g}]},gitHub:{panel:v,timeRange:g},recordingRules:{modal:E}},actions:{getTheme:c}}})),this.addActivationHandler(this.onActivate.bind(this))}}Gc(qc,"Component",(({model:e})=>{var t;const n=(0,i.useStyles2)(Kc),r=rn(e,"spanSelector"),{data:o,actions:a}=e.useSceneFlameGraph(r),s=Vi(),l=Rl(s),{settings:c}=(0,Ui._)(),[u,d]=(0,p.useState)({isOpen:!1}),f=(h=e=>{d({isOpen:!0,functionName:e})},{data:{},actions:{getExtraFlameGraphMenuItems:(0,p.useCallback)((({item:e,label:t})=>[{label:"Create recording rule",icon:"download-alt",onClick:()=>h("total"===t&&0===e.level?void 0:t)}]),[h])}});var h;const{hideAIButton:g}=ha(),b=o.isLoading||!o.hasProfileData;(0,p.useEffect)((()=>{b&&s.close()}),[b,s]);const y=(0,p.useMemo)((()=>m().createElement(m().Fragment,null,o.title,o.isLoading&&m().createElement(i.Spinner,{inline:!0,className:n.spinner}))),[o.isLoading,o.title,n.spinner]);return m().createElement("div",{className:n.flex},m().createElement(pa,{dataTestId:"flame-graph-panel",className:n.flamegraphPanel,title:y,isLoading:o.isLoading,headerActions:m().createElement(m().Fragment,null,r&&m().createElement(Vc,{spanSelector:r,removeSpanSelector:()=>e.removeSpanSelector()}),!g&&m().createElement(Va,{disabled:b||s.isOpen("ai"),onClick:()=>s.open("ai"),interactionName:"g_pyroscope_app_explain_flamegraph_clicked"},"Explain Flame Graph"))},o.fetchProfileError&&m().createElement(Gi._,{severity:"error",title:"Error while loading profile data!",error:o.fetchProfileError}),!o.fetchProfileError&&m().createElement(cl.Ay,{data:o.profileData,disableCollapsing:!(null===(t=o.settings)||void 0===t?void 0:t.collapsedFlamegraphs),getTheme:a.getTheme,getExtraContextMenuButtons:(e,t)=>[...l.actions.getExtraFlameGraphMenuItems(e,t),...(null==c?void 0:c.enableMetricsFromProfiles)&&On.g.metricsFromProfiles?f.actions.getExtraFlameGraphMenuItems(e,t):[]],extraHeaderElements:m().createElement(o.export.menu.Component,{model:o.export.menu,query:o.export.query,timeRange:o.export.timeRange}),keepFocusOnDataChange:!0})),s.isOpen("ai")&&m().createElement(o.ai.panel.Component,{model:o.ai.panel,fetchParams:o.ai.fetchParams,onClose:s.close}),s.isOpen("function-details")&&m().createElement(o.gitHub.panel.Component,{model:o.gitHub.panel,timeRange:o.gitHub.timeRange,stackTrace:l.data.stacktrace,onClose:s.close}),m().createElement(o.recordingRules.modal.Component,{model:o.recordingRules.modal,isModalOpen:u.isOpen,functionName:u.functionName,onDismiss:()=>d({isOpen:!1}),onCreated:()=>{d({isOpen:!1})}}))}));const Kc=e=>({flex:r.css`
display: flex;
`,flamegraphPanel:r.css`
min-width: 0;
flex-grow: 1;
`,spinner:r.css`
margin-left: ${e.spacing(1)};
`});class zc extends o.Bs{onActivate(e){e&&this.initVariables(e);const t=o.jh.findByKeyAndType(this,"profileMetricId",Lt);return t.setState({query:Lt.QUERY_SERVICE_NAME_DEPENDENT}),t.update(!0),()=>{t.setState({query:Lt.QUERY_DEFAULT}),t.update(!0)}}initVariables(e){const{serviceName:t,profileMetricId:n,filters:r}=e.queryRunnerParams;if(t){o.jh.findByKeyAndType(this,"serviceName",Vt).changeValueTo(t)}if(n){o.jh.findByKeyAndType(this,"profileMetricId",Lt).changeValueTo(n)}if(r){o.jh.findByKeyAndType(this,"filters",nn).setState({filters:r})}}getVariablesAndGridControls(){return{variables:[o.jh.findByKeyAndType(this,"serviceName",Vt),o.jh.findByKeyAndType(this,"profileMetricId",Lt),o.jh.findByKeyAndType(this,"filters",nn)],gridControls:[]}}static Component({model:e}){const t=(0,i.useStyles2)(Wc),{mainTimeseries:n,body:r}=e.useState();return m().createElement("div",{className:t.flex},m().createElement("div",{className:t.mainTimeseries},m().createElement(n.Component,{model:n})),m().createElement(r.Component,{model:r}))}constructor({item:e}){super({key:"explore-service-flame-graph",mainTimeseries:new ro({item:e,includeExemplars:!0,headerActions:e=>[new o.dM({component:ll,props:{scene:this}}),new Br({type:"view-labels",item:e}),new xr({item:e})]}),body:new qc}),this.addActivationHandler(this.onActivate.bind(this,e))}}const Wc=e=>({flex:r.css`
display: flex;
flex-direction: column;
width: 100%;
gap: ${e.spacing(1)};
`,mainTimeseries:r.css`
height: ${ro.MIN_HEIGHT}px;
`});var Hc=n(2932),Yc=n(1159);function Zc(e,t,n,r,o,i,a){try{var s=e[i](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function Xc(){return Jc.apply(this,arguments)}function Jc(){var e;return e=function*(){(0,d.r)("g_pyroscope_app_share_link_clicked");try{yield navigator.clipboard.writeText(function(){const e=new URL(window.location.toString()),{searchParams:t}=e;return t.get("from")||t.set("from",Mo().from),t.get("to")||t.set("to",Mo().to),["from","to","from-2","to-2","from-3","to-3","diffFrom","diffTo","diffFrom-2","diffTo-2"].forEach((e=>{const n=t.get(e);n&&t.set(e,String(f.dateMath.parse(n).valueOf()))})),e}().toString()),(0,a.qq)(["Link copied to clipboard!"])}catch(e){be.v.error(e,{info:"Error while creating the shareable link!"})}},Jc=function(){var t=this,n=arguments;return new Promise((function(r,o){var i=e.apply(t,n);function a(e){Zc(i,r,o,a,s,"next",e)}function s(e){Zc(i,r,o,a,s,"throw",e)}a(void 0)}))},Jc.apply(this,arguments)}function Qc({options:e,value:t,onChange:n}){const o=(0,i.useStyles2)(eu),a=e.findIndex((e=>e.value===t));return m().createElement("div",{className:o.explorationTypeContainer,"data-testid":"exploration-types"},m().createElement("div",{className:o.label},"Exploration"),m().createElement("div",{className:o.breadcrumb},e.map(((s,l)=>{const c=t===s.value,u=(d=l,a===e.length-1?d===a?"primary":"secondary":d<=a?"primary":"secondary");var d;const f=[c&&"active","primary"===u&&"primary"];return m().createElement(p.Fragment,{key:s.value},m().createElement(i.Button,{className:(0,r.cx)(o.button,...f),variant:u,size:"sm","aria-label":s.label,icon:s.icon,onClick:c?h.f:()=>n(s.value),tooltip:s.description,tooltipPlacement:"top","data-testid":c?"is-active":void 0},s.label),l<e.length-3&&m().createElement("div",{className:a!==e.length-1&&l<=a-1?(0,r.cx)(o.arrow,"arrow",...f):o.arrow}))}))))}const eu=e=>({explorationTypeContainer:r.css`
display: flex;
align-items: center;
`,label:r.css`
display: flex;
gap: 2px;
align-items: center;
font-size: 14px;
margin-right: ${e.spacing(1)};
${e.breakpoints.down("xxl")} {
display: none;
}
`,breadcrumb:r.css`
display: flex;
align-items: center;
height: 32px;
line-height: 32px;
.active {
background-color: ${e.colors.primary.main};
}
.arrow.primary {
background-color: ${e.colors.primary.main};
}
& button.primary:not(.active),
& .arrow.primary:not(.active) {
opacity: 0.7;
}
& button.primary:not(.active):hover {
opacity: 1;
background-color: ${e.colors.primary.main};
}
`,button:r.css`
height: 27px;
line-height: 27px;
border-radius: 15px;
&:hover {
border-color: ${e.colors.primary.main};
}
&.active:hover {
cursor: default;
background-color: ${e.colors.primary.main};
}
&:nth-last-child(2) {
margin-left: ${e.spacing(1)};
}
&:nth-last-child(1) {
margin-left: ${e.spacing(2)};
}
`,arrow:r.css`
background-color: ${e.colors.text.disabled};
width: 10px;
height: 2px;
`});function tu(e){const t=null===C.useChromeHeaderHeight||void 0===C.useChromeHeaderHeight?void 0:(0,C.useChromeHeaderHeight)();var n;const o=(0,i.useStyles2)(nu,null!=t?t:0,null!==(n=e.isEmbedded)&&void 0!==n&&n),{data:a,actions:s}=function({explorationType:e,controls:t,body:n,$variables:r,onChangeExplorationType:o}){const[i,a]=e===ou.DIFF_FLAME_GRAPH?[]:t,s=r.state.variables[0],l=null==n?void 0:n.state.primary;if("function"!=typeof l.getVariablesAndGridControls)throw new Error(`Error while rendering "${l.constructor.name}": the "getVariablesAndGridControls" method is missing! Please implement it.`);const{variables:c,gridControls:u}=l.getVariablesAndGridControls(),m=s.useState().value,f=(0,Yc.useNavigate)();return{data:{explorationType:e,dataSourceVariable:s,timePickerControl:i,refreshPickerControl:a,sceneVariables:c,gridControls:u,body:n,dataSourceUid:m,serviceName:e!==ou.ALL_SERVICES&&e!==ou.FAVORITES?rn(r,"serviceName"):void 0},actions:{onChangeExplorationType:o,onClickShareLink:Xc,onClickRecordingRules:(0,p.useCallback)((()=>{(0,d.r)("g_pyroscope_app_open_recording_rules_view"),f(`${Ns.Gy}${Ns.bw.RECORDING_RULES}`,{state:{referrer:window.location.href}})}),[f]),onClickAdHoc:(0,p.useCallback)((()=>{(0,d.r)("g_pyroscope_app_upload_ad_hoc_clicked"),f(`${Ns.Gy}${Ns.bw.ADHOC}`,{state:{referrer:window.location.href}})}),[f]),onClickUserSettings:(0,p.useCallback)((()=>{(0,d.r)("g_pyroscope_app_user_settings_clicked"),f(`${Ns.Gy}${Ns.bw.SETTINGS}`,{state:{referrer:window.location.href}})}),[f])}}}(e),{settings:l}=(0,Ui._)(),{explorationType:c,dataSourceVariable:u,timePickerControl:f,refreshPickerControl:h,sceneVariables:g,gridControls:b,serviceName:y}=a,{component:v}=(0,C.usePluginComponent)("grafana-o11yinsights-app/insights-launcher/v1"),E=m().createElement(i.Menu,null,m().createElement(i.Menu.Item,{ariaLabel:"View recording rules",label:"View recording rules",onClick:s.onClickRecordingRules}),m().createElement(i.Menu.Item,{ariaLabel:"Add recording rule",label:"Add recording rule",onClick:e.onCreateRecordingRule}));return m().createElement("div",{className:o.header,"data-testid":"allControls"},!e.isEmbedded&&m().createElement(fs,null),m().createElement("div",{className:o.appControls,"data-testid":"appControls"},m().createElement("div",{className:o.appControlsLeft},m().createElement(Qc,{options:iu.EXPLORATION_TYPE_OPTIONS,value:c,onChange:s.onChangeExplorationType})),m().createElement("div",{className:o.appControlsRight},v&&m().createElement(i.ErrorBoundary,null,(({error:e})=>e?void 0:m().createElement(v,{dataSourceUid:u.getValueText(),serviceName:y}))),f&&m().createElement(f.Component,{key:f.state.key,model:f}),h&&m().createElement(h.Component,{key:h.state.key,model:h}),!e.isEmbedded&&m().createElement("div",{className:o.appMiscButtons},(null==l?void 0:l.enableMetricsFromProfiles)&&On.g.metricsFromProfiles&&m().createElement(m().Fragment,null,m().createElement(i.Dropdown,{overlay:E},m().createElement(i.IconButton,{name:"gf-prometheus",tooltip:"Recording rules","aria-label":"Recording rules"}))),m().createElement(i.IconButton,{name:"upload",tooltip:"Upload ad hoc profiles",onClick:s.onClickAdHoc}),m().createElement(i.IconButton,{name:"cog",tooltip:"View/edit tenant settings",onClick:s.onClickUserSettings}),m().createElement(i.IconButton,{name:"share-alt",tooltip:"Copy shareable link to the clipboard",onClick:s.onClickShareLink}),m().createElement(Hc.U,null)))),m().createElement("div",{id:`scene-controls-${c}`,className:o.sceneControls,"data-testid":"sceneControls"},!e.isEmbedded&&m().createElement(i.Field,{label:u.state.label,className:(0,r.cx)(o.sceneVariable,u.state.name),"data-testid":u.state.name},m().createElement(u.Component,{model:u})),g.map((e=>m().createElement(i.Field,{key:e.state.name,label:"Filters"===e.state.label?m().createElement("div",{className:o.sceneVariableLabel},m().createElement(i.Icon,{name:"filter",className:o.icon}),e.state.label):e.state.label,className:(0,r.cx)(o.sceneVariable,e.state.name),"data-testid":e.state.name},m().createElement(e.Component,{model:e})))),b.map((e=>m().createElement(i.Field,{key:e.state.key,id:e.state.key,className:o.gridControl,label:""},m().createElement(e.Component,{model:e}))))))}const nu=(e,t,n)=>({header:r.css`
background-color: ${n?e.colors.background.primary:e.colors.background.canvas};
position: sticky;
top: ${n?0:t}px;
z-index: 1;
padding-bottom: ${e.spacing(2)};
`,appControls:r.css`
display: flex;
padding: ${e.spacing(1)} 0;
justify-content: space-between;
gap: ${e.spacing(2)};
flex-flow: wrap;
`,appControlsLeft:r.css`
display: flex;
gap: ${e.spacing(1)};
`,appControlsRight:r.css`
display: flex;
gap: ${e.spacing(1)};
`,appMiscButtons:r.css`
display: flex;
align-items: center;
gap: 4px;
border: 1px solid ${e.colors.border.weak};
background-color: ${e.colors.background.secondary};
height: 32px;
padding: 0 ${e.spacing(1)};
& svg {
width: 18px;
height: 18px;
}
`,sceneControls:r.css`
display: flex;
flex-wrap: wrap;
gap: ${e.spacing(1)};
padding: 0;
margin-top: 20px;
`,sceneVariable:r.css`
display: flex;
margin-bottom: 0;
& #dataSource {
width: ${e.spacing(32)};
}
&.filters {
flex-grow: 1;
}
&.compare-presets {
margin-left: auto;
text-align: right;
}
`,sceneVariableLabel:r.css`
font-size: 12px;
font-weight: 500;
line-height: 15px;
height: 15px;
margin-bottom: 4px;
color: ${e.colors.text.primary};
max-width: 480px;
`,icon:r.css`
display: inline-block;
margin-right: 4px;
`,gridControl:r.css`
margin-bottom: 0;
&#quick-filter {
flex: 1;
min-width: 112px;
}
`});function ru(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var ou=function(e){return e.ALL_SERVICES="all",e.PROFILE_TYPES="profiles",e.LABELS="labels",e.FLAME_GRAPH="flame-graph",e.DIFF_FLAME_GRAPH="diff-flame-graph",e.FAVORITES="favorites",e}({});class iu extends o.Bs{onActivate(){const e=this.subscribeToVariableChanges(),t=this.subscribeToEvents();return this.state.explorationType||this.setExplorationType({type:iu.DEFAULT_EXPLORATION_TYPE}),()=>{t.unsubscribe(),e.unsubscribe()}}getUrlState(){return{explorationType:this.state.explorationType}}updateFromUrl(e){if(this.initialFilters&&this.initialFilters.length>0)this.setExplorationType({type:"labels",comesFromUserAction:!1});else if("string"==typeof e.explorationType&&e.explorationType!==this.state.explorationType){const t=e.explorationType;this.setExplorationType({type:Object.values(ou).includes(t)?t:iu.DEFAULT_EXPLORATION_TYPE})}}registerRuntimeDataSources(){try{o.Go.registerRuntimeDataSource({dataSource:new Qo}),o.Go.registerRuntimeDataSource({dataSource:new Sr}),o.Go.registerRuntimeDataSource({dataSource:new _n})}catch(e){const{message:t}=e;/A runtime data source with uid (.+) has already been registered/.test(t)||(0,a.jx)(e,["Fail to register all the runtime data sources!","The application cannot work as expected, please try reloading the page or if the problem persists, contact your organization admin."])}}subscribeToVariableChanges(){const e=o.jh.findByKeyAndType(this,"dataSource",qt).subscribeToState(((e,t)=>{e.value&&e.value!==t.value&&(nn.resetAll(this),this.resetSpanSelector())})),t=o.jh.findByKeyAndType(this,"serviceName",Vt).subscribeToState(((e,t)=>{e.value&&e.value!==t.value&&(nn.resetAll(this),e.options.some((e=>e.value===t.value))&&this.resetSpanSelector())})),n=o.jh.findByKeyAndType(this,"profileMetricId",Lt).subscribeToState(((e,t)=>{e.value&&e.value!==t.value&&this.resetSpanSelector()})),r=o.jh.findByKeyAndType(this,"filters",nn).subscribeToState(((e,t)=>{JSON.stringify(e.filters)!==JSON.stringify(t.filters)&&this.resetSpanSelector()}));return{unsubscribe(){t.unsubscribe(),e.unsubscribe(),r.unsubscribe(),n.unsubscribe()}}}subscribeToEvents(){const e=this.subscribeToEvent(Ir,(e=>{this.setExplorationType({type:"profiles",comesFromUserAction:!0,item:e.payload.item})})),t=this.subscribeToEvent(Rr,(e=>{this.setExplorationType({type:"labels",comesFromUserAction:!0,item:e.payload.item})})),n=this.subscribeToEvent(Nr,(e=>{this.setExplorationType({type:"flame-graph",comesFromUserAction:!0,item:e.payload.item})})),r=this.subscribeToEvent(oo,(e=>{const{useAncestorTimeRange:t,clearDiffRange:n,baselineFilters:r,comparisonFilters:o}=e.payload;this.setExplorationType({type:"diff-flame-graph",comesFromUserAction:!0,bodySceneOptions:{useAncestorTimeRange:t,clearDiffRange:n,baselineFilters:r,comparisonFilters:o}})})),o=this.subscribeToEvent(sl,(()=>{this.resetSpanSelector()}));return{unsubscribe(){r.unsubscribe(),n.unsubscribe(),t.unsubscribe(),e.unsubscribe(),o.unsubscribe()}}}setExplorationType({type:e,comesFromUserAction:t,item:n,bodySceneOptions:r}){t&&(s(),this.resetVariables(e)),this.setState({explorationType:e,body:this.buildBodyScene(e,n,r)})}resetSpanSelector(){o.jh.findByKeyAndType(this,"spanSelector",Vo).reset()}resetVariables(e){o.jh.findByKeyAndType(this,"quick-filter",fr).reset(),o.jh.findByKeyAndType(this,"groupBy",to).changeValueTo(to.DEFAULT_VALUE),o.jh.findByKeyAndType(this,"panel-type-switcher",sn).reset(),this.resetSpanSelector(),["labels","flame-graph","diff-flame-graph"].includes(e)||o.jh.findByKeyAndType(this,"filters",nn).reset()}buildBodyScene(e,t,n){let r;switch(e){case"profiles":r=new Bo({item:t});break;case"labels":r=new Fo({item:t});break;case"flame-graph":r=new zc({item:t});break;case"diff-flame-graph":r=new Es(n||{});break;case"favorites":r=new Hr;break;default:r=new Mr}return new o.n1({direction:"column",primary:r})}static Component({model:e}){const t=(0,i.useStyles2)(au),{data:n,actions:r}=e.useProfilesExplorer(),{explorationType:o,controls:a,body:s,$variables:l,dataSourceUid:c}=n,[u,d]=(0,p.useState)({isOpen:!1}),{createRecordingRuleModal:f,isEmbedded:h}=e.useState();return m().createElement(il,null,m().createElement(el,{dataSourceUid:c},m().createElement(tu,{explorationType:o,controls:a,body:s,$variables:l,onChangeExplorationType:r.onChangeExplorationType,isEmbedded:h,onCreateRecordingRule:()=>{d({isOpen:!0})}}),m().createElement("div",{className:t.body,"data-testid":"sceneBody"},s&&m().createElement(s.Component,{model:s})),u.isOpen&&m().createElement(ui.Component,{model:f,isModalOpen:u.isOpen,functionName:u.functionName,onDismiss:()=>d({isOpen:!1}),onCreated:()=>{d({isOpen:!1})}})))}constructor(e){var t,n;super({key:"profiles-explorer",explorationType:e.initialFilters&&e.initialFilters.length>0?"labels":void 0,body:void 0,$timeRange:null!==(t=null==e?void 0:e.$timeRange)&&void 0!==t?t:new o.JZ(Mo()),$variables:null!==(n=null==e?void 0:e.$variables)&&void 0!==n?n:new o.Pj({variables:[new qt({initialDS:null==e?void 0:e.initialDS}),new Vt({initialFilters:null==e?void 0:e.initialFilters}),new Lt,new nn({key:"filters",initialFilters:(()=>{if(!(null==e?void 0:e.initialFilters))return;const t=e.initialFilters.filter((e=>"service_name"!==e.key));return t.length>0?t:void 0})()}),new nn({key:"filtersBaseline"}),new nn({key:"filtersComparison"}),new to,new Vo]}),createRecordingRuleModal:new ui,controls:[new o.KE({isOnCanvas:!0}),new o.WM({isOnCanvas:!0})],gridControls:[new fr({placeholder:""}),new sn,new ur,new pr],isEmbedded:null==e?void 0:e.isEmbedded}),ru(this,"_urlSync",new o.So(this,{keys:["explorationType"]})),ru(this,"initialFilters",void 0),ru(this,"onChangeExplorationType",(e=>{(0,d.r)("g_pyroscope_app_exploration_type_clicked",{explorationType:e}),this.setExplorationType({type:e,comesFromUserAction:!0})})),ru(this,"useProfilesExplorer",(()=>{const{explorationType:e,controls:t,body:n,$variables:r}=this.useState();return{data:{explorationType:e,controls:t,body:n,$variables:r,dataSourceUid:r.state.variables[0].useState().value},actions:{onChangeExplorationType:this.onChangeExplorationType}}})),this.registerRuntimeDataSources(),this.initialFilters=null==e?void 0:e.initialFilters,this.addActivationHandler(this.onActivate.bind(this))}}ru(iu,"EXPLORATION_TYPE_OPTIONS",[{value:"all",label:"All services",description:"Overview of all services, for any given profile type"},{value:"profiles",label:"Profile types",description:"Overview of all the profile types for a single service"},{value:"labels",label:"Labels",description:"Single service label exploration and filtering"},{value:"flame-graph",label:"Flame graph",description:"Single service flame graph"},{value:"diff-flame-graph",label:"Diff flame graph",description:"Compare the differences between two flame graphs"},{value:"favorites",label:"Favorites",description:"Overview of favorited visualizations",icon:"favorite"}]),ru(iu,"DEFAULT_EXPLORATION_TYPE",iu.EXPLORATION_TYPE_OPTIONS[0].value);const au=()=>({body:r.css`
position: relative;
z-index: 0;
background: transparent;
`})},8629:(e,t,n)=>{n.d(t,{C:()=>j});var r=n(7781),o=n(9318),i=n(2007),a=n(5959),s=n.n(a),l=n(2673),c=n(7907),u=(n(8727),n(2249)),d=n.n(u),p=n(9090);function m(e,t,n,r,o,i,a){try{var s=e[i](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}class f extends p.Q{upload(e,t){var n,r=this;return(n=function*(){const n=yield r.fetch("/upload/v1",{method:"POST",body:JSON.stringify({name:e,profile:btoa(JSON.stringify(t)),fileTypeData:{units:t.metadata.units,spyName:t.metadata.spyName},type:"json"})});return yield n.json()},function(){var e=this,t=arguments;return new Promise((function(r,o){var i=n.apply(e,t);function a(e){m(i,r,o,a,s,"next",e)}function s(e){m(i,r,o,a,s,"throw",e)}a(void 0)}))})()}constructor(){super("https://flamegraph.com/api",{"content-type":"application/json"})}}const h=new f;var g=n(9897);const b=new Intl.DateTimeFormat("fr-CA",{year:"numeric",month:"2-digit",day:"2-digit",hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"});function y(e){const t=b.formatToParts(e).reduce(((e,{type:t,value:n})=>(e[t]=n,e)),{});return`${t.year}-${t.month}-${t.day}_${t.hour}${t.minute}`}function v(e){const t=new Date(Math.round(1e3*e.from.unix())),n=new Date(Math.round(1e3*e.to.unix()));return`${y(t)}-to-${y(n)}`}function E(e){const[t,n]=e===g.N.BASELINE?["diffFrom","diffTo"]:["diffFrom-2","diffTo-2"],o=new URLSearchParams(window.location.search),i=o.get(t),a=o.get(n);return{raw:{from:i,to:a},from:(0,r.dateTimeParse)(i),to:(0,r.dateTimeParse)(a)}}function S(e){const t=["baseline",v(E(g.N.BASELINE)),"comparison",v(E(g.N.COMPARISON))];return e?[e,...t].join("_"):["flamegraph",...t].join("_")}function w(e,t,n,r,o,i,a){try{var s=e[i](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function O({profile:e,enableFlameGraphDotComExport:t}){const n=function(){var t,n=(t=function*(){(0,c.r)("g_pyroscope_app_export_profile",{format:"flamegraph.com"});const t=S(e.metadata.appName);let n;try{n=yield h.upload(t,e)}catch(e){return void(0,l.jx)(e,["Failed to export to flamegraph.com!",e.message])}const r=document.createElement("a");r.target="_blank",r.href=n.url,document.body.appendChild(r),r.click(),document.body.removeChild(r)},function(){var e=this,n=arguments;return new Promise((function(r,o){var i=t.apply(e,n);function a(e){w(i,r,o,a,s,"next",e)}function s(e){w(i,r,o,a,s,"throw",e)}a(void 0)}))});return function(){return n.apply(this,arguments)}}();return{data:{shouldDisplayFlamegraphDotCom:Boolean(t)},actions:{downloadPng:()=>{(0,c.r)("g_pyroscope_app_export_profile",{format:"png"});const t=`${S(e.metadata.appName)}.png`;document.querySelector('canvas[data-testid="flameGraph"]').toBlob((e=>{if(e)d()(e,t);else{const e=new Error("No Blob, the image cannot be created.");(0,l.jx)(e,["Failed to export to png!",e.message])}}),"image/png")},downloadJson:()=>{(0,c.r)("g_pyroscope_app_export_profile",{format:"json"});const t=`${S(e.metadata.appName)}.json`,n=`data:text/json;charset=utf-8,${encodeURIComponent(JSON.stringify(e))}`;try{d()(n,t)}catch(e){return void(0,l.jx)(e,["Failed to export to JSON!",e.message])}},uploadToFlamegraphDotCom:n}}}function x(e){const{actions:t}=O(e);return s().createElement(i.Menu,null,s().createElement(i.Menu.Item,{label:"png",onClick:t.downloadPng}),s().createElement(i.Menu.Item,{label:"json",onClick:t.downloadJson}))}function P(e){const{profile:t,enableFlameGraphDotComExport:n}=e;return s().createElement(i.Dropdown,{overlay:s().createElement(x,{profile:t,enableFlameGraphDotComExport:n})},s().createElement(i.Button,{icon:"download-alt",size:"sm",variant:"secondary",fill:"outline","aria-label":"Export profile data",tooltip:"Export profile data"}))}const C=(0,a.memo)(P);function T(e,t,n){const r=[],o=n?7:4;for(let i=0;i<e.length;i+=o)r.push({level:0,label:n?t[e[i+6]]:t[e[i+3]],offset:e[i],val:e[i+1],self:e[i+2],selfRight:n?e[i+5]:0,valRight:n?e[i+4]:0,valTotal:n?e[i+1]+e[i+4]:e[i+1],offsetRight:n?e[i+3]:0,offsetTotal:n?e[i]+e[i+3]:e[i],children:[]});return r}function A({profile:e,diff:t,vertical:n,enableFlameGraphDotComExport:l,collapsedFlamegraphs:c,getExtraContextMenuButtons:u,showAnalyzeWithAssistant:d}){const{isLight:p}=(0,i.useTheme2)(),m=(0,a.useMemo)((()=>function(e,t,n,o){if(!e.length)return;const i=[];for(let n=0;n<e.length;n++){i[n]=[];for(const r of T(e[n],t,o))if(r.level=n,i[n].push(r),n>0){const e=i[n].slice(0,-1).reduce(((e,t)=>t.offsetTotal+t.valTotal+e),0)+r.offsetTotal,t=i[n-1];let o=0;for(const n of t){const t=o+n.offsetTotal,i=t+n.valTotal;if(t<=e&&i>e){n.children.push(r);break}o+=n.offsetTotal+n.valTotal}}}const a=[i[0][0]],s=[],l=[],c=[],u=[],d=[],p=[];for(;a.length;){const e=a.shift();s.push(e.label),l.push(e.level),c.push(e.self),u.push(e.val),d.push(e.selfRight),p.push(e.valRight),a.unshift(...e.children)}let m="short";switch(n){case"samples":case"trace_samples":case"lock_nanoseconds":case"nanoseconds":m="ns";break;case"bytes":m="bytes"}const f=[{name:"level",values:l},{name:"label",values:s,type:r.FieldType.string},{name:"self",values:c,config:{unit:m}},{name:"value",values:u,config:{unit:m}}];o&&f.push({name:"selfRight",values:d,config:{unit:m}},{name:"valueRight",values:p,config:{unit:m}});const h={name:"response",meta:{preferredVisualisationType:"flamegraph"},fields:f};return(0,r.createDataFrame)(h)}(e.flamebearer.levels,e.flamebearer.names,e.metadata.units,Boolean(t))),[e,t]);return s().createElement(o.Ay,{data:m,disableCollapsing:!c,extraHeaderElements:s().createElement(C,{profile:e,enableFlameGraphDotComExport:l}),vertical:n,getTheme:()=>(0,r.createTheme)({colors:{mode:p?"light":"dark"}}),getExtraContextMenuButtons:u,keepFocusOnDataChange:!0,showAnalyzeWithAssistant:d})}const j=(0,a.memo)(A)},2673:(e,t,n)=>{n.d(t,{HA:()=>c,jx:()=>l,qq:()=>u});var r=n(7781),o=n(8531),i=n(2096);function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function s(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))})),e}function l(e,t){const n=t.reduce(((e,t,n)=>s(function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter((function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable})))),r.forEach((function(t){a(e,t,n[t])}))}return e}({},e),{[`info${n+1}`]:t})),{handheldBy:"displayError"});i.v.error(e,n),(0,o.getAppEvents)().publish({type:r.AppEvents.alertError.name,payload:t})}function c(e){i.v.warn(e),(0,o.getAppEvents)().publish({type:r.AppEvents.alertWarning.name,payload:e})}function u(e){(0,o.getAppEvents)().publish({type:r.AppEvents.alertSuccess.name,payload:e})}},897:(e,t,n)=>{n.d(t,{f:()=>r});const r=()=>{}},7907:(e,t,n)=>{n.d(t,{r:()=>c});var r=n(8531),o=n(4137),i=n(5176);const a=o.bw.EXPLORE.slice(1);function s(){const{pathname:e}=new URL(window.location.toString());return e.split("/").pop()||""}function l(){const e={appRelease:r.config.apps[o.R2].version,appVersion:i.t,page:s()};return e.page===a&&(e.view=new URLSearchParams(window.location.search).get("explorationType")||""),e}function c(e,t){(0,r.reportInteraction)(e,{props:t,meta:l()})}},6415:(e,t,n)=>{function r(e){const[,t=""]=e.match(/.+\{.*service_name="([^"]+)".*\}/)||[],[,n=""]=e.match(/([^{]+)\{.*}/)||[],r=e.substring(e.indexOf("{")),o=r.replace(/(\{|\})/,"").split(",").map((e=>{var t;return null===(t=e.match(/\W*([^=!~]+)(=|!=|=~|!~)"(.*)"/))||void 0===t?void 0:t[0]})).filter((e=>e&&!e.includes("service_name")));return{serviceId:t,profileMetricId:n,labelsSelector:r,labels:o}}n.d(t,{m:()=>r})},9993:(e,t,n)=>{n.d(t,{I:()=>l});var r=n(2673),o=n(9326),i=n(8873),a=n(2096),s=n(1159);function l(){const{searchParams:e,pushNewUrl:t}=function(){const e=(0,s.useNavigate)(),t=(0,s.useLocation)();return{searchParams:new URLSearchParams(t.search),pushNewUrl:t=>{const n=new URLSearchParams(window.location.search);for(const[e,r]of Object.entries(t))n.set(e,r);e({search:n.toString()},{replace:!0})}}}();var n;const l=Number(null!==(n=e.get("maxNodes"))&&void 0!==n?n:""),c=e=>{t({maxNodes:String(e)})};return function(e,t){const{isFetching:n,error:s,settings:l}=(0,i._)({enabled:!e});if(!e&&!n)s?((0,r.HA)(["Error while retrieving the plugin settings!","Some features might not work as expected (e.g. flame graph max nodes). Please try to reload the page, sorry for the inconvenience."]),a.v.error(s),t(o.a.maxNodes)):t(l.maxNodes)}(l>0,c),[l,c]}},5656:(e,t,n)=>{n.d(t,{O:()=>s});var r=n(8531),o=n(2096),i=n(8169),a=n(9090);class s extends a.Q{static getPyroscopeDataSources(){return Object.values(r.config.datasources).filter((e=>"grafana-pyroscope-datasource"===e.type))}static selectDefaultDataSource(){var e;const t=s.getPyroscopeDataSources(),n=new URL(window.location.href).searchParams.get("var-dataSource"),r=null===(e=i.x.get(i.x.KEYS.PROFILES_EXPLORER))||void 0===e?void 0:e.dataSource,a=t.find((e=>e.uid===n))||t.find((e=>e.uid===r))||t.find((e=>e.jsonData.overridesDefault))||t.find((e=>e.isDefault))||t[0];return a||(o.v.warn("Cannot find any Pyroscope data source! Please add and configure a Pyroscope data source to your Grafana instance."),{uid:"no-data-source-configured"})}static getBaseUrl(){const e=s.selectDefaultDataSource();let t=r.config.appSubUrl||"";return"/"!==t.at(-1)&&(t+="/"),`${t}api/datasources/proxy/uid/${e.uid}`}constructor(){var e,t;super(s.getBaseUrl().toString(),{"content-type":"application/json","X-Grafana-Org-Id":String((null===(t=r.config.bootData)||void 0===t||null===(e=t.user)||void 0===e?void 0:e.orgId)||"")})}}},9090:(e,t,n)=>{n.d(t,{Q:()=>u});var r=n(897);function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class i extends Error{constructor(e,t){let n=`HTTP ${e.status} (${e.statusText||"?"})`;(null==t?void 0:t.message)&&(n=`${n}${t.message}`),super(n),o(this,"response",void 0),o(this,"reason",void 0),this.response=e}}function a(e,t,n,r,o,i,a){try{var s=e[i](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function s(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function l(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter((function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable})))),r.forEach((function(t){s(e,t,n[t])}))}return e}function c(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))})),e}class u{fetch(e,t){var n,o=this;return(n=function*(){o.abortController=new AbortController;const{signal:n}=o.abortController,a=`${o.baseUrl}${e}`,s=l({},o.defaultHeaders,null==t?void 0:t.headers),u=c(l({signal:n},t),{headers:s});let d;try{if(d=yield fetch(a,u),!d.ok)throw new i(d,yield d.json().catch(r.f))}catch(e){var p;throw o.isAbortError(e)&&(e.reason=(null==t||null===(p=t.signal)||void 0===p?void 0:p.reason)||n.reason),e}finally{o.abortController=null}return d},function(){var e=this,t=arguments;return new Promise((function(r,o){var i=n.apply(e,t);function s(e){a(i,r,o,s,l,"next",e)}function l(e){a(i,r,o,s,l,"throw",e)}s(void 0)}))})()}abort(e){this.abortController&&this.abortController.abort(e)}isAbortError(e){return e instanceof DOMException&&"AbortError"===e.name}constructor(e,t={}){s(this,"baseUrl",""),s(this,"defaultHeaders",{}),s(this,"abortController",null),this.baseUrl=e,this.defaultHeaders=Object.freeze(t)}}},4386:(e,t,n)=>{n.d(t,{y:()=>o});const r=JSON.parse('{"block:contentions:count:contentions:count":{"id":"block:contentions:count:contentions:count","description":"Number of blocking contentions","type":"contentions","group":"block","unit":"short","aggregationType":"cumulative"},"block:delay:nanoseconds:contentions:count":{"id":"block:delay:nanoseconds:contentions:count","description":"Time spent in blocking delays","type":"delay","group":"block","unit":"ns","aggregationType":"cumulative"},"goroutine:goroutine:count:goroutine:count":{"id":"goroutine:goroutine:count:goroutine:count","description":"Number of goroutines","type":"goroutine","group":"goroutine","unit":"short","aggregationType":"instant"},"goroutines:goroutine:count:goroutine:count":{"id":"goroutines:goroutine:count:goroutine:count","description":"Number of goroutines","type":"goroutine","group":"goroutine","unit":"short","aggregationType":"instant"},"memory:alloc_in_new_tlab_bytes:bytes::":{"id":"memory:alloc_in_new_tlab_bytes:bytes::","description":"Size of memory allocated inside Thread-Local Allocation Buffers (TLAB)","type":"alloc_in_new_tlab_bytes","group":"memory","unit":"bytes","aggregationType":"cumulative"},"memory:alloc_in_new_tlab_objects:count::":{"id":"memory:alloc_in_new_tlab_objects:count::","description":"Number of objects allocated inside Thread-Local Allocation Buffers (TLAB)","type":"alloc_in_new_tlab_objects","group":"memory","unit":"short","aggregationType":"cumulative"},"memory:alloc_objects:count:space:bytes":{"id":"memory:alloc_objects:count:space:bytes","description":"Number of objects allocated","type":"alloc_objects","group":"memory","unit":"short","aggregationType":"cumulative"},"memory:alloc_space:bytes:space:bytes":{"id":"memory:alloc_space:bytes:space:bytes","description":"Size of memory allocated in the heap","type":"alloc_space","group":"memory","unit":"bytes","aggregationType":"cumulative"},"memory:inuse_objects:count:space:bytes":{"id":"memory:inuse_objects:count:space:bytes","description":"Number of objects currently in use","type":"inuse_objects","group":"memory","unit":"short","aggregationType":"instant"},"memory:inuse_space:bytes:space:bytes":{"id":"memory:inuse_space:bytes:space:bytes","description":"Size of memory currently in use","type":"inuse_space","group":"memory","unit":"bytes","aggregationType":"instant"},"mutex:contentions:count:contentions:count":{"id":"mutex:contentions:count:contentions:count","description":"Number of observed mutex contentions","type":"contentions","group":"mutex","unit":"short","aggregationType":"cumulative"},"mutex:delay:nanoseconds:contentions:count":{"id":"mutex:delay:nanoseconds:contentions:count","description":"Time spent waiting due to mutex contentions","type":"delay","group":"mutex","unit":"ns","aggregationType":"cumulative"},"process_cpu:alloc_samples:count:cpu:nanoseconds":{"id":"process_cpu:alloc_samples:count:cpu:nanoseconds","description":"Number of memory allocation samples during CPU time","type":"alloc_samples","group":"memory","unit":"short","aggregationType":"cumulative"},"process_cpu:alloc_size:bytes:cpu:nanoseconds":{"id":"process_cpu:alloc_size:bytes:cpu:nanoseconds","description":"Size of memory allocated during CPU time","type":"alloc_size","group":"alloc_size","unit":"bytes","aggregationType":"cumulative"},"process_cpu:cpu:nanoseconds:cpu:nanoseconds":{"id":"process_cpu:cpu:nanoseconds:cpu:nanoseconds","description":"CPU time consumed","type":"cpu","group":"process_cpu","unit":"ns","aggregationType":"cumulative"},"process_cpu:exception:count:cpu:nanoseconds":{"id":"process_cpu:exception:count:cpu:nanoseconds","description":"Number of exceptions within the sampled CPU time","type":"exceptions","group":"exceptions","unit":"short","aggregationType":"cumulative"},"process_cpu:lock_count:count:cpu:nanoseconds":{"id":"process_cpu:lock_count:count:cpu:nanoseconds","description":"Number of lock acquisitions attempted during CPU time","type":"lock_count","group":"locks","unit":"short","aggregationType":"instant"},"process_cpu:lock_time:nanoseconds:cpu:nanoseconds":{"id":"process_cpu:lock_time:nanoseconds:cpu:nanoseconds","description":"Cumulative time spent acquiring locks","type":"lock_time","group":"locks","unit":"ns","aggregationType":"cumulative"},"process_cpu:samples:count::milliseconds":{"id":"process_cpu:samples:count::milliseconds","description":"Number of process samples collected","type":"samples","group":"process_cpu","unit":"short","aggregationType":"cumulative"},"process_cpu:samples:count:cpu:nanoseconds":{"id":"process_cpu:samples:count:cpu:nanoseconds","description":"Number of samples collected over CPU time","type":"samples","group":"process_cpu","unit":"short","aggregationType":"instant"}}');function o(e){if(r[e])return r[e];const[t="?",n="?"]=e?e.split(":"):[];return{id:e,description:"",type:n,group:t,unit:"short"}}},4164:(e,t,n)=>{n.d(t,{q:()=>r});const r=new(n(9398).E)({defaultOptions:{queries:{networkMode:"always",retry:!1,refetchOnWindowFocus:!1}}})},4002:(e,t,n)=>{n.d(t,{e:()=>E});var r=n(3632),o=n(5656),i=n(2951),a=n(1298);const s=(0,i.w)("ChR0eXBlcy92MS90eXBlcy5wcm90bxIIdHlwZXMudjEiKAoJTGFiZWxQYWlyEgwKBG5hbWUYASABKAkSDQoFdmFsdWUYAiABKAkiewoLUHJvZmlsZVR5cGUSCgoCSUQYASABKAkSDAoEbmFtZRgCIAEoCRITCgtzYW1wbGVfdHlwZRgEIAEoCRITCgtzYW1wbGVfdW5pdBgFIAEoCRITCgtwZXJpb2RfdHlwZRgGIAEoCRITCgtwZXJpb2RfdW5pdBgHIAEoCSItCgZMYWJlbHMSIwoGbGFiZWxzGAEgAygLMhMudHlwZXMudjEuTGFiZWxQYWlyIk4KBlNlcmllcxIjCgZsYWJlbHMYASADKAsyEy50eXBlcy52MS5MYWJlbFBhaXISHwoGcG9pbnRzGAIgAygLMg8udHlwZXMudjEuUG9pbnQiWwoFUG9pbnQSDQoFdmFsdWUYASABKAESEQoJdGltZXN0YW1wGAIgASgDEjAKC2Fubm90YXRpb25zGAMgAygLMhsudHlwZXMudjEuUHJvZmlsZUFubm90YXRpb24iLwoRUHJvZmlsZUFubm90YXRpb24SCwoDa2V5GAEgASgJEg0KBXZhbHVlGAIgASgJIlAKEkxhYmVsVmFsdWVzUmVxdWVzdBIMCgRuYW1lGAEgASgJEhAKCG1hdGNoZXJzGAIgAygJEg0KBXN0YXJ0GAMgASgDEgsKA2VuZBgEIAEoAyIkChNMYWJlbFZhbHVlc1Jlc3BvbnNlEg0KBW5hbWVzGAEgAygJIkEKEUxhYmVsTmFtZXNSZXF1ZXN0EhAKCG1hdGNoZXJzGAEgAygJEg0KBXN0YXJ0GAIgASgDEgsKA2VuZBgDIAEoAyIjChJMYWJlbE5hbWVzUmVzcG9uc2USDQoFbmFtZXMYASADKAkikQEKCUJsb2NrSW5mbxIMCgR1bGlkGAEgASgJEhAKCG1pbl90aW1lGAIgASgDEhAKCG1heF90aW1lGAMgASgDEi0KCmNvbXBhY3Rpb24YBCABKAsyGS50eXBlcy52MS5CbG9ja0NvbXBhY3Rpb24SIwoGbGFiZWxzGAUgAygLMhMudHlwZXMudjEuTGFiZWxQYWlyIkIKD0Jsb2NrQ29tcGFjdGlvbhINCgVsZXZlbBgBIAEoBRIPCgdzb3VyY2VzGAIgAygJEg8KB3BhcmVudHMYAyADKAkiXAoSU3RhY2tUcmFjZVNlbGVjdG9yEiUKCWNhbGxfc2l0ZRgBIAMoCzISLnR5cGVzLnYxLkxvY2F0aW9uEh8KBmdvX3BnbxgCIAEoCzIPLnR5cGVzLnYxLkdvUEdPIhgKCExvY2F0aW9uEgwKBG5hbWUYASABKAkiOgoFR29QR08SFgoOa2VlcF9sb2NhdGlvbnMYASABKA0SGQoRYWdncmVnYXRlX2NhbGxlZXMYAiABKAgiGAoWR2V0UHJvZmlsZVN0YXRzUmVxdWVzdCJqChdHZXRQcm9maWxlU3RhdHNSZXNwb25zZRIVCg1kYXRhX2luZ2VzdGVkGAEgASgIEhsKE29sZGVzdF9wcm9maWxlX3RpbWUYAiABKAMSGwoTbmV3ZXN0X3Byb2ZpbGVfdGltZRgDIAEoAyprChlUaW1lU2VyaWVzQWdncmVnYXRpb25UeXBlEiQKIFRJTUVfU0VSSUVTX0FHR1JFR0FUSU9OX1RZUEVfU1VNEAASKAokVElNRV9TRVJJRVNfQUdHUkVHQVRJT05fVFlQRV9BVkVSQUdFEAFiBnByb3RvMw");const l=(0,i.w)("CiFzZXR0aW5ncy92MS9yZWNvcmRpbmdfcnVsZXMucHJvdG8SC3NldHRpbmdzLnYxIiUKF0dldFJlY29yZGluZ1J1bGVSZXF1ZXN0EgoKAmlkGAEgASgJIkQKGEdldFJlY29yZGluZ1J1bGVSZXNwb25zZRIoCgRydWxlGAEgASgLMhouc2V0dGluZ3MudjEuUmVjb3JkaW5nUnVsZSIbChlMaXN0UmVjb3JkaW5nUnVsZXNSZXF1ZXN0IkcKGkxpc3RSZWNvcmRpbmdSdWxlc1Jlc3BvbnNlEikKBXJ1bGVzGAEgAygLMhouc2V0dGluZ3MudjEuUmVjb3JkaW5nUnVsZSL4AQoaVXBzZXJ0UmVjb3JkaW5nUnVsZVJlcXVlc3QSCgoCaWQYASABKAkSEwoLbWV0cmljX25hbWUYAiABKAkSEAoIbWF0Y2hlcnMYAyADKAkSEAoIZ3JvdXBfYnkYBCADKAkSLAoPZXh0ZXJuYWxfbGFiZWxzGAUgAygLMhMudHlwZXMudjEuTGFiZWxQYWlyEhIKCmdlbmVyYXRpb24YBiABKAMSPQoRc3RhY2t0cmFjZV9maWx0ZXIYByABKAsyHS5zZXR0aW5ncy52MS5TdGFja3RyYWNlRmlsdGVySACIAQFCFAoSX3N0YWNrdHJhY2VfZmlsdGVyIkcKG1Vwc2VydFJlY29yZGluZ1J1bGVSZXNwb25zZRIoCgRydWxlGAEgASgLMhouc2V0dGluZ3MudjEuUmVjb3JkaW5nUnVsZSIoChpEZWxldGVSZWNvcmRpbmdSdWxlUmVxdWVzdBIKCgJpZBgBIAEoCSIdChtEZWxldGVSZWNvcmRpbmdSdWxlUmVzcG9uc2UilgIKDVJlY29yZGluZ1J1bGUSCgoCaWQYASABKAkSEwoLbWV0cmljX25hbWUYAiABKAkSFAoMcHJvZmlsZV90eXBlGAMgASgJEhAKCG1hdGNoZXJzGAQgAygJEhAKCGdyb3VwX2J5GAUgAygJEiwKD2V4dGVybmFsX2xhYmVscxgGIAMoCzITLnR5cGVzLnYxLkxhYmVsUGFpchISCgpnZW5lcmF0aW9uGAcgASgDEj0KEXN0YWNrdHJhY2VfZmlsdGVyGAggASgLMh0uc2V0dGluZ3MudjEuU3RhY2t0cmFjZUZpbHRlckgAiAEBEhMKC3Byb3Zpc2lvbmVkGAkgASgIQhQKEl9zdGFja3RyYWNlX2ZpbHRlciJrChBTdGFja3RyYWNlRmlsdGVyEkUKDWZ1bmN0aW9uX25hbWUYASABKAsyKS5zZXR0aW5ncy52MS5TdGFja3RyYWNlRmlsdGVyRnVuY3Rpb25OYW1lSACIAQFCEAoOX2Z1bmN0aW9uX25hbWUiYwocU3RhY2t0cmFjZUZpbHRlckZ1bmN0aW9uTmFtZRIVCg1mdW5jdGlvbl9uYW1lGAEgASgJEiwKC21ldHJpY190eXBlGAIgASgOMhcuc2V0dGluZ3MudjEuTWV0cmljVHlwZSKQAgoSUmVjb3JkaW5nUnVsZVN0b3JlEgoKAmlkGAEgASgJEhMKC21ldHJpY19uYW1lGAIgASgJEh4KFnByb21ldGhldXNfZGF0YV9zb3VyY2UYAyABKAkSEAoIbWF0Y2hlcnMYBCADKAkSEAoIZ3JvdXBfYnkYBSADKAkSLAoPZXh0ZXJuYWxfbGFiZWxzGAYgAygLMhMudHlwZXMudjEuTGFiZWxQYWlyEhIKCmdlbmVyYXRpb24YByABKAMSPQoRc3RhY2t0cmFjZV9maWx0ZXIYCCABKAsyHS5zZXR0aW5ncy52MS5TdGFja3RyYWNlRmlsdGVySACIAQFCFAoSX3N0YWNrdHJhY2VfZmlsdGVyIlkKE1JlY29yZGluZ1J1bGVzU3RvcmUSLgoFcnVsZXMYASADKAsyHy5zZXR0aW5ncy52MS5SZWNvcmRpbmdSdWxlU3RvcmUSEgoKZ2VuZXJhdGlvbhgCIAEoAyoXCgpNZXRyaWNUeXBlEgkKBVRPVEFMEAAyuwMKFVJlY29yZGluZ1J1bGVzU2VydmljZRJhChBHZXRSZWNvcmRpbmdSdWxlEiQuc2V0dGluZ3MudjEuR2V0UmVjb3JkaW5nUnVsZVJlcXVlc3QaJS5zZXR0aW5ncy52MS5HZXRSZWNvcmRpbmdSdWxlUmVzcG9uc2UiABJnChJMaXN0UmVjb3JkaW5nUnVsZXMSJi5zZXR0aW5ncy52MS5MaXN0UmVjb3JkaW5nUnVsZXNSZXF1ZXN0Gicuc2V0dGluZ3MudjEuTGlzdFJlY29yZGluZ1J1bGVzUmVzcG9uc2UiABJqChNVcHNlcnRSZWNvcmRpbmdSdWxlEicuc2V0dGluZ3MudjEuVXBzZXJ0UmVjb3JkaW5nUnVsZVJlcXVlc3QaKC5zZXR0aW5ncy52MS5VcHNlcnRSZWNvcmRpbmdSdWxlUmVzcG9uc2UiABJqChNEZWxldGVSZWNvcmRpbmdSdWxlEicuc2V0dGluZ3MudjEuRGVsZXRlUmVjb3JkaW5nUnVsZVJlcXVlc3QaKC5zZXR0aW5ncy52MS5EZWxldGVSZWNvcmRpbmdSdWxlUmVzcG9uc2UiAGIGcHJvdG8z",[s]),c=(0,a.Z)(l,9),u=(0,a.Z)(l,10);var d=function(e){return e[e.TOTAL=0]="TOTAL",e}({});function p(e,t,n,r,o,i,a){try{var s=e[i](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function m(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var i=e.apply(t,n);function a(e){p(i,r,o,a,s,"next",e)}function s(e){p(i,r,o,a,s,"throw",e)}a(void 0)}))}}class f extends o.O{get(){var e=this,t=()=>super.fetch;return m((function*(){return t().call(e,"/settings.v1.RecordingRulesService/ListRecordingRules",{method:"POST",body:JSON.stringify({})}).then((e=>e.json())).then((e=>e.rules?e.rules.map((e=>function(e){var t,n;let r="";for(let t of e.matchers||[])if(t.includes("service_name=")){var o;r=(null==t||null===(o=t.match(/service_name="([^"]+)"/))||void 0===o?void 0:o[1])||"";break}const i=null===(n=e.stacktraceFilter)||void 0===n||null===(t=n.functionName)||void 0===t?void 0:t.functionName;return{id:e.id,metricName:e.metricName,serviceName:r,profileType:e.profileType,matchers:e.matchers,groupBy:e.groupBy||[],functionName:i,readonly:e.provisioned}}(e))):[]))}))()}create(e){var t=this,n=()=>super.fetch;return m((function*(){const o=e.serviceName?[`{ service_name="${e.serviceName}" }`]:[];let i={metricName:e.metricName,matchers:[...o,`{ __profile_type__="${e.profileType}"}`,...e.matchers||[]],groupBy:e.groupBy||[]};return e.functionName&&(i.stacktraceFilter=(0,r.v)(c,{functionName:(0,r.v)(u,{functionName:e.functionName,metricType:d.TOTAL})})),n().call(t,"/settings.v1.RecordingRulesService/UpsertRecordingRule",{method:"POST",body:JSON.stringify(i)}).then((e=>e.json()))}))()}remove(e){var t=this,n=()=>super.fetch;return m((function*(){return n().call(t,"/settings.v1.RecordingRulesService/DeleteRecordingRule",{method:"POST",body:JSON.stringify({id:e.id})}).then((e=>e.json()))}))()}}const h=new f;var g=n(3715),b=n(7616),y=n(6667);function v(e,t,n,r,o,i,a){try{var s=e[i](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function E({enabled:e}={}){const t=(0,g.jE)(),{isFetching:n,error:r,data:o}=(0,b.I)({enabled:e,queryKey:["recording_rules"],queryFn:()=>h.get()}),{mutateAsync:i}=(0,y.n)({mutationFn:e=>h.create(e),networkMode:"always"}),{mutateAsync:a}=(0,y.n)({mutationFn:function(){var e,n=(e=function*(e){yield h.remove(e),yield t.invalidateQueries({queryKey:["recording_rules"]})},function(){var t=this,n=arguments;return new Promise((function(r,o){var i=e.apply(t,n);function a(e){v(i,r,o,a,s,"next",e)}function s(e){v(i,r,o,a,s,"throw",e)}a(void 0)}))});return function(e){return n.apply(this,arguments)}}(),networkMode:"always"});return{isFetching:n,error:h.isAbortError(r)?null:r,recordingRules:o,mutate:i,remove:a}}},9326:(e,t,n)=>{n.d(t,{a:()=>r});const r=Object.freeze({collapsedFlamegraphs:!1,maxNodes:16384,enableFlameGraphDotComExport:!0,enableFunctionDetails:!0,enableMetricsFromProfiles:!1})},1835:(e,t,n)=>{n.d(t,{g:()=>o});var r=n(8531);const o={metricsFromProfiles:!!r.config.featureToggles.metricsFromProfiles,grafanaAssistantInProfilesDrilldown:!!r.config.featureToggles.grafanaAssistantInProfilesDrilldown,exemplars:!!r.config.featureToggles.profilesExemplars}},8873:(e,t,n)=>{n.d(t,{_:()=>f});var r,o,i,a=n(5656),s=n(7616),l=n(6667),c=n(9326);function u(e,t,n,r,o,i,a){try{var s=e[i](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function d(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var i=e.apply(t,n);function a(e){u(i,r,o,a,s,"next",e)}function s(e){u(i,r,o,a,s,"throw",e)}a(void 0)}))}}class p extends a.O{get(){var e=this,t=()=>super.fetch;return d((function*(){return t().call(e,"/settings.v1.SettingsService/Get",{method:"POST",body:JSON.stringify({})}).then((e=>e.json())).then((e=>{var t;const n=null===(t=e.settings)||void 0===t?void 0:t.find((({name:e})=>e===p.PLUGIN_SETTING_NAME));return n?JSON.parse(n.value):{}}))}))()}set(e){var t=this,n=()=>super.fetch;return d((function*(){return n().call(t,"/settings.v1.SettingsService/Set",{method:"POST",body:JSON.stringify({setting:{name:p.PLUGIN_SETTING_NAME,value:JSON.stringify(e)}})}).then((e=>e.json()))}))()}}i="pluginSettings",(o="PLUGIN_SETTING_NAME")in(r=p)?Object.defineProperty(r,o,{value:i,enumerable:!0,configurable:!0,writable:!0}):r[o]=i;const m=()=>new p;function f({enabled:e}={}){const t=m(),{isFetching:n,error:r,data:o}=(0,s.I)({enabled:e,queryKey:["settings","ds-uid-"+a.O.selectDefaultDataSource().uid],queryFn:()=>t.get().then((e=>Object.keys(c.a).reduce(((e,t)=>{var n,r,o;return null!==(o=(n=e)[r=t])&&void 0!==o||(n[r]=c.a[t]),e}),e)))}),{mutateAsync:i}=(0,l.n)({mutationFn:e=>t.set(e),networkMode:"always"});return{isFetching:n,error:t.isAbortError(r)?null:r,settings:o,mutate:i}}},8132:(e,t,n)=>{n.d(t,{n1:()=>d,Js:()=>m});var r=n(9128),o=n(7276),i=n(8531),a=n(4137),s=n(5176),l=n(7421);const c=new Map([["dev",{environment:"dev",appName:"grafana-pyroscope-dev",faroUrl:"https://faro-collector-ops-eu-south-0.grafana-ops.net/collect/48e03a2647389f2f6494af7f975b4084"}],["ops",{environment:"ops",appName:"grafana-pyroscope-ops",faroUrl:"https://faro-collector-ops-eu-south-0.grafana-ops.net/collect/b5cfd5eeb412cf5e74bd828b4ddd17ff"}],["prod",{environment:"prod",appName:"grafana-pyroscope-prod",faroUrl:"https://faro-collector-ops-eu-south-0.grafana-ops.net/collect/6cbe17b3af4b72ce5936bf4d15a5c393"}]]);let u=null;const d=()=>u,p=e=>u=e;function m(){if(d())return;const e=function(){const e=(0,l.u)();if(e&&c.has(e))return c.get(e)}();if(!e)return;const{environment:t,faroUrl:n,appName:u}=e,{apps:m,bootData:f,buildInfo:h}=i.config,g=m[a.R2].version,b=f.user.email,y=`v${h.version} (${h.edition})`;p((0,r.p)({url:n,app:{name:u,release:g,version:s.t,environment:t,namespace:y},user:{email:b},instrumentations:[...(0,o.w)({captureConsole:!1})],isolate:!0,beforeSend:e=>{var t,n,r;return(null!==(n=null===(t=e.meta.page)||void 0===t?void 0:t.url)&&void 0!==n?n:"").includes(a.Gy)?(e.meta.view={name:new URLSearchParams(null===(r=e.meta.page)||void 0===r?void 0:r.url).get("explorationType")||""},e):null}}))}},7421:(e,t,n)=>{n.d(t,{u:()=>o});const r=[{regExp:/localhost/,environment:"local"},{regExp:/grafana-dev\.net/,environment:"dev"},{regExp:/grafana-ops\.net/,environment:"ops"},{regExp:/grafana\.net/,environment:"prod"}];function o(){var e,t;if(!(null===(t=window)||void 0===t||null===(e=t.location)||void 0===e?void 0:e.host))return null;const n=r.find((({regExp:e})=>e.test(window.location.host)));return n?n.environment:null}},2096:(e,t,n)=>{n.d(t,{v:()=>m});var r=n(5438),o=n(8132),i=n(7421);function a(e,t){if(t.has(e))throw new TypeError("Cannot initialize the same private elements twice on an object")}function s(e,t,n){if(!t.has(e))throw new TypeError("attempted to "+n+" private field on non-instance");return t.get(e)}function l(e,t,n){return function(e,t,n){if(t.set)t.set.call(e,n);else{if(!t.writable)throw new TypeError("attempted to set read only private field");t.value=n}}(e,s(e,t,"set"),n),n}function c(e,t,n){if(!t.has(e))throw new TypeError("attempted to get private field on non-instance");return n}var u=new WeakMap,d=new WeakSet;function p(e,t){var n;"prod"!==function(e,t){return t.get?t.get.call(e):t.value}(n=this,s(n,u,"get"))&&console[e](...t)}const m=new class{trace(){var e;c(this,d,p).call(this,"trace",[]),null===(e=(0,o.n1)())||void 0===e||e.api.pushLog([],{level:r.$b.TRACE})}debug(...e){var t;c(this,d,p).call(this,"debug",e),null===(t=(0,o.n1)())||void 0===t||t.api.pushLog(e,{level:r.$b.DEBUG})}info(...e){var t;c(this,d,p).call(this,"info",e),null===(t=(0,o.n1)())||void 0===t||t.api.pushLog(e,{level:r.$b.INFO})}log(...e){var t;c(this,d,p).call(this,"log",e),null===(t=(0,o.n1)())||void 0===t||t.api.pushLog(e,{level:r.$b.LOG})}warn(...e){var t;c(this,d,p).call(this,"warn",e),null===(t=(0,o.n1)())||void 0===t||t.api.pushLog(e,{level:r.$b.WARN})}error(e,t){var n;c(this,d,p).call(this,"error",[e]),t&&c(this,d,p).call(this,"error",["Error context",t]),null===(n=(0,o.n1)())||void 0===n||n.api.pushError(e,{context:t})}constructor(){var e,t;a(e=this,t=d),t.add(e),function(e,t,n){a(e,t),t.set(e,n)}(this,u,{writable:!0,value:void 0}),l(this,u,(0,i.u)())}}},8169:(e,t,n)=>{n.d(t,{x:()=>l});var r=n(2096),o=n(2533);function i(e,t){var n=function(e,t,n){if(!t.has(e))throw new TypeError("attempted to "+n+" private field on non-instance");return t.get(e)}(e,t,"get");return function(e,t){return t.get?t.get.call(e):t.value}(e,n)}function a(e,t,n){!function(e,t){if(t.has(e))throw new TypeError("Cannot initialize the same private elements twice on an object")}(e,t),t.set(e,n)}var s=new WeakMap;const l=new class{has(e){return i(this,s).hasOwnProperty(e)}get(e){if(!this.has(e))return null;try{return JSON.parse(i(this,s).getItem(e))}catch(t){return r.v.error(t,{info:`Error parsing JSON for storage item "${e}"!`}),null}}set(e,t){try{i(this,s).setItem(e,JSON.stringify(t))}catch(t){r.v.error(t,{info:`Error setting storage item "${e}"!`})}}constructor(){var e,t,n;a(this,s,{writable:!0,value:window.localStorage}),e=this,t="KEYS",n={SETTINGS:`${o.id}.userSettings`,GITHUB_INTEGRATION:`${o.id}.gitHubIntegration`,PROFILES_EXPLORER:`${o.id}.profilesExplorer`},t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}}},8536:(e,t,n)=>{n.d(t,{_:()=>s});var r=n(2007),o=n(2096),i=n(5959),a=n.n(i);function s({severity:e,title:t,message:n,error:i,errorContext:s}){return i&&o.v.error(i,s),a().createElement(r.Alert,{title:t,severity:e},i&&a().createElement(a().Fragment,null,i.message,a().createElement("br",null)),n)}},2932:(e,t,n)=>{n.d(t,{U:()=>g});var r=n(6089),o=n(7781),i=n(8531),a=n(2007),s=n(5959),l=n.n(s),c=n(5176),u=n(9660);const d=c.t,p=`https://github.com/grafana/profiles-drilldown/commit/${d}`,{buildInfo:m}=i.config;function f(){const e=(0,a.useStyles2)(b),{meta:{info:{version:t,updated:n}}}=(0,o.usePluginContext)()||{meta:{info:{version:"?.?.?",updated:"?"}}};return l().createElement("div",{className:e.menuHeader},l().createElement("h5",null,l().createElement(u.S,{size:"small"}),"Grafana Profiles Drilldown v",t),l().createElement("div",{className:e.subTitle},"Last update: ",n))}function h(){const e="dev"===d,t=e?d:d.slice(0,8);return l().createElement(a.Menu,{header:l().createElement(f,null)},l().createElement(a.Menu.Item,{label:`Commit SHA: ${t}`,icon:"github",onClick:()=>window.open(p),disabled:e}),l().createElement(a.Menu.Item,{label:"Changelog",icon:"list-ul",onClick:()=>window.open("https://github.com/grafana/profiles-drilldown/blob/main/CHANGELOG.md")}),l().createElement(a.Menu.Item,{label:"Contribute",icon:"external-link-alt",onClick:()=>window.open("https://github.com/grafana/profiles-drilldown/blob/main/docs/CONTRIBUTING.md")}),l().createElement(a.Menu.Item,{label:"Documentation",icon:"document-info",onClick:()=>window.open("https://grafana.com/docs/grafana/latest/explore/simplified-exploration/profiles")}),l().createElement(a.Menu.Item,{label:"Report an issue",icon:"bug",onClick:()=>window.open("https://github.com/grafana/profiles-drilldown/issues/new?template=bug_report.md")}),l().createElement(a.Menu.Divider,null),l().createElement(a.Menu.Item,{label:`Grafana ${m.edition} v${m.version} (${m.env})`,icon:"github",onClick:()=>window.open(`https://github.com/grafana/grafana/commit/${m.commit}`)}))}function g(){return l().createElement(a.Dropdown,{overlay:()=>l().createElement(h,null),placement:"bottom-end"},l().createElement(a.IconButton,{name:"info-circle","aria-label":"Plugin info",title:"Plugin info"}))}const b=e=>({menuHeader:r.css`
padding: ${e.spacing(.5,1)};
white-space: nowrap;
`,subTitle:r.css`
color: ${e.colors.text.secondary};
font-size: ${e.typography.bodySmall.fontSize};
`})},9660:(e,t,n)=>{n.d(t,{S:()=>l});var r=n(6089),o=n(2007),i=n(5959),a=n.n(i);function s({size:e}){const t=(0,o.useStyles2)(c);return a().createElement("img",{className:(0,r.cx)(t.logo,e),src:"public/plugins/grafana-pyroscope-app/img/logo.svg"})}const l=a().memo(s),c=()=>({logo:r.css`
&.small {
width: 16px;
height: 16px;
margin-right: 4px;
position: relative;
top: -2px;
}
&.large {
width: 40px;
height: 40px;
}
`})},5176:(e,t,n)=>{n.d(t,{t:()=>r});const r="dev"},2533:e=>{e.exports=JSON.parse('{"id":"grafana-pyroscope-app"}')}}]);
//# sourceMappingURL=72.js.map?_cache=34826ce7944a28353b38