Files
server/opt/grafana/plugins/grafana-pyroscope-app/133.js
2025-12-22 11:03:43 +00:00

963 lines
343 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.
This file contains Unicode characters that might be confused with other characters. 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([[133],{3792:(e,t,n)=>{n.r(t),n.d(t,{App:()=>jp});var r=n(6089),o=n(7781),a=n(8531),i=n(2007);const s=new(n(9398).E)({defaultOptions:{queries:{networkMode:"always",retry:!1,refetchOnWindowFocus:!1}}});var l=n(9128),c=n(7276);const u=JSON.parse('{"id":"grafana-pyroscope-app"}'),d=u.id,p=`/a/${d}`;var m=function(e){return e.EXPLORE="/explore",e.ADHOC="/ad-hoc",e.SETTINGS="/settings",e.RECORDING_RULES="/recording-rules",e.GITHUB_CALLBACK="/github/callback",e}({});const f="dev",h=[{regExp:/localhost/,environment:"local"},{regExp:/grafana-dev\.net/,environment:"dev"},{regExp:/grafana-ops\.net/,environment:"ops"},{regExp:/grafana\.net/,environment:"prod"}];function g(){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=h.find((({regExp:e})=>e.test(window.location.host)));return n?n.environment:null}const b=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 y=null;const v=()=>y;var E=n(3715),S=n(5959),w=n.n(S),O=n(5438);function P(e,t){if(t.has(e))throw new TypeError("Cannot initialize the same private elements twice on an object")}function x(e,t,n){if(!t.has(e))throw new TypeError("attempted to "+n+" private field on non-instance");return t.get(e)}function C(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,x(e,t,"set"),n),n}function T(e,t,n){if(!t.has(e))throw new TypeError("attempted to get private field on non-instance");return n}var A=new WeakMap,N=new WeakSet;function k(e,t){var n;"prod"!==function(e,t){return t.get?t.get.call(e):t.value}(n=this,x(n,A,"get"))&&console[e](...t)}const j=new class{trace(){var e;T(this,N,k).call(this,"trace",[]),null===(e=v())||void 0===e||e.api.pushLog([],{level:O.$b.TRACE})}debug(...e){var t;T(this,N,k).call(this,"debug",e),null===(t=v())||void 0===t||t.api.pushLog(e,{level:O.$b.DEBUG})}info(...e){var t;T(this,N,k).call(this,"info",e),null===(t=v())||void 0===t||t.api.pushLog(e,{level:O.$b.INFO})}log(...e){var t;T(this,N,k).call(this,"log",e),null===(t=v())||void 0===t||t.api.pushLog(e,{level:O.$b.LOG})}warn(...e){var t;T(this,N,k).call(this,"warn",e),null===(t=v())||void 0===t||t.api.pushLog(e,{level:O.$b.WARN})}error(e,t){var n;T(this,N,k).call(this,"error",[e]),t&&T(this,N,k).call(this,"error",["Error context",t]),null===(n=v())||void 0===n||n.api.pushError(e,{context:t})}constructor(){var e,t;P(e=this,t=N),t.add(e),function(e,t,n){P(e,t),t.set(e,n)}(this,A,{writable:!0,value:void 0}),C(this,A,g())}};function R(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 I(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 D=new WeakMap;const _=new class{has(e){return R(this,D).hasOwnProperty(e)}get(e){if(!this.has(e))return null;try{return JSON.parse(R(this,D).getItem(e))}catch(t){return j.error(t,{info:`Error parsing JSON for storage item "${e}"!`}),null}}set(e,t){try{R(this,D).setItem(e,JSON.stringify(t))}catch(t){j.error(t,{info:`Error setting storage item "${e}"!`})}}constructor(){var e,t,n;I(this,D,{writable:!0,value:window.localStorage}),e=this,t="KEYS",n={SETTINGS:`${u.id}.userSettings`,GITHUB_INTEGRATION:`${u.id}.gitHubIntegration`,PROFILES_EXPLORER:`${u.id}.profilesExplorer`},t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}},L=()=>{};function F(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class B extends Error{constructor(e,t){let n=`HTTP ${e.status} (${e.statusText||"?"})`;(null==t?void 0:t.message)&&(n=`${n}${t.message}`),super(n),F(this,"response",void 0),F(this,"reason",void 0),this.response=e}}function $(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function M(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function V(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){M(e,t,n[t])}))}return e}function U(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 G{fetch(e,t){var n,r=this;return(n=function*(){r.abortController=new AbortController;const{signal:n}=r.abortController,o=`${r.baseUrl}${e}`,a=V({},r.defaultHeaders,null==t?void 0:t.headers),i=U(V({signal:n},t),{headers:a});let s;try{if(s=yield fetch(o,i),!s.ok)throw new B(s,yield s.json().catch(L))}catch(e){var l;throw r.isAbortError(e)&&(e.reason=(null==t||null===(l=t.signal)||void 0===l?void 0:l.reason)||n.reason),e}finally{r.abortController=null}return s},function(){var e=this,t=arguments;return new Promise((function(r,o){var a=n.apply(e,t);function i(e){$(a,r,o,i,s,"next",e)}function s(e){$(a,r,o,i,s,"throw",e)}i(void 0)}))})()}abort(e){this.abortController&&this.abortController.abort(e)}isAbortError(e){return e instanceof DOMException&&"AbortError"===e.name}constructor(e,t={}){M(this,"baseUrl",""),M(this,"defaultHeaders",{}),M(this,"abortController",null),this.baseUrl=e,this.defaultHeaders=Object.freeze(t)}}class q extends G{static getPyroscopeDataSources(){return Object.values(a.config.datasources).filter((e=>"grafana-pyroscope-datasource"===e.type))}static selectDefaultDataSource(){var e;const t=q.getPyroscopeDataSources(),n=new URL(window.location.href).searchParams.get("var-dataSource"),r=null===(e=_.get(_.KEYS.PROFILES_EXPLORER))||void 0===e?void 0:e.dataSource,o=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 o||(j.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=q.selectDefaultDataSource();let t=a.config.appSubUrl||"";return"/"!==t.at(-1)&&(t+="/"),`${t}api/datasources/proxy/uid/${e.uid}`}constructor(){var e,t;super(q.getBaseUrl().toString(),{"content-type":"application/json","X-Grafana-Org-Id":String((null===(t=a.config.bootData)||void 0===t||null===(e=t.user)||void 0===e?void 0:e.orgId)||"")})}}var K=n(7616);function z(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}const W=new class extends q{get(){var e,t=this;return(e=function*(){const e=yield t.fetch("/querier.v1.QuerierService/GetProfileStats",{method:"POST",body:JSON.stringify({})}),n=yield e.json();return{hasIngestedData:n.dataIngested,oldestProfileTime:Number(n.oldestProfileTime),newestProfileTime:Number(n.newestProfileTime)}},function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){z(a,r,o,i,s,"next",e)}function s(e){z(a,r,o,i,s,"throw",e)}i(void 0)}))})()}};function H(){const[e,t]=(0,S.useState)(!1),n=q.getPyroscopeDataSources().length,{isFetching:r,error:o,stats:a}=function({enabled:e}){const{isFetching:t,error:n,data:r,refetch:o}=(0,K.I)({enabled:e,placeholderData:()=>({hasIngestedData:!0,oldestProfileTime:0,newestProfileTime:0}),queryKey:["tenant-stats"],queryFn:()=>(W.abort(),W.get())});return{isFetching:t,error:W.isAbortError(n)?null:n,stats:r,refetch:o}}({enabled:n>0}),i=!r&&!(null==a?void 0:a.hasIngestedData);return{data:{shouldShowLoadingPage:!o&&r,shouldShowOnboardingPage:(o||!n||i)&&!e,shouldShowNoDataSourceBanner:!n},actions:{closeModal(){t(!0)}}}}const Y=e=>({row:(0,r.css)({display:"flex",flexDirection:"row",justifyContent:"space-between",alignItems:"flex-start"}),headerColumn:(0,r.css)({display:"flex",flexDirection:"column",minWidth:"120px",alignItems:"start"}),column:(0,r.css)({display:"flex",flexDirection:"column",minWidth:"120px",alignItems:"end"}),tooltip:(0,r.css)({display:"flex",color:e.colors.text.secondary,fontSize:e.typography.bodySmall.fontSize}),contentWithIcon:(0,r.css)({display:"none",[`@media ${i.styleMixins.mediaUp(e.v1.breakpoints.sm)}`]:{display:"block"}})}),Z=e=>(0,o.formattedValueToString)((0,o.getValueFormat)("decbytes")(e)),X=e=>(0,o.formattedValueToString)((0,o.getValueFormat)("short")(e));function J(e){const t=(0,i.useStyles2)(Y),{data:n}=e,r=Z(n.queryImpact.totalBytesInTimeRange),o=(0,S.useMemo)((()=>w().createElement("div",{"data-testid":"queryAnalysis-popup"},w().createElement("div",{className:t.row},w().createElement("div",{className:t.headerColumn},"Data in time range"),w().createElement("div",{className:t.column},r),w().createElement("div",{className:t.column}," ")),void 0!==n.queryImpact.totalQueriedSeries&&w().createElement("div",{className:t.row},w().createElement("div",{className:t.headerColumn},"Series in query"),w().createElement("div",{className:t.column},X(n.queryImpact.totalQueriedSeries)),w().createElement("div",{className:t.column}," ")),w().createElement("div",{className:t.row},w().createElement("div",{className:t.headerColumn},"Deduplication"),w().createElement("div",{className:t.column},n.queryImpact.deduplicationNeeded?"yes":"no"),w().createElement("div",{className:t.column}," ")),w().createElement(i.Divider,null),w().createElement("div",{className:t.row},w().createElement("div",{className:t.headerColumn}," "),n.queryScopes.map(((e,n)=>w().createElement("div",{key:n,className:t.column},w().createElement("strong",null,e.componentType))))),w().createElement("div",{className:t.row},w().createElement("div",{className:t.headerColumn},"Replicas"),n.queryScopes.map(((e,n)=>w().createElement("div",{key:n,className:t.column},e.componentCount||"/")))),w().createElement("div",{className:t.row},w().createElement("div",{className:t.headerColumn},"Blocks"),n.queryScopes.map(((e,n)=>w().createElement("div",{key:n,className:t.column},X(e.blockCount)||"/")))),w().createElement("div",{className:t.row},w().createElement("div",{className:t.headerColumn},"Series"),n.queryScopes.map(((e,n)=>w().createElement("div",{key:n,className:t.column},X(e.seriesCount)||"/")))),w().createElement("div",{className:t.row},w().createElement("div",{className:t.headerColumn},"Profiles"),n.queryScopes.map(((e,n)=>w().createElement("div",{key:n,className:t.column},X(e.profileCount)||"/")))),w().createElement("div",{className:t.row},w().createElement("div",{className:t.headerColumn},"Samples"),n.queryScopes.map(((e,n)=>w().createElement("div",{key:n,className:t.column},X(e.sampleCount)||"/")))),w().createElement("div",{className:t.row},w().createElement("div",{className:t.headerColumn}," "),w().createElement("div",{className:t.column}," "),w().createElement("div",{className:t.column}," ")),w().createElement("div",{className:t.row},w().createElement("div",{className:t.headerColumn},"Index Store"),n.queryScopes.map(((e,n)=>w().createElement("div",{key:n,className:t.column},Z(e.indexBytes)||"/")))),w().createElement("div",{className:t.row},w().createElement("div",{className:t.headerColumn},"Profiles Store"),n.queryScopes.map(((e,n)=>w().createElement("div",{key:n,className:t.column},Z(e.profileBytes)||"/")))),w().createElement("div",{className:t.row},w().createElement("div",{className:t.headerColumn},"Symbols Store"),n.queryScopes.map(((e,n)=>w().createElement("div",{key:n,className:t.column},Z(e.symbolBytes)||"/")))))),[n,t,r]);return w().createElement(w().Fragment,null,void 0!==n.queryImpact.totalBytesInTimeRange?w().createElement(i.Toggletip,{content:o,fitContent:!0},w().createElement("div",{className:t.tooltip,"data-testid":"queryAnalysis-tooltip"},w().createElement("span",{className:t.contentWithIcon},"Stored data in time range: ",r)," ",w().createElement(i.IconButton,{name:"database","aria-label":"Query info"}))):null)}var Q=n(9814);function ee({size:e}){const t=(0,i.useStyles2)(ne);return w().createElement("img",{className:(0,r.cx)(t.logo,e),src:"public/plugins/grafana-pyroscope-app/img/logo.svg"})}const te=w().memo(ee),ne=()=>({logo:r.css`
&.small {
width: 16px;
height: 16px;
margin-right: 4px;
position: relative;
top: -2px;
}
&.large {
width: 40px;
height: 40px;
}
`}),re=f,oe=`https://github.com/grafana/profiles-drilldown/commit/${re}`,{buildInfo:ae}=a.config;function ie(){const e=(0,i.useStyles2)(ce),{meta:{info:{version:t,updated:n}}}=(0,o.usePluginContext)()||{meta:{info:{version:"?.?.?",updated:"?"}}};return w().createElement("div",{className:e.menuHeader},w().createElement("h5",null,w().createElement(te,{size:"small"}),"Grafana Profiles Drilldown v",t),w().createElement("div",{className:e.subTitle},"Last update: ",n))}function se(){const e="dev"===re,t=e?re:re.slice(0,8);return w().createElement(i.Menu,{header:w().createElement(ie,null)},w().createElement(i.Menu.Item,{label:`Commit SHA: ${t}`,icon:"github",onClick:()=>window.open(oe),disabled:e}),w().createElement(i.Menu.Item,{label:"Changelog",icon:"list-ul",onClick:()=>window.open("https://github.com/grafana/profiles-drilldown/blob/main/CHANGELOG.md")}),w().createElement(i.Menu.Item,{label:"Contribute",icon:"external-link-alt",onClick:()=>window.open("https://github.com/grafana/profiles-drilldown/blob/main/docs/CONTRIBUTING.md")}),w().createElement(i.Menu.Item,{label:"Documentation",icon:"document-info",onClick:()=>window.open("https://grafana.com/docs/grafana/latest/explore/simplified-exploration/profiles")}),w().createElement(i.Menu.Item,{label:"Report an issue",icon:"bug",onClick:()=>window.open("https://github.com/grafana/profiles-drilldown/issues/new?template=bug_report.md")}),w().createElement(i.Menu.Divider,null),w().createElement(i.Menu.Item,{label:`Grafana ${ae.edition} v${ae.version} (${ae.env})`,icon:"github",onClick:()=>window.open(`https://github.com/grafana/grafana/commit/${ae.commit}`)}))}function le(){return w().createElement(i.Dropdown,{overlay:()=>w().createElement(se,null),placement:"bottom-end"},w().createElement(i.IconButton,{name:"info-circle","aria-label":"Plugin info",title:"Plugin info"}))}const ce=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};
`});function ue({title:e,queryAnalysis:t}){const n=(0,i.useStyles2)(de),r="string"==typeof e?`${e} | Pyroscope`:"Pyroscope";return w().createElement(w().Fragment,null,w().createElement(Q.m,null,w().createElement("title",null,r)),w().createElement("div",{className:n.titleContainer},w().createElement(i.Stack,{justifyContent:"space-between"},w().createElement("div",null,w().createElement(te,{size:"large"}),w().createElement("h1",{className:n.title,"data-testid":"page-title"},e)),w().createElement("div",{className:n.infoArea},w().createElement(le,null),t?w().createElement(J,{data:t}):null))))}const de=e=>({titleContainer:r.css`
height: ${e.spacing(5)};
line-height: ${e.spacing(5)};
margin-bottom: ${e.spacing(3)};
`,title:r.css`
font-size: ${e.typography.h2.fontSize};
display: inline-block;
margin: 0;
position: relative;
top: 10px;
left: ${e.spacing(1)};
`,infoArea:r.css`
align-self: end;
margin-bottom: 0;
line-height: 20px;
text-align: right;
`}),pe=(0,S.memo)(ue);function me(){return w().createElement(a.PluginPage,{layout:o.PageLayoutType.Canvas},w().createElement(pe,{title:w().createElement("span",null,"Loading... ",w().createElement(i.Icon,{name:"fa fa-spinner"}))}))}const fe=e=>({link:r.css`
color: ${e.colors.text.link};
&:hover {
text-decoration: underline;
}
`});function he({href:e,children:t}){const n=(0,i.useStyles2)(fe);return w().createElement("a",{className:n.link,href:e,target:"_blank",rel:"noreferrer"},t," ",w().createElement(i.Icon,{name:"external-link-alt"}))}function ge(){return w().createElement(a.PluginPage,{layout:o.PageLayoutType.Canvas},w().createElement(pe,{title:"Grafana Profiles Drilldown"}),w().createElement(i.Alert,{severity:"error",title:"Missing Pyroscope data source!"},"This plugin requires a Pyroscope data source. Please"," ",w().createElement(he,{href:"/connections/datasources/new"},"add and configure a Pyroscope data source")," to your Grafana instance."))}const be="public/plugins/grafana-pyroscope-app/img/61b4cf746a6f58780f27.png",ye="public/plugins/grafana-pyroscope-app/img/58f0b0e1cfa063e4b662.png",ve="public/plugins/grafana-pyroscope-app/img/9c9cdd5175734d579007.png",Ee="public/plugins/grafana-pyroscope-app/img/bafee50693eb02088442.png";function Se(){const{instances:e}=function(){const{isFetching:e,error:t,data:n}=(0,K.I)({queryKey:["instances"],queryFn:()=>fetch("/api/plugin-proxy/cloud-home-app/grafanacom-api/instances").then((e=>e.json()))});return{isFetching:e,error:t,instances:n}}(),[t,n]=(0,S.useState)("https://grafana.com/auth/sign-in/"),r=/grafana(-dev|-ops)?\.net/.test(window.location.host);if(e&&e.orgSlug&&e.hpInstanceId){const r=`https://grafana.com/orgs/${e.orgSlug}/hosted-profiles/${e.hpInstanceId}`;t!==r&&n(r)}return{data:{settingsUrl:t,isCloud:r},actions:{}}}const we=e=>({onboardingRow:r.css`
background: ${e.colors.background.secondary};
display: flex;
margin-top: 16px;
gap: 20px;
padding: 20px;
margin-bottom: 2.5rem;
`,onboardingParagraph:r.css`
padding: 20px 64px;
text-align: center;
line-height: 2;
flex: 1;
margin: 0;
`,onboardingPanel:r.css`
flex: 1;
display: flex;
flex-flow: column wrap;
-webkit-box-align: center;
align-items: center;
margin-top: 16px;
text-align: center;
`,onboardingPanelHeader:r.css`
line-height: 1.5;
margin-bottom: 1em;
`,onboardingPanelImage:r.css`
width: 5rem;
margin-bottom: 1em;
`,hero:r.css`
display: flex;
flex-direction: row;
`,heroTitles:r.css`
flex: 1;
`,heroImage:r.css`
width: 40%;
margin-left: 16px;
margin-top: 16px;
margin-bottom: 16px;
border-radius: 3px;
`,onboardingPanelNumber:r.css`
color: rgb(236, 109, 19);
text-align: center;
display: grid;
place-items: center;
background-image: linear-gradient(135deg, currentcolor, 75%, rgb(204, 204, 220));
border-radius: 100%;
font-size: 2.5rem;
line-height: 5rem;
height: 5rem;
width: 5rem;
margin-bottom: 1em;
`,color2:r.css`
color: rgb(190, 85, 190);
`,color3:r.css`
color: rgb(126, 108, 218);
`,onboardingPanelNumberSpan:r.css`
color: rgb(220, 220, 220);
`,onboardingPanelDescription:r.css`
text-align: justify;
text-align: center;
line-height: 1.66;
margin-top: 0;
`,title:r.css`
margin-bottom: 0.5em;
line-height: 1.5;
`,subtitle:r.css`
margin-bottom: 1em;
line-height: 1.5;
font-size: 1.25rem;
`});function Oe(){const e=(0,i.useStyles2)(we),{data:t}=Se();return w().createElement("div",{"data-testid":"onboarding-modal"},w().createElement("div",{className:e.hero,"data-testid":"hero"},w().createElement("div",{className:e.heroTitles},w().createElement("h1",{className:e.title},"Welcome to Grafana Profiles Drilldown"),w().createElement("h2",{className:e.subtitle},"Optimize infrastructure spend, simplify debugging, and enhance application performance")),w().createElement("img",{src:ye,className:e.heroImage})),w().createElement("div",{"data-testid":"what-you-can-do"},w().createElement("h3",null,"What You Can Do"),w().createElement("div",{className:e.onboardingRow},w().createElement("div",{className:e.onboardingPanel},w().createElement("img",{className:e.onboardingPanelImage,src:ve}),w().createElement("h3",{className:e.onboardingPanelHeader},"Reduce Costs"),w().createElement("p",{className:e.onboardingPanelDescription},"Spot CPU spikes, memory leaks, and other inefficiencies with code-level visibility into resource usage. Teams can then optimize their code and lower infrastructure costs.")),w().createElement("div",{className:e.onboardingPanel},w().createElement("img",{className:e.onboardingPanelImage,src:be}),w().createElement("h3",{className:e.onboardingPanelHeader},"Decrease Latency"),w().createElement("p",{className:e.onboardingPanelDescription},"Maintain high speed and efficiency and improve application performance. In a competitive digital world, decreasing latency translates to increasing revenue.")),w().createElement("div",{className:e.onboardingPanel},w().createElement("img",{className:e.onboardingPanelImage,src:Ee}),w().createElement("h3",{className:e.onboardingPanelHeader},"Resolve Incidents Faster"),w().createElement("p",{className:e.onboardingPanelDescription},"Cut down the mean time to resolution (MTTR) by correlating continuous profiling data with metrics, logs, and traces to quickly identify the root cause of any issue.")))),w().createElement("div",{"data-testid":"how-to-get-started"},w().createElement("h3",null,"How to Get Started"),w().createElement("div",{className:e.onboardingRow},t.isCloud?w().createElement(w().Fragment,null,w().createElement("div",{className:e.onboardingPanel},w().createElement("div",{className:e.onboardingPanelNumber},w().createElement("span",{className:e.onboardingPanelNumberSpan},"1")),w().createElement("h3",{className:e.onboardingPanelHeader},"Add Profiling to Your Application"),w().createElement("p",{className:e.onboardingPanelDescription},"Use"," ",w().createElement(he,{href:"https://grafana.com/docs/pyroscope/latest/configure-client/grafana-alloy/"},"Grafana Alloy")," ","or"," ",w().createElement(he,{href:"https://grafana.com/docs/pyroscope/next/configure-client/language-sdks/"},"Pyroscope SDKs")," ","to push profiles from your applications to Grafana Cloud.")),w().createElement("div",{className:e.onboardingPanel},w().createElement("div",{className:(0,r.cx)(e.onboardingPanelNumber,e.color2)},w().createElement("span",{className:e.onboardingPanelNumberSpan},"2")),w().createElement("h3",{className:e.onboardingPanelHeader},"Configure Your Applications"),w().createElement("p",{className:e.onboardingPanelDescription},"Go to ",w().createElement(he,{href:t.settingsUrl},"Grafana Cloud Stack settings")," to find your Grafana Cloud Credentials.")),w().createElement("div",{className:e.onboardingPanel},w().createElement("div",{className:(0,r.cx)(e.onboardingPanelNumber,e.color3)},w().createElement("span",{className:e.onboardingPanelNumberSpan},"3")),w().createElement("h3",{className:e.onboardingPanelHeader},"Start Getting Performance Insights"),w().createElement("p",{className:e.onboardingPanelDescription},"Once you're done with initial setup, refresh this page to see your profiling data."))):w().createElement(w().Fragment,null,w().createElement("div",{className:e.onboardingPanel},w().createElement("div",{className:e.onboardingPanelNumber},w().createElement("span",{className:e.onboardingPanelNumberSpan},"1")),w().createElement("h3",{className:e.onboardingPanelHeader},"Set Up Your Pyroscope Server"),w().createElement("p",{className:e.onboardingPanelDescription},"Install ",w().createElement(he,{href:"https://grafana.com/docs/pyroscope/latest/"},"Pyroscope Server")," on your infrastructure. Or if you want to use a hosted service, go to"," ",w().createElement(he,{href:t.settingsUrl},"Grafana Cloud Stack settings")," to find your Grafana Cloud Credentials.")),w().createElement("div",{className:e.onboardingPanel},w().createElement("div",{className:(0,r.cx)(e.onboardingPanelNumber,e.color2)},w().createElement("span",{className:e.onboardingPanelNumberSpan},"2")),w().createElement("h3",{className:e.onboardingPanelHeader},"Configure Grafana"),w().createElement("p",{className:e.onboardingPanelDescription},"Add a new ",w().createElement(he,{href:"/connections/datasources/new"},"Pyroscope datasource"),". Use your Pyroscope server URL and appropriate security credentials if you use Grafana Cloud Profiles.")),w().createElement("div",{className:e.onboardingPanel},w().createElement("div",{className:(0,r.cx)(e.onboardingPanelNumber,e.color3)},w().createElement("span",{className:e.onboardingPanelNumberSpan},"3")),w().createElement("h3",{className:e.onboardingPanelHeader},"Add Profiling to Your Application"),w().createElement("p",{className:e.onboardingPanelDescription},"Use"," ",w().createElement(he,{href:"https://grafana.com/docs/pyroscope/latest/configure-client/grafana-alloy/"},"Grafana Alloy")," ","or"," ",w().createElement(he,{href:"https://grafana.com/docs/pyroscope/next/configure-client/language-sdks/"},"Pyroscope SDKs")," ","to push profiles from your applications to Grafana Cloud."))))),t.isCloud&&w().createElement("div",{"data-testid":"how-billing-works"},w().createElement("h3",null,"How Billing Works"),w().createElement("div",{className:e.onboardingRow},w().createElement("p",{className:e.onboardingParagraph},"Usage of Grafana Cloud Profiles is subject to"," ",w().createElement(he,{href:"https://grafana.com/pricing/"},"Grafana Cloud Pricing")," for Profiles.",w().createElement("br",null),"For additional information, read the announcement ",w().createElement(he,{href:"https://grafana.com/blog/2023/08/09/grafana-cloud-profiles-for-continuous-profiling/"},"blog post"),"."))))}const Pe=e=>({onboardingPage:r.css`
padding: 16px;
margin: 64px;
position: relative;
background-color: ${e.colors.background.primary};
`,closeButton:r.css`
position: absolute;
top: -30px;
opacity: 0.8;
right: -32px;
border: none;
border-radius: 50%;
width: 40px;
height: 40px;
line-height: 40px;
display: block;
padding: 0;
margin: 0;
font-size: 22px;
`}),xe={text:"Onboarding"};function Ce({onCloseModal:e}){const t=(0,i.useStyles2)(Pe);return w().createElement(a.PluginPage,{pageNav:xe,layout:o.PageLayoutType.Custom},w().createElement("div",{className:t.onboardingPage},w().createElement("button",{className:t.closeButton,onClick:e,title:"Close","data-testid":"close-onboarding-modal"},"×"),w().createElement(Oe,null)))}function Te({children:e}){const{data:t,actions:n}=H();return t.shouldShowLoadingPage?w().createElement(me,null):t.shouldShowOnboardingPage?w().createElement(Ce,{onCloseModal:n.closeModal}):t.shouldShowNoDataSourceBanner?w().createElement(ge,null):w().createElement(w().Fragment,null,e)}var Ae=n(1159);function Ne({onClick:e}){const t=e||(()=>history.back());return w().createElement(i.Button,{variant:"secondary",onClick:t,"aria-label":"Back to Profiles Drilldown"},"Back to Profiles Drilldown")}const ke=m.EXPLORE.slice(1);function je(){const{pathname:e}=new URL(window.location.toString());return e.split("/").pop()||""}function Re(){const e={appRelease:a.config.apps[d].version,appVersion:f,page:je()};return e.page===ke&&(e.view=new URLSearchParams(window.location.search).get("explorationType")||""),e}function Ie(e,t){(0,a.reportInteraction)(e,{props:t,meta:Re()})}function De(e){const[t,n]=(0,S.useState)(!1);(0,S.useEffect)((()=>{t||(n(!0),Ie("g_pyroscope_app_page_initialized",{page:e}))}),[e,t])}const _e=e=>({container:r.css`
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: ${e.spacing(1)};
width: 100%;
`,column:r.css`
width: 50%;
`});function Le({left:e,right:t}){const n=(0,i.useStyles2)(_e);return w().createElement("div",{className:n.container},w().createElement("div",{className:n.column},e),w().createElement("div",{className:n.column},t))}function Fe(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,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}function $e(e,t){const n=t.reduce(((e,t,n)=>Be(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){Fe(e,t,n[t])}))}return e}({},e),{[`info${n+1}`]:t})),{handheldBy:"displayError"});j.error(e,n),(0,a.getAppEvents)().publish({type:o.AppEvents.alertError.name,payload:t})}function Me(e){j.warn(e),(0,a.getAppEvents)().publish({type:o.AppEvents.alertWarning.name,payload:e})}function Ve(e){(0,a.getAppEvents)().publish({type:o.AppEvents.alertSuccess.name,payload:e})}function Ue(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function Ge(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){Ue(a,r,o,i,s,"next",e)}function s(e){Ue(a,r,o,i,s,"throw",e)}i(void 0)}))}}const qe=new class extends q{get(e,t){var n=this;return Ge((function*(){const r=yield n.fetch("/adhocprofiles.v1.AdHocProfileService/Get",{method:"POST",body:JSON.stringify({id:e,profile_type:t})}),o=yield r.json();return{id:o.id,name:o.name,profileTypes:o.profileTypes,profile:JSON.parse(o.flamebearerProfile)}}))()}uploadSingle(e){var t=this;return Ge((function*(){const n=yield t._readProfileFile(e),r=yield t.fetch("/adhocprofiles.v1.AdHocProfileService/Upload",{method:"POST",body:JSON.stringify({name:e.name,profile:n})}),o=yield r.json();return{id:o.id,name:e.name,profileTypes:o.profileTypes,profile:JSON.parse(o.flamebearerProfile)}}))()}uploadDiff(){return Ge((function*(){return{id:"?",name:"??",profileTypes:[],profile:null}}))()}_readProfileFile(e){return Ge((function*(){return new Promise(((t,n)=>{const r=new FileReader;r.addEventListener("load",(()=>{try{t(function(e){const[,t]=e.split(";base64,");if(!t)throw new Error("No content after stripping the base64 prefix.");if(e===t)throw new Error("No base64 prefix?!");return t}(r.result))}catch(e){n(e)}})),r.addEventListener("error",(()=>{n(new Error(`Error while reading file "${e.name}"!`))})),r.readAsDataURL(e)}))}))()}};function Ke(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function ze(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){Ke(a,r,o,i,s,"next",e)}function s(e){Ke(a,r,o,i,s,"throw",e)}i(void 0)}))}}function We(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function He(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){We(e,t,n[t])}))}return e}function Ye(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 Ze={id:"",name:"",profileTypes:[],profile:null};function Xe(){const[e,t]=(0,S.useState)(!1),[n,r]=(0,S.useState)(Ze);(0,S.useEffect)((()=>()=>{qe.abort()}),[]);const o=(0,S.useCallback)((()=>{qe.abort(),t(!1),r(Ze)}),[]),a=(0,S.useCallback)(function(){var e=ze((function*(e){o();try{t(!0);const n=yield qe.uploadSingle(e);r(n)}catch(e){r(Ze),qe.isAbortError(e)||$e(e,["Error while uploading profile!",e.message])}t(!1)}));return function(t){return e.apply(this,arguments)}}(),[o]),i=(0,S.useCallback)(function(){var e=ze((function*(e){const o=e.value;if(o&&n.id&&n.profileTypes.includes(o)){qe.abort(),t(!1),r((e=>Ye(He({},e),{profile:null}))),t(!0);try{const e=yield qe.get(n.id,o);r((t=>Ye(He({},t),{profile:e.profile})))}catch(e){qe.isAbortError(e)||$e(e,["Error while fetching profile!",e.message])}t(!1)}}));return function(t){return e.apply(this,arguments)}}(),[n.id,n.profileTypes]);return{processFile:a,profileTypes:n.profileTypes,selectProfileType:i,profile:n.profile,removeFile:o,isLoading:e}}function Je(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Qe(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){Je(e,t,n[t])}))}return e}function et(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 tt={accept:{"application/gzip":[".gz"],"application/json":[".json"],"application/proto":[".pb",".pprof"]},multiple:!1,onError(e){$e(e,["Error while uploading file!",e.toString()])}};function nt({onFileDropped:e,onFileRemove:t}){const n=(0,S.useCallback)((function(t){e(t[0])}),[e]);return w().createElement(i.FileDropzone,{options:et(Qe({},tt),{onDropAccepted:n}),onFileRemove:t})}var rt=n(6248),ot=(n(8727),n(2249)),at=n.n(ot);function it(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}const st=new class extends G{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 a=n.apply(e,t);function i(e){it(a,r,o,i,s,"next",e)}function s(e){it(a,r,o,i,s,"throw",e)}i(void 0)}))})()}constructor(){super("https://flamegraph.com/api",{"content-type":"application/json"})}};var lt=function(e){return e.BASELINE="baseline",e.COMPARISON="comparison",e}({});const ct=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 ut(e){const t=ct.formatToParts(e).reduce(((e,{type:t,value:n})=>(e[t]=n,e)),{});return`${t.year}-${t.month}-${t.day}_${t.hour}${t.minute}`}function dt(e){const t=new Date(Math.round(1e3*e.from.unix())),n=new Date(Math.round(1e3*e.to.unix()));return`${ut(t)}-to-${ut(n)}`}function pt(e){const[t,n]=e===lt.BASELINE?["diffFrom","diffTo"]:["diffFrom-2","diffTo-2"],r=new URLSearchParams(window.location.search),a=r.get(t),i=r.get(n);return{raw:{from:a,to:i},from:(0,o.dateTimeParse)(a),to:(0,o.dateTimeParse)(i)}}function mt(e){const t=["baseline",dt(pt(lt.BASELINE)),"comparison",dt(pt(lt.COMPARISON))];return e?[e,...t].join("_"):["flamegraph",...t].join("_")}function ft(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function ht({profile:e,enableFlameGraphDotComExport:t}){const n=function(){var t,n=(t=function*(){Ie("g_pyroscope_app_export_profile",{format:"flamegraph.com"});const t=mt(e.metadata.appName);let n;try{n=yield st.upload(t,e)}catch(e){return void $e(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 a=t.apply(e,n);function i(e){ft(a,r,o,i,s,"next",e)}function s(e){ft(a,r,o,i,s,"throw",e)}i(void 0)}))});return function(){return n.apply(this,arguments)}}();return{data:{shouldDisplayFlamegraphDotCom:Boolean(t)},actions:{downloadPng:()=>{Ie("g_pyroscope_app_export_profile",{format:"png"});const t=`${mt(e.metadata.appName)}.png`;document.querySelector('canvas[data-testid="flameGraph"]').toBlob((e=>{if(e)at()(e,t);else{const e=new Error("No Blob, the image cannot be created.");$e(e,["Failed to export to png!",e.message])}}),"image/png")},downloadJson:()=>{Ie("g_pyroscope_app_export_profile",{format:"json"});const t=`${mt(e.metadata.appName)}.json`,n=`data:text/json;charset=utf-8,${encodeURIComponent(JSON.stringify(e))}`;try{at()(n,t)}catch(e){return void $e(e,["Failed to export to JSON!",e.message])}},uploadToFlamegraphDotCom:n}}}function gt(e){const{actions:t}=ht(e);return w().createElement(i.Menu,null,w().createElement(i.Menu.Item,{label:"png",onClick:t.downloadPng}),w().createElement(i.Menu.Item,{label:"json",onClick:t.downloadJson}))}function bt(e){const{profile:t,enableFlameGraphDotComExport:n}=e;return w().createElement(i.Dropdown,{overlay:w().createElement(gt,{profile:t,enableFlameGraphDotComExport:n})},w().createElement(i.Button,{icon:"download-alt",size:"sm",variant:"secondary",fill:"outline","aria-label":"Export profile data",tooltip:"Export profile data"}))}const yt=(0,S.memo)(bt);function vt(e,t,n){const r=[],o=n?7:4;for(let a=0;a<e.length;a+=o)r.push({level:0,label:n?t[e[a+6]]:t[e[a+3]],offset:e[a],val:e[a+1],self:e[a+2],selfRight:n?e[a+5]:0,valRight:n?e[a+4]:0,valTotal:n?e[a+1]+e[a+4]:e[a+1],offsetRight:n?e[a+3]:0,offsetTotal:n?e[a]+e[a+3]:e[a],children:[]});return r}function Et({profile:e,diff:t,vertical:n,enableFlameGraphDotComExport:r,collapsedFlamegraphs:a,getExtraContextMenuButtons:s,showAnalyzeWithAssistant:l}){const{isLight:c}=(0,i.useTheme2)(),u=(0,S.useMemo)((()=>function(e,t,n,r){if(!e.length)return;const a=[];for(let n=0;n<e.length;n++){a[n]=[];for(const o of vt(e[n],t,r))if(o.level=n,a[n].push(o),n>0){const e=a[n].slice(0,-1).reduce(((e,t)=>t.offsetTotal+t.valTotal+e),0)+o.offsetTotal,t=a[n-1];let r=0;for(const n of t){const t=r+n.offsetTotal,a=t+n.valTotal;if(t<=e&&a>e){n.children.push(o);break}r+=n.offsetTotal+n.valTotal}}}const i=[a[0][0]],s=[],l=[],c=[],u=[],d=[],p=[];for(;i.length;){const e=i.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),i.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:o.FieldType.string},{name:"self",values:c,config:{unit:m}},{name:"value",values:u,config:{unit:m}}];r&&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,o.createDataFrame)(h)}(e.flamebearer.levels,e.flamebearer.names,e.metadata.units,Boolean(t))),[e,t]);return w().createElement(rt.Ay,{data:u,disableCollapsing:!a,extraHeaderElements:w().createElement(yt,{profile:e,enableFlameGraphDotComExport:r}),vertical:n,getTheme:()=>(0,o.createTheme)({colors:{mode:c?"light":"dark"}}),getExtraContextMenuButtons:s,keepFocusOnDataChange:!0,showAnalyzeWithAssistant:l})}const St=(0,S.memo)(Et),wt=e=>({flamegraph:r.css`
margin-top: ${e.spacing(2)};
`});function Ot({profile:e,diff:t}){const n=(0,i.useStyles2)(wt);return w().createElement("div",{className:n.flamegraph,"data-testid":"flamegraph"},w().createElement(St,{profile:e,diff:t}))}const Pt=e=>({selectorContainer:r.css`
display: flex;
justify-content: center;
margin-bottom: ${e.spacing(2)};
`});function xt({profileTypes:e,onChange:t}){const n=(0,i.useStyles2)(Pt),r=(0,S.useMemo)((()=>e.map((e=>({value:e,label:e})))),[e]),[o,a]=(0,S.useState)(),s=(0,S.useCallback)((e=>{a(e),t(e)}),[t]);return(0,S.useEffect)((()=>{a(r[0])}),[r]),w().createElement("div",{className:n.selectorContainer},w().createElement(i.InlineFieldRow,null,w().createElement(i.InlineField,{label:"Profile",disabled:!r.length,"data-testid":"profile-types-dropdown"},w().createElement(i.Select,{key:null==o?void 0:o.value,value:o,options:r,onChange:s,width:16}))))}const Ct=e=>({spinner:r.css`
text-align: center;
margin-top: ${e.spacing(2)};
`});function Tt(){const e=(0,i.useStyles2)(Ct);return w().createElement("div",{className:e.spinner},w().createElement(i.Spinner,{size:36}))}function At(){const{processFile:e,profileTypes:t,selectProfileType:n,profile:r,removeFile:o,isLoading:a}=Xe();return w().createElement("div",null,w().createElement(xt,{profileTypes:t,onChange:e=>{Ie("g_pyroscope_app_ad_hoc_profile_metric_selected"),n(e)}}),w().createElement(nt,{onFileDropped:t=>{Ie("g_pyroscope_app_ad_hoc_file_dropped",{fileType:t.type}),e(t)},onFileRemove:()=>{Ie("g_pyroscope_app_ad_hoc_file_removed"),o()}}),a&&!r?w().createElement(Tt,null):null,r&&w().createElement(Ot,{profile:r}))}const Nt=(0,S.memo)(At);function kt(){return w().createElement(Le,{left:w().createElement(Nt,null),right:w().createElement(Nt,null)})}const jt=e=>({tabContent:r.css`
padding: ${e.spacing(2)};
margin: ${e.spacing(2)};
`});function Rt(){const e=(0,i.useStyles2)(jt),[t,n]=(0,S.useState)(0);return w().createElement("div",null,w().createElement(i.TabsBar,null,w().createElement(i.Tab,{label:" Single view",active:0===t,onChangeTab:()=>n(0)}),w().createElement(i.Tab,{label:" Comparison view",active:1===t,onChangeTab:()=>n(1)})),w().createElement(i.TabContent,{className:e.tabContent},0===t&&w().createElement(Nt,null),1===t&&w().createElement(kt,null)))}function It(){return De("ad_hoc"),w().createElement(w().Fragment,null,w().createElement(pe,{title:"Ad hoc view"}),w().createElement(Rt,null),w().createElement(Ne,null))}const Dt=e=>({loadingIcon:r.css`
color: ${e.colors.primary.main};
font-size: 48px;
margin-bottom: ${e.spacing(2)};
display: flex;
justify-content: center;
`,loadingMessage:r.css`
text-align: center;
font-size: ${e.typography.h4.fontSize};
margin-bottom: ${e.spacing(2)};
`,fullScreenModal:r.css`
width: 100vw !important;
height: 100vh !important;
max-width: none !important;
max-height: none !important;
margin: 0 !important;
top: 0 !important;
left: 0 !important;
right: 0 !important;
bottom: 0 !important;
`});function _t(){const e=(0,i.useStyles2)(Dt),[t,n]=(0,S.useState)(!0);return w().createElement(i.Modal,{title:"GitHub Login",isOpen:t,onDismiss:()=>{n(!1),window.close()},closeOnEscape:!0,closeOnBackdropClick:!0,className:e.fullScreenModal},w().createElement("div",{className:e.loadingMessage},w().createElement("div",{className:e.loadingIcon},w().createElement(i.Spinner,{size:"xl"})),w().createElement("p",null,"Logging in to GitHub...")))}var Lt=n(9612);function Ft(){history.pushState(null,"")}var Bt,$t,Mt,Vt=n(3241);class Ut extends o.BusEventWithPayload{}Mt="timeseries-data-received",($t="type")in(Bt=Ut)?Object.defineProperty(Bt,$t,{value:Mt,enumerable:!0,configurable:!0,writable:!0}):Bt[$t]=Mt;var Gt=function(e){return e.partial="partial",e["attribute-operator-value"]="attribute-operator-value",e["attribute-operator"]="attribute-operator",e}({}),qt=function(e){return e["="]="=",e["!="]="!=",e.in="in",e["not-in"]="not-in",e["is-empty"]="is-empty",e["=~"]="=~",e["!~"]="!~",e}({}),Kt=function(e){return e.attribute="attribute",e.operator="operator",e.value="value",e}({}),zt=function(e){return e.attribute="attribute",e.operator="operator",e.value="value",e}({});var Wt=n(1015),Ht=n(7268),Yt=n(8987),Zt=n(9221);class Xt extends G{constructor(e){var t;const{dataSourceUid:n}=e;let{appSubUrl:r="",bootData:o}=a.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 Jt(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function Qt(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){Jt(a,r,o,i,s,"next",e)}function s(e){Jt(a,r,o,i,s,"throw",e)}i(void 0)}))}}class en extends Xt{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 Qt((function*(){return r._post("/querier.v1.QuerierService/LabelNames",{matchers:en.queryToMatchers(e),start:t,end:n}).then((e=>e.json()))}))()}fetchLabelValues(e,t,n,r){var o=this;return Qt((function*(){return o._post("/querier.v1.QuerierService/LabelValues",{name:e,matchers:en.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 tn{static buildCacheKey(e){let t="";for(const n of e)t+=String(n);return t}get(e){return this.store.get(tn.buildCacheKey(e))}set(e,t){this.store.set(tn.buildCacheKey(e),t)}delete(e){this.store.delete(tn.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 nn(e,t){if(!e)throw new Error(t)}function rn(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class on{setApiClient(e){this.apiClient=e}setCacheClient(e){this.cacheClient=e}cancel(e){this.apiClient.abort(e)}constructor(e){rn(this,"apiClient",void 0),rn(this,"cacheClient",void 0),this.apiClient=e.apiClient,this.cacheClient=null==e?void 0:e.cacheClient}}function an(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function sn(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){an(a,r,o,i,s,"next",e)}function s(e){an(a,r,o,i,s,"throw",e)}i(void 0)}))}}class ln extends q{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 sn((function*(){return r._post("/querier.v1.QuerierService/LabelNames",{matchers:ln.queryToMatchers(e),start:t,end:n}).then((e=>e.json()))}))()}fetchLabelValues(e,t,n,r){var o=this;return sn((function*(){return o._post("/querier.v1.QuerierService/LabelValues",{name:e,matchers:ln.queryToMatchers(t),start:n,end:r}).then((e=>e.json()))}))()}_post(e,t){return super.fetch(e,{method:"POST",body:JSON.stringify(t)})}}function cn(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function un(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){cn(a,r,o,i,s,"next",e)}function s(e){cn(a,r,o,i,s,"throw",e)}i(void 0)}))}}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}class pn extends on{static parseLabelsResponse(e){if(!Array.isArray(e.names))return[];return Array.from(new Set(e.names.filter(pn.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){nn(Boolean(e),'Missing "query" parameter!'),nn(t>0&&n>0&&n>t,"Invalid timerange!")}listLabels({query:e,from:t,to:n}){var r=this;return un((function*(){pn.assertParams(e,t,n);const o=[r.apiClient.baseUrl,e,t,n],a=r.cacheClient.get(o);if(a){const e=yield a,t=pn.parseLabelsResponse(e);return t.length||r.cacheClient.delete(o),t}const i=r.apiClient.fetchLabels(e,t,n);r.cacheClient.set(o,i);try{const e=yield i;return pn.parseLabelsResponse(e)}catch(e){throw r.cacheClient.delete(o),e}}))()}listLabelValues({label:e,query:t,from:n,to:r}){var o=this;return un((function*(){pn.assertParams(t,n,r),nn(Boolean(e),"Missing label value!");const a=[o.apiClient.baseUrl,e,t,n,r],i=o.cacheClient.get(a);if(i){const e=yield i,t=pn.parseLabelsResponse(e);return t.length||o.cacheClient.delete(a),t}const s=o.apiClient.fetchLabelValues(e,t,n,r);o.cacheClient.set(a,s);try{const e=yield s;return pn.parseLabelValuesResponse(e)}catch(e){throw o.cacheClient.delete(a),e}}))()}constructor(e){super({apiClient:e.apiClient}),dn(this,"cacheClient",void 0),this.cacheClient=e.cacheClient}}dn(pn,"isNotMetaLabelOrServiceName",(e=>!/^(__.+__|service_name)$/.test(e)));const mn=new pn({apiClient:new ln,cacheClient:new tn});function fn(e,t){const n=e.filter((({type:e})=>e!==Gt.partial)),r=t.filter((({type:e})=>e!==Gt.partial));return n.length===r.length&&n.every((e=>r.find((({type:t,attribute:n,operator:r,value:o})=>{var a,i;return t===e.type&&n.value===e.attribute.value&&(null==r?void 0:r.value)===(null===(a=e.operator)||void 0===a?void 0:a.value)&&(null==o?void 0:o.value)===(null===(i=e.value)||void 0===i?void 0:i.value)}))))}function hn(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const gn={type:Gt["attribute-operator"],operator:{value:qt["is-empty"],label:"is empty"},value:{value:qt["is-empty"],label:""}},bn=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){hn(e,t,n[t])}))}return e}({},e,gn);function yn(e,t){const n=t.filter((({type:e})=>e!==Gt.partial)).map((e=>{const{attribute:t,operator:n,value:r}=e;switch(n.value){case qt.in:return`${t.value}=~"${r.value}"`;case qt["not-in"]:return`${t.value}!~"${r.value}"`;case qt["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 vn=e=>e.at(-1)||null,En=e=>e===qt.in||e===qt["not-in"],Sn=e=>(nn(Boolean(e),"The filter is falsy!"),e.type===Gt.partial);function wn(e,t){return e!==t&&(t!==qt["is-empty"]&&([qt["=~"],qt["!~"],qt.in,qt["not-in"],qt["is-empty"]].includes(e)||[qt["=~"],qt["!~"],qt.in,qt["not-in"]].includes(t)))}function On(e,t){nn(void 0!==e.operator,"No operator for the filter under edition!");return wn(e.operator.value,t)}function Pn(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function xn(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 Cn=e=>{const t=e.matchAll(/(\w+)(=|!=|=~|!~)"([^"]*)"/g);return Array.from(t).map((([,e,t,n])=>[e,t,n]))},Tn=/.+:[^{]+\{(.+)\}$/,An=/.*(\^|\$|\*|\+|\{|\}|\?).*/;function Nn(e){if(!e)return[];const t=e.match(Tn);if(!t)return[];return Cn(t[1]).filter((([e])=>"service_name"!==e)).map((([e,t,n])=>{const r={id:(0,Yt.Ak)(10),type:Gt["attribute-operator-value"],active:!0,attribute:{value:e,label:e},operator:{value:t,label:t},value:{value:n,label:n}};if(t===qt["="]&&""===n)return bn(r);return[qt["=~"],qt["!~"]].includes(t)&&!An.test(n)?xn(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){Pn(e,t,n[t])}))}return e}({},r),{operator:t===qt["=~"]?{value:qt.in,label:"in"}:{value:qt["not-in"],label:"not in"},value:{value:n,label:n.split("|").map((e=>e.trim())).join(", ")}}):r}))}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 jn(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 Rn=(e,t)=>e.map((e=>e.type!==Gt.partial?jn(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){kn(e,t,n[t])}))}return e}({},e),{active:t}):e));function In(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Dn(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){In(e,t,n[t])}))}return e}function _n(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 Ln(e,t){const n=fn(e,Nn(t.inputParams.query));return{filters:n?Rn(e,!0):e,query:yn(t.query,e),isQueryUpToDate:n}}const Fn={cancelAllLoad:()=>{mn.cancel("Discarded by user")},setFilterAttribute:(0,Zt.kp)(((e,t)=>{const n=[...e.filters,{id:(0,Yt.Ak)(10),type:Gt.partial,active:!1,attribute:t.data}];return _n(Dn({},e),{filters:n,isQueryUpToDate:fn(n,Nn(e.inputParams.query))})})),editFilterAttribute:(0,Zt.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?_n(Dn({},e),{attribute:t.data,operator:void 0,value:void 0}):e));return _n(Dn({},e),{filters:r,isQueryUpToDate:fn(r,Nn(e.inputParams.query)),edition:null})})),setFilterOperator:(0,Zt.kp)(((e,t)=>{const n=e.filters.map((e=>{if(!Sn(e))return e;const n=t.data;return n.value===qt["is-empty"]?bn(e):_n(Dn({},e),{operator:n,value:void 0})}));return Dn({},e,Ln(n,e))})),editFilterOperator:(0,Zt.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 a=e.filters.map((t=>{const a=t.operator.value;return t.id!==n||a===r.value?t:r.value===qt["is-empty"]?bn(_n(Dn({},t),{active:!1})):(a===qt["is-empty"]&&(t.value={value:"(no value)",label:"(no value)"}),!Sn(t)&&wn(a,r.value)&&(o=_n(Dn({},e.edition),{part:Kt.value})),_n(Dn({},t),{operator:r,value:En(a)&&!En(r.value)&&t.value?{value:t.value.value.split("|").shift(),label:t.value.label.split(", ").shift()}:t.value,active:!1}))}));return _n(Dn({},e,Ln(a,e)),{edition:o})})),setFilterValue:(0,Zt.kp)(((e,t)=>{const n=e.filters.map((e=>Sn(e)?_n(Dn({},e),{type:Gt["attribute-operator-value"],active:!1,value:t.data}):e));return Dn({},e,Ln(n,e))})),editFilterValue:(0,Zt.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?_n(Dn({},e),{type:Gt["attribute-operator-value"],active:!1,value:t.data}):e));return _n(Dn({},e,Ln(r,e)),{edition:null})})),removeFilter:(0,Zt.kp)(((e,t)=>{const n=t.data,r=Rn(e.filters.filter((({id:e})=>e!==n)),!1);return Dn({},e,Ln(r,e))})),removeLastFilter:(0,Zt.kp)((e=>{const{filters:t}=e,n=vn(t);if(!n)return e;if(Sn(n)&&n.operator){const r=t.slice(0,t.length-1).concat(_n(Dn({},n),{operator:void 0}));return _n(Dn({},e),{filters:r,isQueryUpToDate:!0})}const r=t.slice(0,t.length-1).map((e=>_n(Dn({},e),{active:!1})));return Dn({},e,Ln(r,e))})),setEdition:(0,Zt.kp)({edition:(e,t)=>t.data}),changeInputParams:(0,Zt.kp)(((e,t)=>(t.data.dataSourceUid&&mn.setApiClient(new en({dataSourceUid:t.data.dataSourceUid})),{inputParams:t.data,query:t.data.query,filters:Nn(t.data.query),isQueryUpToDate:!0}))),activateFilters:(0,Zt.kp)((e=>Dn({},e,Ln(e.filters,e))))};function Bn(e){const{edition:t,filters:n}=e;nn(null!==t,'"edition" is null!');const r=n.find((({id:e})=>e===t.filterId));return nn(void 0!==r,"Cannot find the filter under edition!"),r}const $n={shouldSuggestAttributes:e=>{const t=vn(e.filters);return!t||!Sn(t)},shouldSuggestOperators:e=>{var t;return!(null===(t=vn(e.filters))||void 0===t?void 0:t.operator)},shouldSuggestValues:e=>{const t=vn(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&&On(Bn(e),t.data.value),shouldNotSuggestValuesAfterOperatorEdition:(e,t)=>!!e.edition&&!On(Bn(e),t.data.value),hasPartialFilter:e=>{const t=vn(e.filters);return Boolean(t&&Sn(t))},shouldEditAttribute:(e,t)=>t.data.part===Kt.attribute,shouldEditOperator:(e,t)=>t.data.part===Kt.operator,shouldEditValue:(e,t)=>t.data.part===Kt.value};function Mn(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}const Vn=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 a=e.apply(t,n);function i(e){Mn(a,r,o,i,s,"next",e)}function s(e){Mn(a,r,o,i,s,"throw",e)}i(void 0)}))})();var e}},Un=e=>e.startsWith("__");function Gn(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function qn(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){Gn(a,r,o,i,s,"next",e)}function s(e){Gn(a,r,o,i,s,"throw",e)}i(void 0)}))}}function Kn(e,t){if(e instanceof DOMException&&"AbortError"===e.name)return[];throw j.error(e,{info:t}),e}const zn={fetchLabels:function(){var e=qn((function*(e){const{from:t,to:n}=e.inputParams;try{const r=yield mn.listLabels({query:e.query,from:t,to:n}),o=[],a=[];return r.forEach((e=>{Un(e.value)?a.push(e):o.push(e)})),[...o,...a]}catch(e){return Kn(e,"Error while fetching labels!")}}));return function(t){return e.apply(this,arguments)}}(),fetchOperators:qn((function*(){try{return yield Vn.list()}catch(e){return Kn(e,"Error while fetching operators!")}})),fetchLabelValues:function(){var e=qn((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=yn(n,o)}else if(t=vn(e.filters),(null==t?void 0:t.type)!==Gt.partial)throw new Error("Impossible to load label values: no partial filter found!");if(o.disabled)return[];const a=t.attribute.value,{from:i,to:s}=e.inputParams;return yield mn.listLabelValues({label:a,query:n,from:i,to:s})}catch(e){return Kn(e,"Error while fetching label values!")}}));return function(t){return e.apply(this,arguments)}}()},Wn={always:[{cond:"shouldSuggestOperators",target:"loadOperators"},{cond:"shouldSuggestValues",target:"loadLabelValues"},{target:"idle"}]},Hn={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."},Yn=e=>e===qt["=~"]||e===qt["!~"];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 Xn(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 Jn={entry:["cancelAllLoad",(0,Zt.kp)({suggestions:e=>{let t=Hn.FILTER_ADD,n=!1;const r=vn(e.filters);return r&&Sn(r)&&(r.operator?(n=Yn(r.operator.value),t=En(r.operator.value)?Hn.SELECT_VALUES:n?Hn.TYPE_VALUE:Hn.SELECT_VALUE):t=Hn.SELECT_OPERATOR),Xn(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){Zn(e,t,n[t])}))}return e}({},gr.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 Qn(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){Qn(e,t,n[t])}))}return e}function tr(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 nr={entry:(0,Zt.kp)({suggestions:()=>tr(er({},gr.suggestions),{isVisible:!0,isLoading:!0})}),invoke:{id:"fetchLabels",src:"fetchLabels",onDone:{target:"displayLabels",actions:(0,Zt.kp)({suggestions:(e,t)=>tr(er({},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,Zt.kp)({suggestions:(e,t)=>tr(er({},e.suggestions),{isLoading:!1,error:t.data})})}},on:{DISCARD_SUGGESTIONS:"idle"}},rr={entry:(0,Zt.kp)({suggestions:e=>tr(er({},e.suggestions),{type:zt.attribute,isVisible:!0,placeholder:Hn.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 or(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ar(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){or(e,t,n[t])}))}return e}function ir(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 sr={entry:(0,Zt.kp)({suggestions:e=>{const t=e.edition?Bn(e):vn(e.filters);return nn(void 0!==typeof(null==t?void 0:t.operator),"No operator for the target filter!"),ir(ar({},gr.suggestions),{disabled:["=~","!~"].includes(t.operator.value)||Un(t.attribute.value),isVisible:!0,isLoading:!0})}}),invoke:{id:"fetchLabelValues",src:"fetchLabelValues",onDone:{target:"displayLabelValues",actions:(0,Zt.kp)({suggestions:(e,t)=>ir(ar({},e.suggestions),{items:t.data,isLoading:!1})})},onError:{target:"displayLabelValues",actions:(0,Zt.kp)({suggestions:(e,t)=>ir(ar({},e.suggestions),{items:[],isLoading:!1,error:t.data})})}},on:{DISCARD_SUGGESTIONS:"idle"}},lr={entry:(0,Zt.kp)({suggestions:e=>{const t=e.edition?Bn(e):vn(e.filters);nn(void 0!==typeof(null==t?void 0:t.operator),"No operator for the target filter!");const n=t.operator.value,r=Yn(n)||e.suggestions.disabled,o=En(n);let a,i;return a=r?Hn.TYPE_VALUE:o?Hn.SELECT_VALUES:Hn.SELECT_VALUE,i=e.suggestions.error?Hn.ERROR_LOAD:e.suggestions.disabled?Hn.SUGGESTIONS_DISABLED:Hn.SUGGESTIONS_NONE,ir(ar({},e.suggestions),{type:zt.value,isVisible:!0,placeholder:a,noOptionsMessage:i,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 cr(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){cr(e,t,n[t])}))}return e}function dr(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 pr={entry:(0,Zt.kp)({suggestions:()=>dr(ur({},gr.suggestions),{isVisible:!0,isLoading:!0})}),invoke:{id:"fetchOperators",src:"fetchOperators",onDone:{target:"displayOperators",actions:(0,Zt.kp)({suggestions:(e,t)=>dr(ur({},e.suggestions),{items:t.data,isLoading:!1})})},onError:{target:"displayOperators",actions:(0,Zt.kp)({suggestions:(e,t)=>dr(ur({},e.suggestions),{items:[],isLoading:!1,error:t.data})})}},on:{DISCARD_SUGGESTIONS:"idle"}},mr={entry:(0,Zt.kp)({suggestions:e=>dr(ur({},e.suggestions),{type:zt.operator,isVisible:!0,placeholder:Hn.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 fr(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function hr(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 gr=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}}),br=e=>({id:"query-builder",initial:"idle",context:e,predictableActionArguments:!0,states:{idle:Jn,loadLabels:nr,displayLabels:rr,loadOperators:pr,displayOperators:mr,loadLabelValues:sr,displayLabelValues:lr,autoSuggestProxy:Wn}}),yr={guards:$n,services:zn,actions:Fn};function vr(e){const{query:t}=e,n=hr(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){fr(e,t,n[t])}))}return e}({},gr),{inputParams:e,query:t,filters:Nn(t)}),r=(0,Wt.O)(br(n),yr);return{actor:(0,Ht.U4)(r),initialContext:n}}const Er=new Intl.Collator("en",{sensitivity:"case"}).compare,Sr=e=>(t,n)=>{const r=e.some((e=>e.value===t.value)),o=e.some((e=>e.value===n.value));return r&&o?Er(t.value,n.value):o?1:r?-1:0};function wr({selection:e,suggestions:t,onCloseMenu:n}){const r=(0,i.useStyles2)(Or),o=(0,S.useMemo)((()=>{const t=e.value.split("|"),n=e.label.split(", ");return t.map(((e,t)=>({value:e,label:n[t]})))}),[e]),[a,s]=(0,S.useState)(o),l=(0,S.useMemo)((()=>t.items.sort(Sr(a))),[t.items]),c=(0,S.useCallback)((e=>{s(e.map((({value:e="",label:t=""})=>({value:e,label:t}))))}),[]),u=(0,S.useCallback)((()=>{n(a)}),[n,a]);return w().createElement(i.MultiSelect,{className:r.editionSelect,placeholder:t.placeholder,loadingMessage:Hn.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 Or=()=>({editionSelect:r.css`
position: absolute;
z-index: 1;
[aria-label='Remove'] svg {
display: none;
}
`});function Pr({placeholder:e,defaultValue:t,onFocus:n,onChange:o,onBlur:a}){const s=(0,i.useStyles2)(xr),l=(0,S.useRef)(null),[c,u]=(0,S.useState)(!1);return(0,S.useEffect)((()=>{l.current&&l.current.focus()}),[]),w().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 xr=()=>({edition:r.css`
position: absolute;
z-index: 1;
`}),Cr=()=>({editionSelect:r.css`
position: absolute;
z-index: 1;
min-width: 160px;
box-shadow: none;
& input:focus {
outline: none !important;
}
`});function Tr({selection:e,suggestions:t,onChange:n,onCloseMenu:r}){const o=(0,i.useStyles2)(Cr);return t.allowCustomValue?w().createElement(Pr,{defaultValue:e.value,placeholder:t.placeholder,onChange:n,onBlur:r}):w().createElement(i.Select,{className:o.editionSelect,placeholder:t.placeholder,loadingMessage:Hn.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 Ar=()=>{},Nr=({filter:e,onClick:t,onRemove:n})=>{const o=(0,i.useStyles2)(_r),{attribute:a,operator:s,active:l}=e,c=l?o.chiclet:(0,r.cx)(o.chiclet,o.inactiveChiclet);return w().createElement("div",{className:c,"aria-label":"Filter"},w().createElement(i.Tag,{"aria-label":"Filter label",className:o.chicletAttribute,name:a.label,onClick:Ar}),w().createElement(i.Tag,{"aria-label":"Filter operator",className:o.chicletOperator,name:s.label,onClick:(n,r)=>t(r,e,Kt.operator),tabIndex:0}),w().createElement(i.Tag,{"aria-label":"Remove filter",className:o.chicletRemoveButton,icon:"times",name:"",onClick:(t,r)=>n(r,e),tabIndex:0}))},kr=()=>{},jr=({filter:e,onClick:t,onRemove:n})=>{const o=(0,i.useStyles2)(_r),{attribute:a,operator:s,value:l,active:c}=e,u=c?o.chiclet:(0,r.cx)(o.chiclet,o.inactiveChiclet);return w().createElement("div",{className:u,"aria-label":"Filter"},w().createElement(i.Tag,{"aria-label":"Filter label",className:o.chicletAttribute,name:a.label,onClick:kr}),w().createElement(i.Tag,{"aria-label":"Filter operator",className:o.chicletOperator,name:s.label,onClick:(n,r)=>t(r,e,Kt.operator),tabIndex:0}),w().createElement(i.Tooltip,{content:l.label},w().createElement(i.Tag,{"aria-label":"Filter value",name:l.label,className:o.chicletValue,onClick:(n,r)=>t(r,e,Kt.value),tabIndex:0})),w().createElement(i.Tag,{"aria-label":"Remove filter",className:o.chicletRemoveButton,icon:"times",name:"",onClick:(t,r)=>n(r,e),tabIndex:0}))},Rr=({filter:e,onClick:t})=>{const n=(0,i.useStyles2)(_r),{attribute:o,operator:a}=e;return o||a?w().createElement("div",{className:(0,r.cx)(n.chiclet,n.partialChiclet),"aria-label":"Partial filter"},w().createElement(i.Tag,{colorIndex:9,name:o.label,title:`Edit "${o.label}"`,onClick:(n,r)=>t(r,e,Kt.attribute),tabIndex:0}),a&&w().createElement(i.Tag,{colorIndex:9,name:a.label,title:`Edit "${a.label}"`,className:n.chicletOperator,onClick:(n,r)=>t(r,e,Kt.operator),tabIndex:0})):null},Ir="rgb(61, 113, 217)",Dr="#4a4b52",_r=e=>({chiclet:r.css`
display: flex;
align-items: center;
border: 1px solid ${Ir};
border-radius: 2px;
& > button {
height: 30px;
background-color: ${e.colors.background.primary};
color: ${e.colors.text.maxContrast};
}
& > :first-child {
background-color: ${Ir};
color: ${"#fff"};
border-radius: 0;
&:hover {
cursor: not-allowed !important;
}
}
& > :last-child {
border-left: 1px solid ${Ir};
border-top-left-radius: 0;
border-bottom-left-radius: 0;
}
`,partialChiclet:r.css`
border-color: ${Dr};
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: ${Dr};
color: ${e.colors.text.maxContrast};
}
`,inactiveChiclet:r.css`
border-color: ${Dr};
& > button {
color: ${e.colors.text.maxContrast};
}
& > :first-child {
background-color: ${e.colors.background.secondary};
color: ${e.colors.text.maxContrast};
}
& > :last-child {
border-color: ${Dr};
}
`,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;
}
`}),Lr=({filter:e,onClick:t,onRemove:n})=>{switch(e.type){case Gt.partial:return w().createElement(Rr,{filter:e,onClick:t});case Gt["attribute-operator-value"]:return w().createElement(jr,{filter:e,onClick:t,onRemove:n});case Gt["attribute-operator"]:return w().createElement(Nr,{filter:e,onClick:t,onRemove:n});default:throw new TypeError(`Unsupported filter type "${e.type}" (${JSON.stringify(e)})!`)}},Fr=(0,S.memo)(Lr,((e,t)=>JSON.stringify(e.filter)===JSON.stringify(t.filter))),Br=()=>({chicletsList:r.css`
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 4px;
`,editChicletContainer:r.css`
position: relative;
`});function $r({filters:e,onClickChiclet:t,onRemoveChiclet:n,edition:r,suggestions:o,onChangeSingleSuggestion:a,onCloseSingleSuggestionsMenu:s,onCloseMultipleSuggestionsMenu:l}){const c=(0,i.useStyles2)(Br);return w().createElement("div",{className:c.chicletsList,"data-testid":"filtersList"},e.map((e=>w().createElement("div",{key:e.id,className:c.editChicletContainer},w().createElement(Fr,{filter:e,onClick:t,onRemove:n}),(null==r?void 0:r.filterId)===e.id?o.multiple?w().createElement(wr,{selection:e[r.part],suggestions:o,onCloseMenu:l}):w().createElement(Tr,{key:r.part,selection:e[r.part],suggestions:o,onChange:a,onCloseMenu:s}):null))))}const Mr=(0,S.memo)($r),Vr=()=>({select:r.css`
border-top-right-radius: 0;
border-bottom-right-radius: 0;
`});function Ur({suggestions:e,onFocus:t,onChange:n,onKeyDown:r,onCloseMenu:o}){const a=(0,i.useStyles2)(Vr),s=function(e){const[t,n]=(0,S.useState)(!1);return(0,S.useEffect)((()=>{!e||t?e!==t&&n(e):setTimeout((()=>n(!0)),0)}),[t,e]),t}(e.isVisible);return e.allowCustomValue?w().createElement(Pr,{placeholder:e.placeholder,onFocus:t,onChange:n,onBlur:o}):w().createElement(i.Select,{className:a.select,placeholder:e.placeholder,loadingMessage:Hn.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 Gr=()=>{};function qr(){const e=(0,i.useStyles2)(Vr);return w().createElement(i.Select,{disabled:!0,className:e.select,placeholder:Hn.FILTER_ADD,onChange:Gr})}function Kr({suggestions:e,onFocus:t,onKeyDown:n,onCloseMenu:r}){const o=(0,i.useStyles2)(zr),[a,s]=(0,S.useState)([]),l=(0,S.useCallback)((e=>{s(e.map((({value:e="",label:t=""})=>({value:e,label:t}))))}),[]),c=(0,S.useCallback)((e=>{n(e,a)}),[n,a]),u=(0,S.useCallback)((()=>{r(a)}),[r,a]);return w().createElement(i.MultiSelect,{className:o.select,placeholder:e.placeholder,loadingMessage:Hn.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 zr=()=>({select:r.css`
[aria-label='Remove'] svg {
display: none;
}
`}),Wr=()=>({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 Hr(e){const t=(0,i.useStyles2)(Wr),{actor:n,internalProps:o}=function({dataSourceUid:e,query:t,from:n,to:r,onChangeQuery:o}){const{actor:a,initialContext:i}=(0,S.useMemo)((()=>vr({query:t,from:n,to:r})),[]);(0,S.useEffect)((()=>{a.send({type:"CHANGE_INPUT_PARAMS",data:{dataSourceUid:e,query:t,from:n,to:r}})}),[a,e,t,n,r]);const[s,l]=(0,S.useState)(i);return(0,S.useEffect)((()=>(a.start(),a.subscribe((({event:e,context:t})=>{"EXECUTE_QUERY"===e.type&&o(t.query,t.filters),l(t)})),()=>{a.stop()})),[a]),{actor:a,internalProps:s}}(e),{filters:a,edition:s,isQueryUpToDate:l,suggestions:c}=o,{onClickChiclet:u,onRemoveChiclet:d}=function(e){const t=(0,S.useCallback)(((t,n,r)=>{e.send({type:"EDIT_FILTER",data:{filterId:n.id,part:r}})}),[e]),n=(0,S.useCallback)(((t,n)=>{e.send({type:"REMOVE_FILTER",data:n.id})}),[e]);return{onClickChiclet:t,onRemoveChiclet:n}}(n),{onFocus:p,onChangeSingleSuggestion:m,onSingleSelectKeyDown:f,onCloseSingleMenu:h,onMultipleSelectKeyDown:g,onCloseMultipleMenu:b}=function(e,t,n){const r=(0,S.useCallback)((()=>{e.send({type:"START_INPUT"})}),[e]),o=(0,S.useCallback)((t=>{const{value:n="",label:r=""}=t;e.send({type:"SELECT_SUGGESTION",data:{value:n,label:r}})}),[e]),a=(0,S.useCallback)((t=>{"Backspace"!==t.code||t.target.value||e.send({type:"REMOVE_LAST_FILTER"})}),[e]),i=(0,S.useCallback)((()=>{e.send({type:"DISCARD_SUGGESTIONS"})}),[e]),s=(0,S.useCallback)(((t,n)=>{"Backspace"!==t.code||t.target.value||n.length||e.send({type:"REMOVE_LAST_FILTER"})}),[e]),l=(0,S.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,S.useRef)();return(0,S.useEffect)((()=>{t.current=e})),t.current}(t.isVisible);return(0,S.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:a,onMultipleSelectKeyDown:s,onCloseSingleMenu:i,onCloseMultipleMenu:l}}(n,c,e.id),y=(0,S.useCallback)((()=>{n.send({type:"EXECUTE_QUERY"})}),[n]);return(0,S.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]),w().createElement("div",{id:e.id,className:(0,r.cx)(t.queryBuilder,e.className)},a.length>0?w().createElement(Mr,{filters:a,onClickChiclet:u,onRemoveChiclet:d,edition:s,suggestions:c,onChangeSingleSuggestion:m,onCloseSingleSuggestionsMenu:h,onCloseMultipleSuggestionsMenu:b}):null,w().createElement("div",{className:t.controls},s?w().createElement(qr,null):c.multiple?w().createElement(Kr,{suggestions:c,onFocus:p,onKeyDown:g,onCloseMenu:b}):w().createElement(Ur,{suggestions:c,onFocus:p,onChange:m,onKeyDown:f,onCloseMenu:h}),!e.autoExecute&&w().createElement(i.Button,{onClick:y,tooltip:l?"Nothing to execute, all filters applied":"Execute new query",className:t.executeButton,disabled:l},"Execute")))}const Yr=(0,S.memo)(Hr),Zr=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 Xr(e){if(Zr[e])return Zr[e];const[t="?",n="?"]=e?e.split(":"):[];return{id:e,description:"",type:n,group:t,unit:"short"}}var Jr=n(1269);const Qr=Object.freeze({type:"grafana-pyroscope-datasource",uid:"$dataSource"}),eo=Object.freeze({type:"grafana-pyroscope-series-datasource",uid:"grafana-pyroscope-series-datasource"}),to=Object.freeze({type:"grafana-pyroscope-favorites-datasource",uid:"grafana-pyroscope-favorites-datasource"}),no=Object.freeze({type:"grafana-pyroscope-labels-datasource",uid:"grafana-pyroscope-labels-datasource"});function ro(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function oo(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class ao extends Lt.fS{onActivate(){this.state.value||this.setState({value:ao.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,Jr.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 a=t.apply(e,n);function i(e){ro(a,r,o,i,s,"next",e)}function s(e){ro(a,r,o,i,s,"throw",e)}i(void 0)}))})()}static buildCascaderOptions(e){const t=new Map;for(const{value:n}of e){const e=Xr(n),{group:r,type:o}=e,a=t.get(r)||{value:r,label:r,items:[]},i=a.items||[];i.push({value:n,label:o}),a.items=i,t.set(r,a)}return Array.from(t.values()).sort(((e,t)=>Er(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){oo(e,t,n[t])}))}return e}({key:"profileMetricId",name:"profileMetricId",label:"Profile type",datasource:eo,query:ao.QUERY_DEFAULT,loading:!0,refresh:o.VariableRefresh.onTimeRangeChanged},e)),oo(this,"onSelect",(e=>{Ie("g_pyroscope_app_profile_metric_selected"),this.state.skipUrlSync||Ft(),this.changeValueTo(e)})),this.changeValueTo=this.changeValueTo.bind(this),this.addActivationHandler(this.onActivate.bind(this))}}oo(ao,"DEFAULT_VALUE","process_cpu:cpu:nanoseconds:cpu:nanoseconds"),oo(ao,"QUERY_DEFAULT","$dataSource and all profile metrics"),oo(ao,"QUERY_SERVICE_NAME_DEPENDENT","$dataSource and only $serviceName profile metrics"),oo(ao,"Component",(({model:e})=>{const t=(0,i.useStyles2)(io),{loading:n,value:r,options:o,error:a}=e.useState(),s=(0,S.useMemo)((()=>ao.buildCascaderOptions(o)),[o]);return a?w().createElement(i.Tooltip,{theme:"error",content:a.toString()},w().createElement(i.Icon,{className:t.iconError,name:"exclamation-triangle",size:"xl"})):w().createElement(i.Cascader,{key:(0,Yt.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 io=e=>({iconError:r.css`
height: 32px;
align-self: center;
color: ${e.colors.error.text};
`});function so(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function lo(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 Lt.fS{onActivate(){const{serviceName:e}=_.get(_.KEYS.PROFILES_EXPLORER)||{};e&&!this.state.value&&this.setState({value:e}),this.subscribeToState(((e,t)=>{if(e.value&&e.value!==t.value){const t=_.get(_.KEYS.PROFILES_EXPLORER)||{};t.serviceName=e.value,_.set(_.KEYS.PROFILES_EXPLORER,t)}}))}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,Jr.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 a=e.apply(t,n);function i(e){so(a,r,o,i,s,"next",e)}function s(e){so(a,r,o,i,s,"throw",e)}i(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){lo(e,t,n[t])}))}return e}({key:"serviceName",name:"serviceName",label:"Service",datasource:eo,query:co.QUERY_DEFAULT,loading:!0,refresh:o.VariableRefresh.onTimeRangeChanged},e)),lo(this,"selectNewValue",(e=>{Ie("g_pyroscope_app_service_name_selected"),this.state.skipUrlSync||Ft(),this.changeValueTo(e)})),this.addActivationHandler(this.onActivate.bind(this))}}lo(co,"QUERY_DEFAULT","$dataSource and all services"),lo(co,"QUERY_PROFILE_METRIC_DEPENDENT","$dataSource and only $profileMetricId services"),lo(co,"Component",(({model:e})=>{const t=(0,i.useStyles2)(uo),{loading:n,value:r,options:o,error:a}=e.useState(),s=(0,S.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 a=t[e],i=o;o=o?`${o}/${a}`:a;const s=e===t.length-1;if(!r.has(o)||s){const e={value:s?o:o+"/",label:a,items:s?void 0:[]};if(s||r.set(o,e),i){const t=r.get(i);t&&t.items&&t.items.push(e)}else n.push(e)}}}return n}(o.map((({label:e})=>e)))),[o]);return a?w().createElement(i.Tooltip,{theme:"error",content:a.toString()},w().createElement(i.Icon,{className:t.iconError,name:"exclamation-triangle",size:"xl"})):w().createElement(i.Cascader,{key:(0,Yt.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 uo=e=>({iconError:r.css`
height: 32px;
align-self: center;
color: ${e.colors.error.text};
`});function po(e,t){const{value:n}=Lt.jh.findByKeyAndType(e,"serviceName",co).useState(),{value:r}=Lt.jh.findByKeyAndType(e,"profileMetricId",ao).useState(),{filterExpression:o}=Lt.jh.findByKeyAndType(e,t,xo).useState();return(0,S.useMemo)((()=>`${r}{service_name="${n}",${o}}`),[o,r,n])}class mo extends Lt.mI{onActivate(){this.setState({skipUrlSync:!1}),this.subscribeToState(((e,t)=>{if(e.value&&e.value!==t.value){const t=_.get(_.KEYS.PROFILES_EXPLORER)||{};t.dataSource=e.value,_.set(_.KEYS.PROFILES_EXPLORER,t)}}))}constructor(){super({pluginId:"grafana-pyroscope-datasource",key:"dataSource",name:"dataSource",label:"Data source",skipUrlSync:!0,value:q.selectDefaultDataSource().uid}),this.addActivationHandler(this.onActivate.bind(this))}}function fo(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ho(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){fo(e,t,n[t])}))}return e}function go(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 bo=e=>{let t=e.operator.value;return e.operator.value===qt.in?t=qt["=~"]:e.operator.value===qt["not-in"]&&(t=qt["!~"]),{key:e.attribute.value,operator:t,value:e.value.value}};function yo(e,t){let n;const r=e.filter((e=>e.key!==t||(n=e,!1)));return{found:n,filtersWithoutFound:r}}const vo=(e,t)=>[...e,t];function Eo(e,t){const{found:n,filtersWithoutFound:r}=yo(e,t.key);if(!n)return vo(e,go(ho({},t),{operator:"=~"}));if(["!~","!="].includes(n.operator))return vo(r,go(ho({},t),{operator:"=~"}));const o=new Set(n.value.split("|"));return"=~"===n.operator?vo(r,go(ho({},n),{value:Array.from(o.add(t.value)).join("|")})):n.value===t.value?e:vo(r,go(ho({},t),{operator:"=~",value:Array.from(o.add(t.value)).join("|")}))}function So(e,t){const{found:n,filtersWithoutFound:r}=yo(e,t.key);if(!n)return vo(e,go(ho({},t),{operator:"!~"}));if(["=~","="].includes(n.operator))return vo(r,go(ho({},t),{operator:"!~"}));const o=new Set(n.value.split("|"));return"!~"===n.operator?vo(r,go(ho({},n),{value:Array.from(o.add(t.value)).join("|")})):n.value===t.value?e:vo(r,go(ho({},t),{operator:"!~",value:Array.from(o.add(t.value)).join("|")}))}function wo(e,t){const{found:n,filtersWithoutFound:r}=yo(e,t.key);if(!n)return e;const o=n.value.split("|").filter((e=>e!==t.value));return o.length>0?vo(r,go(ho({},n),{value:o.join("|")})):[...r]}const Oo=e=>e.operator in qt;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 xo extends Lt.H9{reset(){this.setState({filters:xo.DEFAULT_VALUE})}static resetAll(e){["filters","filtersBaseline","filtersComparison"].forEach((t=>{Lt.jh.findByKeyAndType(e,t,xo).reset()}))}onActivate(){const e=Lt.jh.findByKeyAndType(this,"dataSource",mo).subscribeToState((()=>{this.reset()}));return()=>{e.unsubscribe()}}constructor({key:e}){super({key:e,name:e,label:"Filters",filters:xo.DEFAULT_VALUE,expressionBuilder:e=>e.filter(Oo).map((({key:e,operator:t,value:n})=>t===qt["is-empty"]?`${e}=""`:`${e}${t}"${n}"`)).join(",")}),Po(this,"onChangeQuery",((e,t)=>{Ie("g_pyroscope_app_filters_changed",{name:this.state.name,count:t.length,operators:(0,Vt.uniq)(t.map((e=>e.operator.label)))}),this.setState({filters:t.map(bo)})})),this.addActivationHandler(this.onActivate.bind(this))}}function Co(e,t){var n;return null===(n=Lt.jh.lookupVariable(t,e))||void 0===n?void 0:n.getValue()}function To(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}Po(xo,"DEFAULT_VALUE",[]),Po(xo,"Component",(({model:e})=>{const{key:t}=e.useState(),n=po(e,t),{value:r}=Lt.jh.findByKeyAndType(e,"dataSource",mo).useState(),{from:o,to:a}=Lt.jh.getTimeRange(e).state.value;return w().createElement(Yr,{id:`query-builder-${t}`,autoExecute:!0,dataSourceUid:r,query:n,from:1e3*o.unix(),to:1e3*a.unix(),onChangeQuery:e.onChangeQuery})}));var Ao=function(e){return e.TIMESERIES="time-series",e.BARGAUGE="bar-gauge",e.TABLE="table",e.HISTOGRAM="histogram",e}({});class No extends Lt.Bs{getUrlState(){return{panelType:this.state.panelType}}updateFromUrl(e){const t={};"string"==typeof e.panelType&&e.panelType!==this.state.panelType&&(t.panelType=Object.values(Ao).includes(e.panelType)?e.panelType:No.DEFAULT_PANEL_TYPE),this.setState(t)}reset(){this.setState({panelType:No.DEFAULT_PANEL_TYPE})}constructor(){super({key:"panel-type-switcher",panelType:No.DEFAULT_PANEL_TYPE}),To(this,"_urlSync",new Lt.So(this,{keys:["panelType"]})),To(this,"onChange",(e=>{Ie("g_pyroscope_app_panel_type_changed",{panelType:e}),this.setState({panelType:e})}))}}To(No,"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"}]),To(No,"DEFAULT_PANEL_TYPE","time-series"),To(No,"Component",(({model:e})=>{const{panelType:t}=e.useState();return w().createElement(i.RadioButtonGroup,{"aria-label":"Panel type switcher",options:No.OPTIONS,value:t,onChange:e.onChange,fullWidth:!1})}));var ko=n(1625);function jo(e){const t=a.config.theme2.visualization;return t.getColorByName(t.palette[e%8])}const Ro=(e,t)=>{var n;return(null===(n=e.labels)||void 0===n?void 0:n[t])||"(no value)"},Io=(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};function Do(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}}function _o(e){return e.addActivationHandler((()=>{const{profileTypeId:t,labelSelector:n}=e.state.queries[0];if(!t)return void e.setState({queries:[{refId:"null"}],data:Lo(e,"Missing profile type!")});if(!n)return void e.setState({queries:[{refId:"null"}],data:Lo(e,"Missing label selector!")});if(!Lt.jh.interpolate(e,"$profileMetricId"))return void e.setState({queries:[{refId:"null"}],data:Lo(e,"Missing profile type!")});Do(Lt.jh.interpolate(e,`$profileTypeId${n})`)).serviceId||e.setState({queries:[{refId:"null"}],data:Lo(e,"Missing service name!")})})),e}function Lo(e,t){const n=new Error(t);return j.error(n),{state:o.LoadingState.Error,errors:[n],series:[],timeRange:Lt.jh.getTimeRange(e).state.value}}function Fo({serviceName:e,profileMetricId:t,groupBy:n,filters:r},o,a){const i=r?[...r]:[];i.unshift({key:"service_name",operator:"=",value:e||"$serviceName"});const s=i.map((({key:e,operator:t,value:n})=>`${e}${t}"${n}"`)).join(",");return _o(new Lt.dt({datasource:Qr,queries:[{refId:`${t||"$profileMetricId"}-${s}-${(null==n?void 0:n.label)||"no-group-by"}`,queryType:"metrics",profileTypeId:t||"$profileMetricId",labelSelector:`{${s},$filters}`,groupBy:(null==n?void 0:n.label)?[n.label]:[],limit:o,annotations:a}]}))}const Bo=()=>e=>e.pipe((0,Jr.map)((e=>null==e?void 0:e.map(((e,t)=>(0,Vt.merge)(e,{refId:`${e.refId}-${t}`})))))),$o=()=>e=>e.pipe((0,Jr.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 a=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,Vt.merge)(e,{meta:{stats:[{displayName:"totalSeriesCount",value:t},{displayName:"allValuesSum",value:a},{displayName:"maxValue",value:o}]}})}))})));class Mo extends Lt.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)!==o.LoadingState.Done)return;const{series:a}=n.data;(null==a?void 0:a.length)&&t.setState(this.getConfig(e,a)),this.publishEvent(new Ut({series:a}),!0)}));return()=>{n.unsubscribe()}}getConfig(e,t){var n;let r=Number.NEGATIVE_INFINITY;for(const e of t){const t=Io(e,"allValuesSum")||0;t>r&&(r=t)}const a=null===(n=e.queryRunnerParams.groupBy)||void 0===n?void 0:n.label,i=a?"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:o.VizOrientation.Horizontal,displayMode:ko.eX.Gradient,valueMode:ko.$l.Text,showUnfilled:!0,sizing:ko.T6.Manual,text:{titleSize:13,valueSize:13},namePlacement:ko.TZ.Top,minVizHeight:36,maxVizHeight:36,legend:{showLegend:!1}},fieldConfig:{defaults:{displayName:1===t.length?a:void 0,min:0,max:r,thresholds:{mode:o.ThresholdsMode.Percentage,steps:[]}},overrides:this.getOverrides(e,t)}}}getOverrides(e,t){var n;const{index:r,queryRunnerParams:a}=e,i=null===(n=a.groupBy)||void 0===n?void 0:n.label;return t.map(((e,t)=>({matcher:{id:o.FieldMatcherID.byFrameRefID,options:e.refId},properties:[{id:"displayName",value:Ro(e.fields[1],i)},{id:"color",value:{mode:"fixed",fixedColor:jo(r+t)}}]})))}static Component({model:e}){const{body:t}=e.useState();return w().createElement(t.Component,{model:t})}constructor({item:e,headerActions:t}){super({key:"bar-gauge-label-values",body:Lt.d0.bargauge().setTitle(e.label).setData(new Lt.Es({$data:Fo(e.queryRunnerParams),transformations:[Bo,$o]})).setHeaderActions(t(e)).build()}),this.addActivationHandler(this.onActivate.bind(this,e))}}function Vo(e,t){var n,r;const a=(null===(r=t.fields[1])||void 0===r||null===(n=r.config)||void 0===n?void 0:n.unit)||"short",i=Io(t,"allValuesSum")||0,s=Io(t,"maxValue")||0,l=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 c,u;if(l){var d;const e=t.fields.find((e=>"number"===e.type));c=i/((null==e||null===(d=e.values)||void 0===d?void 0:d.length)||1),u="avg"}else c=i,u="total";const p=(0,o.getValueFormat)(a)(c),m=(0,o.getValueFormat)(a)(s);return`${u} ${e} = ${p.text}${p.suffix} / max = ${m.text}${m.suffix}`}class Uo extends Lt.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)!==o.LoadingState.Done)return;const{series:a}=n.data;(null==a?void 0:a.length)&&t.setState(this.getConfig(e,a)),this.publishEvent(new Ut({series:a}),!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:ko.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:a}=e,i=null===(n=a.groupBy)||void 0===n?void 0:n.label;return t.map(((e,n)=>{const a=e.fields[1];let s=i?Ro(a,i):a.name;return 1===t.length&&(s=Vo(s,e)),{matcher:{id:o.FieldMatcherID.byFrameRefID,options:e.refId},properties:[{id:"displayName",value:s},{id:"color",value:{mode:"fixed",fixedColor:jo(r+n)}}]}}))}static Component({model:e}){const{body:t}=e.useState();return w().createElement(t.Component,{model:t})}constructor({item:e,headerActions:t,legendPlacement:n}){super({key:"histogram-label-values",legendPlacement:n||"bottom",body:Lt.d0.histogram().setTitle(e.label).setData(new Lt.Es({$data:Fo(e.queryRunnerParams),transformations:[Bo,$o]})).setHeaderActions(t(e)).build()}),this.addActivationHandler(this.onActivate.bind(this,e))}}class Go extends Lt.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)!==o.LoadingState.Done)return;const{series:a}=n.data;(null==a?void 0:a.length)&&t.setState(this.getConfig(e,a)),this.publishEvent(new Ut({series:a}),!0)}));return()=>{n.unsubscribe()}}getConfig(e,t){const n=t[0].fields[0].values.length,r=Xr(Lt.jh.findByKeyAndType(this,"profileMetricId",ao).state.value).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:r},{id:"custom.width",value:100}]}]}}}static Component({model:e}){const t=(0,i.useStyles2)(qo),{body:n}=e.useState();return w().createElement("span",{className:t.container},w().createElement(n.Component,{model:n}))}constructor({item:e,headerActions:t}){super({key:"table-label-values",body:Lt.d0.table().setTitle(e.label).setData(new Lt.Es({$data:Fo(e.queryRunnerParams),transformations:[{id:o.DataTransformerID.reduce,options:{reducers:["max"],labelsToFields:!0}},{id:o.DataTransformerID.filterFieldsByName,options:{exclude:{names:["Field"]}}},{id:o.DataTransformerID.renameByRegex,options:{regex:"Max",renamePattern:"max"}},{id:o.DataTransformerID.sortBy,options:{sort:[{field:"max",desc:!0}]}}]})).setHeaderActions(t(e)).build()}),this.addActivationHandler(this.onActivate.bind(this,e))}}const qo=()=>({container:r.css`
[data-testid='data-testid table body'] [role='row']:first-child {
color: ${jo(3)};
font-weight: 500;
}
`});function Ko(e){return{from:1e4*Math.floor((e.from.valueOf()||0)/1e4),to:1e4*Math.floor((e.to.valueOf()||0)/1e4)}}function zo(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function Wo(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){zo(a,r,o,i,s,"next",e)}function s(e){zo(a,r,o,i,s,"throw",e)}i(void 0)}))}}function Ho(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Yo(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){Ho(e,t,n[t])}))}return e}function Zo(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 Xo=(0,n(8537).A)(20);class Jo extends Lt.UU{query(){return Wo((function*(){return{state:o.LoadingState.Done,data:[{name:"Labels",fields:[{name:"Label",type:o.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.value,a=Lt.jh.interpolate(o,"$dataSource"),i=Lt.jh.interpolate(o,"$serviceName"),s=Lt.jh.interpolate(o,"$profileMetricId"),l=`${s}{service_name="${i}"}`,{from:c,to:u}=Ko(r);return{dataSourceUid:a,serviceName:i,profileMetricId:s,query:l,from:c,to:u}}fetchLabels(e,t,n,r,o){return Wo((function*(){mn.setApiClient(new en({dataSourceUid:e}));try{return yield mn.listLabels({query:t,from:n,to:r})}catch(e){throw j.error(e,{info:"Error while loading Pyroscope label names!",variableName:o||""}),e}}))()}fetchLabelValues(e,t,n,r,o,a){return Wo((function*(){let e;try{e=yield mn.listLabelValues({query:t,from:n,to:r,label:o})}catch(e){j.error(e,{info:"Error while loading Pyroscope label values!",variableName:a||""})}const i=e?e.length:-1;return{value:{value:o,groupBy:{label:o,values:e||[]}},text:`${o} (${i>-1?i:"?"})`,count:i}}))()}metricFindQuery(e,t){var n=this;return Wo((function*(){var e,r,o;if(!(null===(r=t.scopedVars)||void 0===r||null===(e=r.__sceneObject)||void 0===e?void 0:e.value).isActive)return[];const{dataSourceUid:a,serviceName:i,profileMetricId:s,query:l,from:c,to:u}=n.getParams(t);if(!i||!s)return j.warn('LabelsDataSource: either serviceName="%s" and/or profileMetricId="%s" is empty! Discarding request.',i,s),[];const d=yield n.fetchLabels(a,l,c,u,null===(o=t.variable)||void 0===o?void 0:o.name),p=yield Promise.all(d.filter((({value:e})=>!Un(e))).map((({value:e},r)=>Xo((()=>{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(Zo(Yo({},e),{index:n})),text:t})));return[{value:"all",text:"All"},...m]}))()}testDatasource(){return Wo((function*(){return{status:"success",message:"OK"}}))()}constructor(){super(no.type,no.uid)}}Ho(Jo,"MAX_TIMESERIES_LABEL_VALUES",10);const Qo=n.p+"e6c722427cfa8715e19d.svg";function ea(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ta(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){ea(e,t,n[t])}))}return e}function na(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 ra(e){const t=Xr(e);return`${t.type} (${t.group})`}function oa(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function aa(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){oa(e,t,n[t])}))}return e}function ia(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 sa=[{text:"Linear",scaleDistribution:{type:ko.L4.Linear}},{text:"Log2",scaleDistribution:{type:ko.L4.Log,log:2}}];class la extends Lt.Bs{onActivate(){this.setState({items:this.buildMenuItems()})}buildMenuItems(e){const{items:t,scaleType:n}=this.state,r=[{text:"Scale type",type:"group",subMenu:sa.map((e=>({text:`${n===e.scaleDistribution.type?"✔ ":""}${e.text}`,onClick:()=>this.onClickScaleOption(e)})))},{type:"divider",text:""},{iconClassName:"compass",text:"Open in Explore",onClick:()=>this.onClickExplore()}];if(e)r.push({iconClassName:"plus-square",text:"Add to investigation (beta)",onClick:()=>{e.onClick()}});else{const e=null==t?void 0:t.find((e=>e.text.includes("Add to investigation")));e&&r.push(aa({},e))}return r}onClickScaleOption(e){const{scaleDistribution:t,text:n}=e;(0,a.reportInteraction)("g_pyroscope_app_timeseries_scale_changed",{scale:t.type});Lt.jh.getAncestor(this,ca).changeScale(t,n),this.setState({scaleType:t.type,items:this.buildMenuItems()})}onClickExplore(){(0,a.reportInteraction)("g_pyroscope_app_open_in_explore_clicked");const e=function(e,t,n){const r=JSON.stringify({"pyroscope-explore":{range:(0,o.toURLRange)(e),queries:[na(ta({},t),{datasource:n})],panelsState:{},datasource:n}});var i;const s=null!==(i=a.config.appSubUrl)&&void 0!==i?i:"";return o.urlUtil.renderUrl(`${s}/explore`,{panes:r,schemaVersion:1})}(Lt.jh.getTimeRange(this).state.value.raw,this.getInterpolatedQuery(),Lt.jh.interpolate(this,"${dataSource}"));window.open(e,"_blank")}getInterpolatedQuery(){var e;const t=null===(e=Lt.jh.getAncestor(this,ca).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?Lt.jh.interpolate(this,t):t])).reduce(((e,[t,n])=>ia(aa({},e),{[t]:n})),{})}useGetInvestigationPluginLinkContext(){const{refId:e,queryType:t,profileTypeId:n,labelSelector:r,groupBy:o}=this.getInterpolatedQuery(),a=Do(`${n}${r}`),i=[a.serviceId,ra(a.profileMetricId)];(null==o?void 0:o.length)&&i.push(o[0]),a.labels.length&&i.push(a.labels.join(", "));const s=i.join(" · "),l=Lt.jh.interpolate(this,"${dataSource}"),c=Lt.jh.getTimeRange(this).state.value;return(0,S.useMemo)((()=>({id:(0,Yt.Ak)(),origin:"Grafana Profiles Drilldown",url:window.location.href,logoPath:Qo,title:s,type:"timeseries",timeRange:aa({},c),queries:[{refId:e,queryType:t,profileTypeId:n,labelSelector:r,groupBy:o}],datasource:l})),[l,o,r,n,t,e,c,s])}useUpdateMenuItems(){const e=function({extensionPointId:e,context:t,pluginId:n}){const r=(0,a.usePluginLinks)({extensionPointId:e,context:t}),[o]=r.links.filter((e=>e.pluginId===n));return o}({extensionPointId:"grafana-pyroscope-app/investigation/v1",context:this.useGetInvestigationPluginLinkContext(),pluginId:"grafana-investigations-app"});(0,S.useEffect)((()=>{e&&this.setState({items:this.buildMenuItems(e)})}),[e])}static Component({model:e}){return e.useUpdateMenuItems(),w().createElement(Lt.Lw.Component,{model:e})}constructor(e){super(aa({scaleType:ko.L4.Linear},e)),this.addActivationHandler(this.onActivate.bind(this))}}class ca extends Lt.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)!==o.LoadingState.Done)return;this.retainPreviousAnnotations(e,t);const{series:r}=e.data;(null==r?void 0:r.length)&&this.updateBodyConfig(r),this.publishEvent(new Ut({series:r}),!0)}retainPreviousAnnotations(e,t){var n,r,o;!(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)&&(e.data.annotations=t.data.annotations)}updateBodyConfig(e){const{body:t}=this.state,n=this.state.displayAllValues?this.getAllValuesConfig(e):this.getConfig(e);t.setState((0,Vt.merge)({},t.state,n))}subscribeToProfileMetricChanges(){try{return Lt.jh.findByKeyAndType(this,"profileMetricId",ao).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)}getConfig(e){var t;const{body:n,item:r,legendPlacement:o}=this.state;let a,{title:i}=n.state;return(null===(t=r.queryRunnerParams.groupBy)||void 0===t?void 0:t.label)&&(i=e.length>1?`${r.label} (${e.length})`:r.label,a=this.buildDescription(r.queryRunnerParams.groupBy)),{title:i,description:a,options:{tooltip:{mode:"single",sort:"none"},legend:{showLegend:!0,displayMode:"list",placement:o}},fieldConfig:{defaults:{min:0,custom:{fillOpacity:e.length>=Jo.MAX_TIMESERIES_LABEL_VALUES?0:9,gradientMode:1===e.length?ko.on.None:ko.on.Opacity,pointSize:3}},overrides:this.getOverrides(e)}}}buildDescription(e){return e?e.values?e.values.length>Jo.MAX_TIMESERIES_LABEL_VALUES?`Showing only ${Jo.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 ${Jo.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:ko.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 a=e.fields[1];let i=r?Ro(a,r):a.name;i=Vo(i,e);const s=[{id:"displayName",value:i},{id:"color",value:{mode:"fixed",fixedColor:jo(n.index+t)}}];return{matcher:{id:o.FieldMatcherID.byFrameRefID,options:e.refId},properties:s}}))}updateItem(e){var t,n;const{item:r,headerActions:o,body:a}=this.state,i=(0,Vt.merge)({},r,e);if((null===(t=e.queryRunnerParams)||void 0===t?void 0:t.hasOwnProperty("groupBy"))&&(void 0===e.queryRunnerParams.groupBy?delete i.queryRunnerParams.groupBy:i.queryRunnerParams.groupBy=e.queryRunnerParams.groupBy),(null===(n=e.queryRunnerParams)||void 0===n?void 0:n.hasOwnProperty("filters"))&&void 0===e.queryRunnerParams.filters&&delete i.queryRunnerParams.filters,this.setState({item:i}),a.setState({title:e.label,description:this.buildDescription(i.queryRunnerParams.groupBy),headerActions:o(i)}),!(0,Vt.isEqual)(r.queryRunnerParams,i.queryRunnerParams)){var s;const{queries:e}=Fo(i.queryRunnerParams,Jo.MAX_TIMESERIES_LABEL_VALUES).state,t=null===(s=a.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,Vt.merge)({},n.state.fieldConfig,{defaults:{custom:{scaleDistribution:e,axisLabel:e.type!==ko.L4.Linear?t:""}}})})}static Component({model:e}){const{body:t}=e.useState();return w().createElement(t.Component,{model:t})}constructor({item:e,headerActions:t,displayAllValues:n,legendPlacement:r,data:o,overrides:a,annotations:i}){super({key:"timeseries-label-values",item:e,headerActions:t,displayAllValues:Boolean(n),legendPlacement:r||"bottom",overrides:a,body:Lt.d0.timeseries().setTitle(e.label).setData(o||new Lt.Es({$data:Fo(e.queryRunnerParams,n?void 0:Jo.MAX_TIMESERIES_LABEL_VALUES,i),transformations:[Bo,$o]})).setHeaderActions(t(e)).setMenu(new la({})).build()}),this.addActivationHandler(this.onActivate.bind(this))}}function ua(e,t){switch(e){case Ao.BARGAUGE:return new Mo(t);case Ao.TABLE:return new Go(t);case Ao.HISTOGRAM:return new Uo(t);case Ao.TIMESERIES:default:return new ca(t)}}var da=n(9488);const pa=n.p+"944c737f589d02ecf603.svg",ma=n.p+"e79edcfbe2068fae2364.svg",fa=(e=50)=>{const[t,n]=(0,S.useState)({x:null,y:null});return(0,S.useEffect)((()=>{const t=(0,Vt.throttle)((e=>{n({x:e.clientX,y:e.clientY})}),e);return window.addEventListener("mousemove",t),()=>{window.removeEventListener("mousemove",t)}}),[e]),t},ha=({width:e="auto",height:t,show404:n=!1})=>{const r=(0,i.useTheme2)(),{x:o,y:a}=fa(),s=(0,i.useStyles2)(ga,o,a,n);return w().createElement(da.A,{src:r.isDark?pa:ma,className:s.svg,height:t,width:e})};ha.displayName="GrotNotFound";const ga=(e,t,n,o)=>{const{innerWidth:a,innerHeight:i}=window,s=n&&n/i,l=t&&t/a,c=null!==s?ba(s,-20,5):0,u=null!==l?ba(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"}})}},ba=(e,t,n)=>e*(n-t)+t,ya=({message:e})=>{const t=(0,i.useStyles2)(va);return w().createElement("div",{className:t.container},w().createElement(i.Box,{paddingY:8},w().createElement(i.Stack,{direction:"column",alignItems:"center",gap:3},w().createElement(ha,{width:300}),w().createElement(i.Text,{variant:"h5"},e))))};function va(){return{container:(0,r.css)({width:"100%",display:"flex",justifyContent:"space-evenly",flexDirection:"column"})}}ya.displayName="EmptyState";class Ea extends Lt.Bs{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(Ea,"Component",(({model:e})=>{const{message:t}=e.useState();return w().createElement(ya,{message:t})}));class Sa extends Lt.Bs{}function wa(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}(Sa,"Component",(({model:e})=>{const{message:t}=e.useState();return w().createElement(i.Alert,{title:"Query error!",severity:"error"},t)}));var Oa=function(e){return e.GRID="grid",e.ROWS="rows",e}({});class Pa extends Lt.Bs{getUrlState(){return{layout:this.state.layout}}updateFromUrl(e){const t={};"string"==typeof e.layout&&e.layout!==this.state.layout&&(t.layout=Object.values(Oa).includes(e.layout)?e.layout:Pa.DEFAULT_LAYOUT),this.setState(t)}constructor(){super({key:"layout-switcher",layout:Pa.DEFAULT_LAYOUT}),wa(this,"_urlSync",new Lt.So(this,{keys:["layout"]})),wa(this,"onChange",(e=>{Ie("g_pyroscope_app_layout_changed",{layout:e}),this.setState({layout:e})}))}}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}wa(Pa,"OPTIONS",[{label:"Grid",value:"grid"},{label:"Rows",value:"rows"}]),wa(Pa,"DEFAULT_LAYOUT","grid"),wa(Pa,"Component",(({model:e})=>{const{layout:t}=e.useState();return w().createElement(i.RadioButtonGroup,{"aria-label":"Layout switcher",options:Pa.OPTIONS,value:t,onChange:e.onChange,fullWidth:!1})}));class Ca extends Lt.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:Ca.DEFAULT_VALUE),this.setState(t)}constructor(){super({key:"no-data-switcher",hideNoData:Ca.DEFAULT_VALUE}),xa(this,"_urlSync",new Lt.So(this,{keys:["hideNoData"]})),xa(this,"onChange",(e=>{Ie("g_pyroscope_app_hide_no_data_changed",{hideNoData:e}),this.setState({hideNoData:e})}))}}function Ta(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}xa(Ca,"DEFAULT_VALUE","off"),xa(Ca,"Component",(({model:e})=>{const{hideNoData:t}=e.useState();return w().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 Aa extends Lt.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:Aa.DEFAULT_SEARCH_TEXT,resultsCount:""}),Ta(this,"_urlSync",new Lt.So(this,{keys:["searchText"]})),Ta(this,"onChange",(e=>{this.setState({searchText:e.target.value})})),Ta(this,"clearSearchText",(()=>{this.setState({searchText:""})})),Ta(this,"onFocus",(()=>{Ie("g_pyroscope_app_quick_filter_focused")}))}}Ta(Aa,"DEFAULT_SEARCH_TEXT",""),Ta(Aa,"DEBOUNCE_DELAY",250),Ta(Aa,"Component",(({model:e})=>{const t=(0,i.useStyles2)(Na),{placeholder:n,searchText:r,resultsCount:o}=e.useState();return w().createElement(i.Input,{type:"text",className:"quick-filter","aria-label":"Quick filter",placeholder:n,value:r,prefix:w().createElement(i.Icon,{name:"search"}),suffix:w().createElement(w().Fragment,null,""!==o&&w().createElement(i.Tag,{className:t.resultsCount,name:o,colorIndex:9,"data-testid":"quick-filter-results-count"}),w().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 Na=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 ka(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function ja(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){ka(a,r,o,i,s,"next",e)}function s(e){ka(a,r,o,i,s,"throw",e)}i(void 0)}))}}function Ra(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Ia(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){Ra(e,t,n[t])}))}return e}class Da extends Lt.UU{static getAllFavorites(){var e;return(null===(e=_.get(_.KEYS.PROFILES_EXPLORER))||void 0===e?void 0:e.favorites)||[]}static areFavoritesEqual(e,t){return e.panelType===t.panelType&&(0,Vt.isEqual)(e.queryRunnerParams,t.queryRunnerParams)}static exists(e){return Da.getAllFavorites().some((t=>Da.areFavoritesEqual(t,e)))}static addFavorite(e){const t=_.get(_.KEYS.PROFILES_EXPLORER);t.favorites.push(e),_.set(_.KEYS.PROFILES_EXPLORER,t)}static removeFavorite(e){const t=_.get(_.KEYS.PROFILES_EXPLORER);t.favorites=t.favorites.filter((t=>!Da.areFavoritesEqual(t,e))),_.set(_.KEYS.PROFILES_EXPLORER,t)}query(){return ja((function*(){return{state:o.LoadingState.Done,data:[{name:"Favories",fields:[{name:null,type:o.FieldType.other,values:[],config:{}}],length:0}]}}))()}metricFindQuery(){return ja((function*(){return Da.getAllFavorites().map((e=>{const{serviceName:t,profileMetricId:n,groupBy:r,filters:o}=e.queryRunnerParams||{},a=[t,ra(n)];return(null==r?void 0:r.label)&&a.push(r.label),(null==o?void 0:o.length)&&a.push(o.map((({key:e,operator:t,value:n})=>`${e}${t}"${n}"`)).join(", ")),{value:JSON.stringify(Ia({value:JSON.stringify(e)},e)),text:a.join(" · ")}}))}))()}testDatasource(){return ja((function*(){return{status:"success",message:"OK"}}))()}constructor(){var e;super(to.type,to.uid);const t=_.get(_.KEYS.PROFILES_EXPLORER)||{};(e=t).favorites||(e.favorites=[]),t.favorites=t.favorites.map((e=>Ia({panelType:Ao.TIMESERIES},e))),_.set(_.KEYS.PROFILES_EXPLORER,t)}}function _a(e,t){const{queryRunnerParams:n}=t,r=(0,Vt.defaults)((0,Vt.clone)(n),{serviceName:Co(e,"serviceName"),profileMetricId:Co(e,"profileMetricId")}),o=Lt.jh.lookupVariable("filters",e).state.filters.map((({key:e,operator:t,value:n})=>({key:e,operator:t,value:n})));return r.filters=(0,Vt.uniqBy)([...r.filters||[],...o],(({key:e,operator:t,value:n})=>`${e}${t}${n}`)),r}function La(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class Fa extends Lt.Bs{update(){this.setState({isFav:this.isStored()})}isStored(){return Da.exists(this.buildFavorite())}static buildFavorite(e){var t;const{index:n,queryRunnerParams:r,panelType:o}=e,a={index:n,queryRunnerParams:{serviceName:r.serviceName,profileMetricId:r.profileMetricId},panelType:o};return r.groupBy&&(a.queryRunnerParams.groupBy={label:r.groupBy.label}),(null===(t=r.filters)||void 0===t?void 0:t.length)&&(a.queryRunnerParams.filters=r.filters),a}buildFavorite(){const{item:e,skipVariablesInterpolation:t}=this.state;return Fa.buildFavorite({index:e.index,queryRunnerParams:t?e.queryRunnerParams:_a(this,e),panelType:e.panelType})}constructor(e){super(e),La(this,"_variableDependency",new Lt.Sh(this,{variableNames:["serviceName","profileMetricId","filters"],onReferencedVariableValueChanged:()=>{this.update()}})),La(this,"onClick",(()=>{Ie("g_pyroscope_app_fav_action_clicked",{favAfterClick:!this.state.isFav}),this.state.isFav?Da.removeFavorite(this.buildFavorite()):Da.addFavorite(this.buildFavorite()),this.setState({isFav:!this.state.isFav})})),this.addActivationHandler((()=>this.update()))}}La(Fa,"Component",(({model:e})=>{const t=(0,i.useStyles2)(Ba),{isFav:n}=e.useState();return w().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 Ba=()=>({favedButton:r.css`
color: #f2cc0d;
margin: 0;
`,notFavedbutton:r.css`
margin: 0;
`}),$a=function(e,t){const n=Da.exists(Fa.buildFavorite(e)),r=Da.exists(Fa.buildFavorite(t));return n&&r?Er(e.label,t.label):r?1:n?-1:0},Ma="240px";class Va extends Lt.Bs{static buildGridItemKey(e){return`grid-item-${e.index}-${e.value}`}static getGridColumnsTemplate(e){return e===Oa.ROWS?"1fr":"repeat(auto-fit, minmax(400px, 1fr))"}onActivate(){const e=Lt.jh.lookupVariable(this.state.variableName,this),t=e.subscribeToState(((e,t)=>{!e.loading&&t.loading&&this.renderGridItems()}));e.update();const n=this.subscribeToRefreshClick(),r=this.subscribeToQuickFilterChange(),o=this.subscribeToLayoutChange(),a=this.subscribeToHideNoDataChange(),i=this.subscribeToFiltersChange();return()=>{i.unsubscribe(),a.unsubscribe(),o.unsubscribe(),r.unsubscribe(),n.unsubscribe(),t.unsubscribe()}}subscribeToRefreshClick(){const e=Lt.jh.lookupVariable(this.state.variableName,this),t=e.state.refresh;e.setState({refresh:o.VariableRefresh.never});const n=()=>{e.update()},r=document.querySelector('[data-testid="data-testid RefreshPicker run button"]');return r||j.error(new Error("SceneByVariableRepeaterGrid: Refresh button not found! The list of items will never be updated.")),null==r||r.addEventListener("click",n),null==r||r.setAttribute("title","Click to completely refresh all the panels present on the screen"),{unsubscribe(){null==r||r.removeAttribute("title"),null==r||r.removeEventListener("click",n),e.setState({refresh:t})}}}subscribeToQuickFilterChange(){const e=Lt.jh.findByKeyAndType(this,"quick-filter",Aa);this.subscribeToState(((t,n)=>{t.items.length!==n.items.length&&e.setResultsCount(t.items.length)}));return e.subscribeToState((0,Vt.debounce)(((e,t)=>{e.searchText!==(null==t?void 0:t.searchText)&&this.renderGridItems()}),Aa.DEBOUNCE_DELAY))}subscribeToLayoutChange(){const e=Lt.jh.findByKeyAndType(this,"layout-switcher",Pa),t=this.state.body,n=(e,n)=>{e.layout!==(null==n?void 0:n.layout)&&t.setState({templateColumns:Va.getGridColumnsTemplate(e.layout)})};return n(e.state),e.subscribeToState(n)}subscribeToHideNoDataChange(){const e=Lt.jh.findByKeyAndType(this,"no-data-switcher",Ca);if(!e.isActive)return this.setState({hideNoData:!1}),{unsubscribe:L};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=Lt.jh.findByKeyAndType(this,"filters",xo),t=Lt.jh.findByKeyAndType(this,"no-data-switcher",Ca);return e.subscribeToState((()=>{"on"===t.state.hideNoData&&this.renderGridItems(!0)}))}buildItemsData(e){const{mapOptionToItem:t}=this.state,n={serviceName:Co(this,"serviceName"),profileMetricId:Co(this,"profileMetricId"),panelType:Lt.jh.findByKeyAndType(this,"panel-type-switcher",No).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,Vt.isEqual)(t,e)}renderGridItems(e=!1){const t=Lt.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=ua(e.panelType,{item:e,headerActions:this.state.headerActions.bind(null,e,this.state.items)});return this.state.hideNoData&&this.setupHideNoData(t),new Lt.xK({key:Va.buildGridItemKey(e),body:t})}));this.state.body.setState({autoRows:Ma,children:r})}setupHideNoData(e){const t=e.subscribeToEvent(Ut,(t=>{var n;if(null===(n=t.payload.series)||void 0===n?void 0:n.length)return;const r=Lt.jh.getAncestor(e,Lt.xK),{key:o}=r.state,a=Lt.jh.getAncestor(r,Lt.gF),i=a.state.children.filter((e=>e.state.key!==o));i.length?a.setState({children:i}):this.renderEmptyState()}));e.addActivationHandler((()=>()=>{t.unsubscribe()}))}filterItems(e){const t=Lt.jh.findByKeyAndType(this,"quick-filter",Aa),{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 Lt.xK({body:new Ea({message:"No results"})})]})}renderErrorState(e){this.state.body.setState({autoRows:"480px",children:[new Lt.xK({body:new Sa({message:e.message||e.toString()})})]})}static Component({model:e}){var t;const{body:n,variableName:r}=e.useState(),{loading:o}=null===(t=Lt.jh.lookupVariable(r,e))||void 0===t?void 0:t.useState();return o?w().createElement(i.Spinner,null):w().createElement(n.Component,{model:n})}constructor({key:e,variableName:t,headerActions:n,mapOptionToItem:r,sortItemsFn:a}){super({key:e,variableName:t,items:[],headerActions:n,mapOptionToItem:r,sortItemsFn:a||$a,hideNoData:!1,body:new Lt.gF({templateColumns:Va.getGridColumnsTemplate(Pa.DEFAULT_LAYOUT),autoRows:Ma,isLazy:!0,$behaviors:[new Lt.Gg.K2({key:"metricCrosshairSync",sync:o.DashboardCursorSync.Crosshair})],children:[]})}),this.addActivationHandler(this.onActivate.bind(this))}}class Ua extends o.BusEventWithPayload{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(Ua,"type","expand-panel");class Ga extends o.BusEventWithPayload{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(Ga,"type","select-label");class qa extends o.BusEventWithPayload{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(qa,"type","view-service-flame-graph");class Ka extends o.BusEventWithPayload{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(Ka,"type","view-service-labels");class za extends o.BusEventWithPayload{}function Wa(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Ha(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){Wa(e,t,n[t])}))}return e}function Ya(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}(za,"type","view-service-profiles");const Za=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:Ua})],["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:Ga})],["view-flame-graph",Object.freeze({label:"Flame graph",tooltip:({queryRunnerParams:e},t)=>{const n=e.serviceName||Co(t,"serviceName");return`View the "${Xr(e.profileMetricId||Co(t,"profileMetricId")).type}" flame graph of ${n}`},EventConstructor:qa})],["view-labels",Object.freeze({label:"Labels",tooltip:({queryRunnerParams:e},t)=>`Explore the labels of ${e.serviceName||Co(t,"serviceName")}`,EventConstructor:Ka})],["view-profiles",Object.freeze({label:"Profile types",tooltip:({queryRunnerParams:e},t)=>`View the profile types of ${e.serviceName||Co(t,"serviceName")}`,EventConstructor:za})]]);class Xa extends Lt.Bs{buildEvent(){const{EventConstructor:e,item:t,skipVariablesInterpolation:n}=this.state;return new e({item:Ya(Ha({},t),{queryRunnerParams:n?t.queryRunnerParams:_a(this,t)})})}constructor({type:e,item:t,tooltip:n,skipVariablesInterpolation:r}){const o=Za.get(e);if(!o)throw new TypeError(`Unknown event type="${e}"!`);super(Ha({type:e,item:t},(0,Vt.merge)({},o,{tooltip:n,skipVariablesInterpolation:r}))),Wa(this,"onClick",(()=>{Ie("g_pyroscope_app_select_action_clicked",{type:this.state.type}),this.publishEvent(this.buildEvent(),!0)}))}}Wa(Xa,"Component",(({model:e})=>{const t=(0,i.useStyles2)(Ja),{ariaLabel:n,label:r,icon:o,tooltip:a,item:s}=e.useState();return w().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 Ja=()=>({selectButton:r.css`
margin: 0;
padding: 0;
`});class Qa extends Lt.Bs{onActivate(){Lt.jh.findByKeyAndType(this,"quick-filter",Aa).setPlaceholder("Search services (comma-separated regexes are supported)")}getVariablesAndGridControls(){return{variables:[Lt.jh.findByKeyAndType(this,"profileMetricId",ao)],gridControls:[Lt.jh.findByKeyAndType(this,"quick-filter",Aa),Lt.jh.findByKeyAndType(this,"layout-switcher",Pa)]}}static Component({model:e}){const{body:t}=e.useState();return w().createElement(t.Component,{model:t})}constructor(){super({key:"explore-all-services",$variables:new Lt.Pj({variables:[new co({query:co.QUERY_PROFILE_METRIC_DEPENDENT,skipUrlSync:!0})]}),body:new Va({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:Ao.TIMESERIES}),headerActions:e=>[new Xa({type:"view-profiles",item:e}),new Xa({type:"view-labels",item:e}),new Xa({type:"view-flame-graph",item:e}),new Fa({item:e})]})}),this.addActivationHandler(this.onActivate.bind(this))}}function ei(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ti(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){ei(e,t,n[t])}))}return e}function ni(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 ri extends Lt.Bs{constructor(e){super(ti({key:"drawer",isOpen:!1},e)),ei(this,"open",(({title:e,subTitle:t,body:n})=>{this.setState(ni(ti({},this.state),{isOpen:!0,title:e,subTitle:t,body:n}))})),ei(this,"close",(()=>{this.setState({isOpen:!1})}))}}function oi(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}ei(ri,"Component",(({model:e})=>{const{isOpen:t,title:n,subTitle:r,body:o}=e.useState();return w().createElement(w().Fragment,null,o&&t&&w().createElement(i.Drawer,{size:"lg",title:n,subtitle:r,closeOnMaskClick:!0,onClose:e.close},w().createElement(o.Component,{model:o})))}));class ai extends Lt.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,Jr.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 a=e.apply(t,n);function i(e){oi(a,r,o,i,s,"next",e)}function s(e){oi(a,r,o,i,s,"throw",e)}i(void 0)}))})()}constructor(){super({name:"favorite",label:"🔖 Favorite",datasource:to,query:"$dataSource",loading:!0,refresh:o.VariableRefresh.never,skipUrlSync:!0})}}function ii(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}class si extends Lt.Bs{onActivate(){Lt.jh.findByKeyAndType(this,"quick-filter",Aa).setPlaceholder("Search favorites (comma-separated regexes are supported)");var e=this;const t=this.subscribeToEvent(Ua,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 a=t.apply(e,n);function i(e){ii(a,r,o,i,s,"next",e)}function s(e){ii(a,r,o,i,s,"throw",e)}i(void 0)}))});return function(e){return n.apply(this,arguments)}}());return()=>{t.unsubscribe()}}getVariablesAndGridControls(){return{variables:[],gridControls:[Lt.jh.findByKeyAndType(this,"quick-filter",Aa),Lt.jh.findByKeyAndType(this,"layout-switcher",Pa),Lt.jh.findByKeyAndType(this,"no-data-switcher",Ca)]}}openExpandedPanelDrawer(e){this.state.drawer.open({title:e.label,body:ua(e.panelType,{displayAllValues:!0,legendPlacement:"right",item:e,headerActions:()=>[new Xa({type:"view-labels",item:e}),new Xa({type:"view-flame-graph",item:e})]})})}static Component({model:e}){const{body:t,drawer:n}=e.useState();return w().createElement(w().Fragment,null,w().createElement(t.Component,{model:t}),w().createElement(n.Component,{model:n}))}constructor(){super({key:"explore-favorites",$variables:new Lt.Pj({variables:[new ai]}),body:new Va({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)=>Er(e.label,t.label),headerActions:e=>{const t=[new Xa({type:"view-labels",item:e,skipVariablesInterpolation:!0}),new Xa({type:"view-flame-graph",item:e,skipVariablesInterpolation:!0})];return e.queryRunnerParams.groupBy&&t.push(new Xa({type:"expand-panel",item:e,tooltip:()=>"Expand panel to view all the data",skipVariablesInterpolation:!0})),t.push(new Fa({item:e,skipVariablesInterpolation:!0})),t}}),drawer:new ri}),this.addActivationHandler(this.onActivate.bind(this))}}var li=n(5540);function ci({options:e,mainLabels:t,value:n,onChange:r,onRefresh:o}){const a=(0,i.useStyles2)(ui),s=(0,i.useTheme2)(),[l,c]=(0,S.useState)(0),[u,d]=(0,S.useState)(0),p=u>l,m=(0,S.useRef)(null);(0,li.w)({ref:m,onResize:()=>{const e=m.current;e&&d(e.clientWidth)}});const f=e.filter((e=>t.includes(e.value))),h=e.filter((e=>!t.includes(e.value)));return(0,S.useEffect)((()=>{const{fontSize:e}=s.typography,t=f.map((e=>e.label||e.text||"")).join(" "),n=(0,i.measureText)(t,e).width;c(n+70*f.length)}),[f,s]),w().createElement(i.Field,{label:"Group by labels"},w().createElement("div",{ref:m,className:a.container},p?w().createElement(w().Fragment,null,w().createElement(i.RadioButtonGroup,{"aria-label":"Labels selector",options:f,value:n,onChange:r}),w().createElement(i.Select,{"aria-label":"Other labels selector",className:a.select,placeholder:"Other labels",options:h,value:n&&h.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})):w().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)||fi.DEFAULT_VALUE),isClearable:!0}),w().createElement(i.RefreshPicker,{noIntervalPicker:!0,onRefresh:o,isOnCanvas:!1,onIntervalChanged:L,tooltip:"Click to refresh all labels"})))}const ui=e=>({container:r.css`
display: flex;
gap: ${e.spacing(1)};
`,select:r.css`
max-width: ${e.spacing(22)};
`});function di(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function pi(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){di(a,r,o,i,s,"next",e)}function s(e){di(a,r,o,i,s,"throw",e)}i(void 0)}))}}function mi(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class fi extends Lt.fS{onActivate(){this.state.value||this.setState({value:fi.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:no,query:'$dataSource and $profileMetricId{service_name="$serviceName"}',loading:!0}),e=this,mi(this,"update",pi((function*(){if(e.state.loading)return;let t=[],n=null;e.setState({loading:!0,options:[],error:null});try{t=yield(0,Jr.lastValueFrom)(e.getValueOptions({}))}catch(e){n=e}finally{e.setState({loading:!1,options:t,error:n})}}))),mi(this,"onChange",(e=>{Ie("g_pyroscope_app_group_by_label_clicked"),Ft(),this.changeValueTo(e)})),this.changeValueTo=this.changeValueTo.bind(this),this.addActivationHandler(this.onActivate.bind(this))}}mi(fi,"DEFAULT_VALUE","all"),mi(fi,"MAX_MAIN_LABELS",8),mi(fi,"Component",(({model:e})=>{const t=(0,i.useStyles2)(hi),{loading:n,value:r,options:o,error:a}=e.useState(),s=(0,S.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 w().createElement(i.Field,{label:"Group by labels"},w().createElement(i.Spinner,{className:t.spinner}));if(a)return w().createElement(i.Field,{label:"Group by labels"},w().createElement("div",{className:t.groupByErrorContainer},w().createElement(i.Tooltip,{theme:"error",content:a.toString()},w().createElement(i.Icon,{className:t.iconError,name:"exclamation-triangle",size:"xl"})),w().createElement(i.RefreshPicker,{noIntervalPicker:!0,onRefresh:e.update,isOnCanvas:!1,onIntervalChanged:L})));return w().createElement(ci,{options:s,value:r,mainLabels:(e=>e.slice(0,fi.MAX_MAIN_LABELS).map((({value:e})=>e)))(s),onChange:e.onChange,onRefresh:e.update})}));const hi=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};
`});function gi(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class bi extends Lt.Bs{onActivate(e,t){e&&this.initVariables(e),this.setState({body:this.buildTimeseries(e,t)}),t&&this.subscribeToGroupByStateChanges(e)}initVariables(e){const{serviceName:t,profileMetricId:n,filters:r}=e.queryRunnerParams;if(t){Lt.jh.findByKeyAndType(this,"serviceName",co).changeValueTo(t)}if(n){Lt.jh.findByKeyAndType(this,"profileMetricId",ao).changeValueTo(n)}if(r){Lt.jh.findByKeyAndType(this,"filters",xo).setState({filters:r})}}buildTimeseries(e,t){const{headerActions:n}=this.state,r={index:0,value:"",queryRunnerParams:{},label:this.buildTitle(),panelType:Ao.TIMESERIES};e&&t&&(r.queryRunnerParams.groupBy=e.queryRunnerParams.groupBy);const o=Lt.jh.findByKeyAndType(this,"groupBy",fi).state.value;return new ca({item:r,headerActions:n,annotations:!0,data:!e&&t&&o&&"all"!==o?new Lt.Es({$data:new Lt.dt({datasource:Qr,queries:[]}),transformations:[Bo,$o]}):void 0})}subscribeToGroupByStateChanges(e){const t=Lt.jh.findByKeyAndType(this,"groupBy",fi);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&&Lt.jh.findByKeyAndType(this,"filters",xo).reset(),null===(t=this.state.body)||void 0===t||t.updateItem({index:0,label:this.buildTitle(),queryRunnerParams:{groupBy:void 0}})}buildTitle(){const e=Co(this,"profileMetricId"),{description:t}=Xr(e);return t||ra(e)}static Component({model:e}){const{body:t}=e.useState();return t&&w().createElement(t.Component,{model:t})}constructor({item:e,headerActions:t,supportGroupBy:n}){super({headerActions:t,body:void 0}),gi(this,"_variableDependency",new Lt.Sh(this,{variableNames:["serviceName","profileMetricId"],onReferencedVariableValueChanged:e=>{this.resetTimeseries("serviceName"===e.state.name)}})),this.addActivationHandler(this.onActivate.bind(this,e,n))}}gi(bi,"MIN_HEIGHT",240);class yi extends o.BusEventWithPayload{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(yi,"type","view-diff-flame-graph");class vi extends o.BusEventWithPayload{}function Ei({option:e,checked:t,onChange:n}){var o;const a=(0,i.useStyles2)(Si),[s,l]=(0,S.useState)(!1),c=(0,S.useRef)(null),u=null===(o=c.current)||void 0===o?void 0:o.closest("label");return(0,S.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]),w().createElement(w().Fragment,null,w().createElement(i.Tooltip,{content:e.description,show:!t&&s,placement:"top"},w().createElement("span",{className:a.tooltipAnchor})),w().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}(vi,"type","select-for-compare");const Si=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 wi({item:e,itemStats:t,statsDescription:n,compareActionChecks:r,onChangeCompareTarget:a}){const s=(0,i.useStyles2)(Oi),{index:l,value:c}=e,u=jo(l),d=(0,S.useMemo)((()=>{if(!t)return w().createElement(i.Spinner,{inline:!0});const{allValuesSum:e,unit:n}=t,{text:r,suffix:a}=(0,o.getValueFormat)(n)(e);return`${r}${a}`}),[t]),p=(0,S.useMemo)((()=>[{label:"Baseline",value:lt.BASELINE,description:r[0]?"":`Click to select "${c}" as baseline for comparison`},{label:"Comparison",value:lt.COMPARISON,description:r[1]?"":`Click to select "${c}" as target for comparison`}]),[r,c]);return w().createElement("div",{className:s.container,"data-testid":`stats-panel-${c}`},w().createElement("h1",{style:{color:u},className:s.title,title:`${n}: ${d}`},d),w().createElement("div",{className:s.compareActions},w().createElement(Ei,{option:p[0],checked:r[0],onChange:a}),w().createElement(Ei,{option:p[1],checked:r[1],onChange:a})))}const Oi=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 Pi(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class xi extends Lt.Bs{onActivate(){const e=Lt.jh.findByKeyAndType(this,"group-by-labels",Gi).getCompare();this.updateCompareActions(e.get(lt.BASELINE),e.get(lt.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=Co(this,"profileMetricId"),{description:t}=Xr(e);return t||ra(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 w().createElement(wi,{item:t,itemStats:n,statsDescription:r,compareActionChecks:o,onChangeCompareTarget:e.onChangeCompareTarget})}constructor({item:e}){super({item:e,itemStats:void 0,compareActionChecks:[!1,!1],statsDescription:""}),Pi(this,"onChangeCompareTarget",(e=>{this.publishEvent(new vi({compareTarget:e,item:this.state.item}),!0)})),this.addActivationHandler(this.onActivate.bind(this))}}Pi(xi,"WIDTH_IN_PIXELS",186);class Ci extends Lt.Bs{static buildPanelKey(e){return`compare-panel-${e.value}`}onActivate(){const{statsPanel:e,timeseriesPanel:t}=this.state,n=t.subscribeToEvent(Ut,(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 a=Io(o,"allValuesSum")||0;(null===(r=e.getStats())||void 0===r?void 0:r.allValuesSum)!==a&&e.updateStats({allValuesSum:a,unit:o.fields[1].config.unit||"short"})}));return()=>{n.unsubscribe()}}static Component({model:e}){const t=(0,i.useStyles2)(Ti),{statsPanel:n,timeseriesPanel:o}=e.useState(),{compareActionChecks:a}=n.useState(),s=a[0]||a[1];return w().createElement("div",{className:(0,r.cx)(t.container,s&&"selected")},w().createElement("div",{className:t.statsPanel},w().createElement(n.Component,{model:n})),w().createElement("div",{className:t.timeseriesPanel},w().createElement(o.Component,{model:o})))}constructor({item:e,headerActions:t}){super({key:"label-value-panel",statsPanel:new xi({item:e}),timeseriesPanel:new ca({item:e,headerActions:t})}),this.addActivationHandler(this.onActivate.bind(this))}}const Ti=e=>({container:r.css`
display: flex;
min-width: 0px;
min-height: ${Ni};
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: ${Ni};
}
`,statsPanel:r.css`
width: ${xi.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 Ai({label:e}){const t='service_name="$serviceName"';return new Lt.dt({datasource:Qr,queries:[{refId:`$profileMetricId-${t}-${e}`,queryType:"metrics",profileTypeId:"$profileMetricId",labelSelector:`{${t}}`,groupBy:[e]}]})}const Ni="160px";class ki extends Lt.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(),a=this.subscribeToFiltersChange();return()=>{a.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)!==o.LoadingState.Loading&&(t.unsubscribe(),this.renderGridItems(e),this.setState({isLoading:!1}))}))}subscribeToGroupByChange(){return Lt.jh.findByKeyAndType(this,"groupBy",fi).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||j.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=Lt.jh.findByKeyAndType(this,"quick-filter",Aa);this.subscribeToState(((t,n)=>{t.items.length!==n.items.length&&e.setResultsCount(t.items.length)}));return e.subscribeToState((0,Vt.debounce)(((e,t)=>{e.searchText!==(null==t?void 0:t.searchText)&&this.renderGridItems()}),Aa.DEBOUNCE_DELAY))}subscribeToLayoutChange(){const e=Lt.jh.findByKeyAndType(this,"layout-switcher",Pa),t=this.state.body,n=(e,n)=>{e.layout!==(null==n?void 0:n.layout)&&t.setState({templateColumns:e.layout===Oa.ROWS?"1fr":"repeat(auto-fit, minmax(600px, 1fr))"})};return n(e.state),e.subscribeToState(n)}subscribeToHideNoDataChange(){const e=Lt.jh.findByKeyAndType(this,"no-data-switcher",Ca);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=Lt.jh.findByKeyAndType(this,"filters",xo),t=Lt.jh.findByKeyAndType(this,"no-data-switcher",Ca);return e.subscribeToState((()=>{"on"===t.state.hideNoData&&this.refetchData()}))}refetchData(e=!1){this.setState({isLoading:!0,$data:new Lt.Es({$data:Ai({label:this.state.label}),transformations:[Bo,$o]})}),this.subscribeOnceToDataChange(e)}shouldRenderItems(e){const{items:t}=this.state;return!e.length||t.length!==e.length||!(0,Vt.isEqual)(t,e)}buildItemsData(e){const t=Co(this,"serviceName"),n=Co(this,"profileMetricId"),{label:r,startColorIndex:o,sortItemsFn:a}=this.state,i=e.map(((e,a)=>{var i;const s=e.fields[1],l=(null===(i=s.labels)||void 0===i?void 0:i[r])||"",c=Ro(s,r);return{index:o+a,value:l,label:c,queryRunnerParams:{serviceName:t,profileMetricId:n,filters:[{key:r,operator:"=",value:l}]},panelType:Ao.TIMESERIES}}));return this.filterItems(i).sort(a)}renderGridItems(e=!1){if(!this.state.$data.state.data)return;const{state:t,series:n,errors:r}=this.state.$data.state.data;if(t===o.LoadingState.Loading)return;if(t===o.LoadingState.Error)return void this.renderErrorState(null==r?void 0:r[0]);const a=this.buildItemsData(n);if(!e&&!this.shouldRenderItems(a))return;if(this.setState({items:a}),!this.state.items.length)return void this.renderEmptyState();const i=a.map((e=>new Lt.xK({key:ki.buildGridItemKey(e),body:this.buildVizPanel(e)})));this.state.body.setState({autoRows:Ni,children:i})}buildVizPanel(e){const t=new Ci({item:e,headerActions:this.state.headerActions.bind(null,e,this.state.items)}),n=t.subscribeToEvent(Ut,(e=>{var n;if(!this.state.hideNoData||(null===(n=e.payload.series)||void 0===n?void 0:n.length))return;const r=Lt.jh.getAncestor(t,Lt.xK),{key:o}=r.state,a=Lt.jh.getAncestor(r,Lt.gF),i=a.state.children.filter((e=>e.state.key!==o));i.length?a.setState({children:i}):this.renderEmptyState()}));return t.addActivationHandler((()=>()=>{n.unsubscribe()})),t}filterItems(e){const t=Lt.jh.findByKeyAndType(this,"quick-filter",Aa),{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 Lt.xK({body:new Ea({message:"No results"})})]})}renderErrorState(e){this.state.body.setState({autoRows:"480px",children:[new Lt.xK({body:new Sa({message:e.message||e.toString()})})]})}static Component({model:e}){const{body:t,isLoading:n}=e.useState();return n?w().createElement(i.Spinner,null):w().createElement("div",{style:{marginBottom:"2px"}},w().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 Lt.Es({$data:Ai({label:t}),transformations:[Bo,$o]}),hideNoData:!1,headerActions:r,sortItemsFn:$a,body:new Lt.gF({templateColumns:"1fr",autoRows:Ni,isLazy:!0,$behaviors:[new Lt.Gg.K2({key:"metricCrosshairSync",sync:o.DashboardCursorSync.Crosshair})],children:[]})}),this.addActivationHandler(this.onActivate.bind(this))}}class ji extends o.BusEventWithPayload{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(ji,"type","clear-label-from-filters");class Ri extends o.BusEventWithPayload{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(Ri,"type","exclude-label-from-filters");class Ii extends o.BusEventWithPayload{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(Ii,"type","include-label-in-filters");const Di=e=>{const t=(0,i.useStyles2)(Li),{include:n,exclude:o}=function({status:e,label:t,onInclude:n,onExclude:r,onClear:o}){const a="included"===e,i="excluded"===e;return{include:{isSelected:a,tooltip:a?`Clear "${t}" from the filters`:`Include "${t}" in the filters`,onClick:a?o:n},exclude:{isSelected:i,tooltip:i?`Clear "${t}" from the filters`:`Exclude "${t}" in the filters`,onClick:i?o:r}}}(e);return w().createElement("div",{className:t.container},w().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"),w().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"))},_i=(0,S.memo)(Di),Li=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 Fi(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class Bi extends Lt.Bs{getStatus(e){const{key:t,value:n}=this.state.item.queryRunnerParams.filters[0],r=e.find((e=>e.key===t));return r?Yn(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}),Fi(this,"onInclude",(()=>{Ie("g_pyroscope_app_include_action_clicked"),this.publishEvent(new Ii({item:this.state.item}),!0)})),Fi(this,"onExclude",(()=>{Ie("g_pyroscope_app_exclude_action_clicked"),this.publishEvent(new Ri({item:this.state.item}),!0)})),Fi(this,"onClear",(()=>{this.publishEvent(new ji({item:this.state.item}),!0)}))}}function $i({compare:e,onClickCompare:t,onClickClear:n}){const o=(0,i.useStyles2)(Mi),a=e.size<2,s=e.size>0,l=(0,S.useMemo)((()=>{var t,n,r,o;return 2===e.size?`Compare "${null===(r=e.get(lt.BASELINE))||void 0===r?void 0:r.label}" vs "${null===(o=e.get(lt.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(lt.BASELINE)?`Select another panel to compare against "${null===(t=e.get(lt.BASELINE))||void 0===t?void 0:t.label}"`:`Select another panel to compare against "${null===(n=e.get(lt.COMPARISON))||void 0===n?void 0:n.label}"`}),[e]);return w().createElement("div",{className:o.container},w().createElement(i.Button,{"arial-label":"Compare",className:o.compareButton,variant:"primary",disabled:a,onClick:a?L:t,tooltip:l},"Compare (",e.size,"/2)"),w().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:L}))}Fi(Bi,"Component",(({model:e})=>{const{item:t}=e.useState(),{filters:n}=Lt.jh.findByKeyAndType(e,"filters",xo).useState(),r=(0,S.useMemo)((()=>e.getStatus(n)),[n,e]);return w().createElement(_i,{label:t.value,status:r,onInclude:e.onInclude,onExclude:e.onExclude,onClear:e.onClear})}));const Mi=e=>({container:r.css`
display: flex;
align-items: center;
width: ${xi.WIDTH_IN_PIXELS}px;
`,compareButton:r.css`
width: ${xi.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 Vi(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function Ui(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class Gi extends Lt.Bs{onActivate(e){var t,n=this;return(t=function*(){const t=Lt.jh.findByKeyAndType(n,"groupBy",fi);yield t.update(),e&&n.initVariablesAndControls(e),n.renderBody(t);const r=n.subscribeToGroupByChange(),o=n.subscribeToPanelEvents();return()=>{var e;o.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 a=t.apply(e,n);function i(e){Vi(a,r,o,i,s,"next",e)}function s(e){Vi(a,r,o,i,s,"throw",e)}i(void 0)}))})()}initVariablesAndControls(e){const{queryRunnerParams:t,panelType:n}=e,{groupBy:r}=t;if(null==r?void 0:r.label){Lt.jh.findByKeyAndType(this,"groupBy",fi).changeValueTo(r.label)}if(n){Lt.jh.findByKeyAndType(this,"panel-type-switcher",No).setState({panelType:n})}}subscribeToGroupByChange(){const e=Lt.jh.findByKeyAndType(this,"groupBy",fi),t=Lt.jh.findByKeyAndType(this,"quick-filter",Aa);return e.subscribeToState(((n,r)=>{n.value!==(null==r?void 0:r.value)&&(t.clearSearchText(),this.renderBody(e))}))}subscribeToPanelEvents(){const e=this.subscribeToEvent(Ga,(e=>{this.selectLabel(e.payload.item)})),t=this.subscribeToEvent(vi,(e=>{const{compareTarget:t,item:n}=e.payload;this.selectForCompare(t,n)})),n=this.subscribeToEvent(Ii,(e=>{this.includeLabelValueInFilters(e.payload.item)})),r=this.subscribeToEvent(Ri,(e=>{this.excludeLabelValueFromFilters(e.payload.item)})),o=this.subscribeToEvent(ji,(e=>{this.clearLabelValueFromFilters(e.payload.item)}));return{unsubscribe(){o.unsubscribe(),r.unsubscribe(),n.unsubscribe(),t.unsubscribe(),e.unsubscribe()}}}subscribeToPanelTypeChange(){return Lt.jh.findByKeyAndType(this,"panel-type-switcher",No).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(){Lt.jh.findByKeyAndType(this,"quick-filter",Aa).setPlaceholder("Search labels (comma-separated regexes are supported)"),this.setState({body:this.buildSceneLabelNamesGrid()})}buildSceneLabelNamesGrid(){return new Va({key:"service-labels-grid",variableName:"groupBy",mapOptionToItem:(e,t,{serviceName:n,profileMetricId:r,panelType:o})=>{if("all"===e.value)return null;const{value:a,groupBy:i}=JSON.parse(e.value);return{index:t-1,value:a,label:a,queryRunnerParams:{serviceName:n,profileMetricId:r,groupBy:i,filters:[]},panelType:o}},headerActions:e=>[new Xa({type:"select-label",item:e}),new Xa({type:"expand-panel",item:e}),new Fa({item:e})]})}switchToLabelValuesGrid(e){Lt.jh.findByKeyAndType(this,"quick-filter",Aa).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 ki({key:"service-label-values-grid",startColorIndex:t,label:e,headerActions:e=>[new Xa({type:"view-flame-graph",item:e,tooltip:(e,t)=>{const{queryRunnerParams:n,label:r}=e,o=n.profileMetricId||Co(t,"profileMetricId"),a=Co(t,"groupBy");return`View the "${Xr(o).type}" flame graph for "${a}=${r}"`}}),new Bi({item:e}),new Fa({item:e})]})}selectLabel({queryRunnerParams:e}){const t=e.groupBy.label,n=Lt.jh.findByKeyAndType(this,"groupBy",fi);Ft(),n.changeValueTo(t)}includeLabelValueInFilters(e){const[t]=e.queryRunnerParams.filters,n=Lt.jh.findByKeyAndType(this,"filters",xo);n.setState({filters:Eo(n.state.filters,t)})}excludeLabelValueFromFilters(e){const t=Lt.jh.findByKeyAndType(this,"filters",xo),[n]=e.queryRunnerParams.filters;t.setState({filters:So(t.state.filters,n)})}clearLabelValueFromFilters(e){const t=Lt.jh.findByKeyAndType(this,"filters",xo),[n]=e.queryRunnerParams.filters;t.setState({filters:wo(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(lt.BASELINE),n=e.get(lt.COMPARISON),r=Lt.jh.findAllObjects(this,(e=>e instanceof xi));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}),Ui(this,"onClickCompareButton",(()=>{Ie("g_pyroscope_app_compare_link_clicked");const{compare:e}=this.state,{filters:t}=_a(this,e.get(lt.BASELINE)),{filters:n}=_a(this,e.get(lt.COMPARISON));this.publishEvent(new yi({useAncestorTimeRange:!0,clearDiffRange:!0,baselineFilters:t,comparisonFilters:n}),!0)})),Ui(this,"onClickClearCompareButton",(()=>{this.clearCompare(),this.updateStatsPanels()})),this.addActivationHandler((()=>{this.onActivate(e)}))}}Ui(Gi,"Component",(({model:e})=>{const t=(0,i.useStyles2)(qi),{body:n,compare:r}=e.useState(),o=Lt.jh.findByKeyAndType(e,"groupBy",fi),{value:a}=o.useState(),s=(0,S.useMemo)((()=>"all"===a?Lt.jh.findByKeyAndType(e,"profiles-explorer",sp).state.gridControls:[Lt.jh.findByKeyAndType(e,"quick-filter",Aa),Lt.jh.findByKeyAndType(e,"layout-switcher",Pa),Lt.jh.findByKeyAndType(e,"no-data-switcher",Ca)]),[a,e]);return w().createElement("div",{className:t.container,"data-testid":"groupByLabelsContainer"},w().createElement(o.Component,{model:o}),w().createElement("div",{className:t.sceneControls},w().createElement(i.Stack,{wrap:"wrap"},"all"!==a&&w().createElement($i,{compare:r,onClickCompare:e.onClickCompareButton,onClickClear:e.onClickClearCompareButton}),s.map((e=>w().createElement(e.Component,{key:e.state.key,model:e}))))),n&&w().createElement(n.Component,{model:n}))}));const qi=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 Ki(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function zi(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Wi(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){zi(e,t,n[t])}))}return e}function Hi(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 Yi extends Lt.Bs{onActivate(e){e&&this.initVariables(e);const t=Lt.jh.findByKeyAndType(this,"profileMetricId",ao);t.setState({query:ao.QUERY_SERVICE_NAME_DEPENDENT}),t.update(!0);const n=this.subscribeToPanelEvents();return()=>{n.unsubscribe(),t.setState({query:ao.QUERY_DEFAULT}),t.update(!0)}}initVariables(e){const{queryRunnerParams:t}=e,{serviceName:n,profileMetricId:r,filters:o}=t;if(n){Lt.jh.findByKeyAndType(this,"serviceName",co).changeValueTo(n)}if(r){Lt.jh.findByKeyAndType(this,"profileMetricId",ao).changeValueTo(r)}if(o){Lt.jh.findByKeyAndType(this,"filters",xo).setState({filters:o})}}subscribeToPanelEvents(){var e=this;const t=this.subscribeToEvent(Ua,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 a=t.apply(e,n);function i(e){Ki(a,r,o,i,s,"next",e)}function s(e){Ki(a,r,o,i,s,"throw",e)}i(void 0)}))});return function(e){return n.apply(this,arguments)}}()),n=this.subscribeToEvent(Ga,(()=>{this.state.drawer.close()}));return{unsubscribe(){n.unsubscribe(),t.unsubscribe()}}}getVariablesAndGridControls(){return{variables:[Lt.jh.findByKeyAndType(this,"serviceName",co),Lt.jh.findByKeyAndType(this,"profileMetricId",ao),Lt.jh.findByKeyAndType(this,"filters",xo)],gridControls:[]}}openExpandedPanelDrawer(e){var t;const n=Co(this,"serviceName"),r=Co(this,"profileMetricId"),o=`${Xr(r).description||ra(r)}, grouped by ${(null===(t=e.queryRunnerParams.groupBy)||void 0===t?void 0:t.label)||"?"}`;this.state.drawer.open({title:n,body:ua(e.panelType,{displayAllValues:!0,legendPlacement:"right",item:Hi(Wi({},e),{label:o}),headerActions:()=>[new Xa({type:"select-label",item:e}),new Fa({item:e})]})})}static Component({model:e}){const{body:t,drawer:n}=e.useState();return w().createElement(w().Fragment,null,w().createElement(t.Component,{model:t}),w().createElement(n.Component,{model:n}))}constructor({item:e}){super({key:"explore-service-labels",body:new Lt.G1({direction:"column",$behaviors:[new Lt.Gg.K2({key:"metricCrosshairSync",sync:o.DashboardCursorSync.Crosshair})],children:[new Lt.vA({minHeight:bi.MIN_HEIGHT,body:new bi({item:e,headerActions:e=>e.queryRunnerParams.groupBy?[new Xa({type:"view-flame-graph",item:e}),new Xa({type:"expand-panel",item:e}),new Fa({item:e})]:[new Xa({type:"view-flame-graph",item:e}),new Fa({item:e})],supportGroupBy:!0})}),new Lt.vA({body:new Gi({item:e})})]}),drawer:new ri}),this.addActivationHandler(this.onActivate.bind(this,e))}}class Zi extends Lt.Bs{onActivate(e){Lt.jh.findByKeyAndType(this,"quick-filter",Aa).setPlaceholder("Search profile types (comma-separated regexes are supported)"),e&&this.initVariables(e)}initVariables(e){if(e.queryRunnerParams.serviceName){Lt.jh.findByKeyAndType(this,"serviceName",co).changeValueTo(e.queryRunnerParams.serviceName)}}getVariablesAndGridControls(){return{variables:[Lt.jh.findByKeyAndType(this,"serviceName",co)],gridControls:[Lt.jh.findByKeyAndType(this,"quick-filter",Aa),Lt.jh.findByKeyAndType(this,"layout-switcher",Pa)]}}static Component({model:e}){const{body:t}=e.useState();return w().createElement(t.Component,{model:t})}constructor({item:e}){super({key:"explore-service-profile-types",$variables:new Lt.Pj({variables:[new ao({query:ao.QUERY_SERVICE_NAME_DEPENDENT,skipUrlSync:!0})]}),body:new Va({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:Ao.TIMESERIES}),headerActions:e=>[new Xa({type:"view-labels",item:e}),new Xa({type:"view-flame-graph",item:e}),new Fa({item:e})]})}),this.addActivationHandler(this.onActivate.bind(this,e))}}function Xi(e,t){return{from:e,to:t,value:{from:(0,o.dateTimeParse)(e),to:(0,o.dateTimeParse)(t),raw:{from:e,to:t}}}}const Ji=()=>Xi("now-30m","now");class Qi extends Lt.yP{reset(){this.setState({value:void 0})}constructor(){super({key:"spanSelector",name:"spanSelector",label:"Span selector",value:void 0})}}function es(e,t){if(t){const n=e.services.get(t)||new Map;return Array.from(n.values()).sort(((e,t)=>Er(t.group,e.group))).map((({id:e,type:t,group:n})=>({value:e,text:`${t} (${n})`})))}return Array.from(e.profileMetrics.keys()).map((e=>Xr(e))).sort(((e,t)=>Er(t.group,e.group))).map((({id:e,type:t,group:n})=>({value:e,text:`${t} (${n})`})))}function ts(e,t){if(t){const n=e.profileMetrics.get(t)||new Set;return Array.from(n).sort(Er).map((e=>({text:e,value:e})))}return Array.from(e.services.keys()).sort(Er).map((e=>({text:e,value:e})))}class ns{static build(e,t){const n=`${e}-${t.name}`,r=ns.cache.get(n);if(r instanceof t)return r;const o=new t({dataSourceUid:e});return ns.cache.set(n,o),o}}function rs(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 os(e){const t=new Map,n=new Map;if(!e.labelsSet)return j.warn("Pyroscope SeriesApiClient: no data received!"),{services:t,profileMetrics:n};for(const{labels:r}of e.labelsSet){const[e,o]=rs(r);if(!e||!o){j.warn('Pyroscope ServicesApiClient: "service_name" and/or "__profile_type__" are missing in the labels received!',r);continue}const a=t.get(e)||new Map;a.set(o,Xr(o)),t.set(e,a);const i=n.get(o)||new Set;i.add(e),n.set(o,i)}return{services:t,profileMetrics:n}}function as(e,t,n,r,o,a,i){try{var s=e[a](i),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}(ns,"cache",new Map);class is extends Xt{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(os)},function(){var e=this,n=arguments;return new Promise((function(r,o){var a=t.apply(e,n);function i(e){as(a,r,o,i,s,"next",e)}function s(e){as(a,r,o,i,s,"throw",e)}i(void 0)}))})()}constructor(e){super(e)}}function ss(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}const ls=new class extends on{list(e){var t,n=this;return(t=function*(){const{from:t,to:r}=Ko(e.timeRange),o=[n.apiClient.baseUrl,t,r],a=n.cacheClient.get(o);if(a){const{services:e,profileMetrics:t}=yield a;return e.size||t.size||n.cacheClient.delete(o),{services:e,profileMetrics:t}}const i=n.apiClient.list({from:t,to:r});n.cacheClient.set(o,i);try{const{services:e,profileMetrics:t}=yield i;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 a=t.apply(e,n);function i(e){ss(a,r,o,i,s,"next",e)}function s(e){ss(a,r,o,i,s,"throw",e)}i(void 0)}))})()}constructor(e){super(e)}}({cacheClient:new tn});function cs(e,t,n,r,o,a,i){try{var s=e[a](i),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 a=e.apply(t,n);function i(e){cs(a,r,o,i,s,"next",e)}function s(e){cs(a,r,o,i,s,"throw",e)}i(void 0)}))}}class ds extends Lt.UU{fetchSeries(e,t,n){return us((function*(){ls.setApiClient(ns.build(e,is));try{return yield ls.list({timeRange:t})}catch(e){throw j.error(e,{info:"Error while loading Pyroscope series!",variableName:n||""}),e}}))()}query(){return us((function*(){return{state:o.LoadingState.Done,data:[{name:"PyroscopeSeries",fields:[{name:"PyroscopeSeries",type:o.FieldType.other,values:[],config:{}}],length:0}]}}))()}metricFindQuery(e,t){var n=this;return us((function*(){var r,o,a;const i=null===(o=t.scopedVars)||void 0===o||null===(r=o.__sceneObject)||void 0===r?void 0:r.value,s=Lt.jh.interpolate(i,"$dataSource"),l=Lt.jh.interpolate(i,"$serviceName"),c=Lt.jh.interpolate(i,"$profileMetricId"),u=yield n.fetchSeries(s,t.range,null===(a=t.variable)||void 0===a?void 0:a.name);switch(e){case"$dataSource and all services":return ts(u);case"$dataSource and all profile metrics":return es(u);case"$dataSource and only $profileMetricId services":return ts(u,c);case"$dataSource and only $serviceName profile metrics":return es(u,l);default:throw new TypeError(`Unsupported query "${e}"!`)}}))()}testDatasource(){return us((function*(){return{status:"success",message:"OK"}}))()}constructor(){super(eo.type,eo.uid)}}var ps=n(9215),ms=n(3518),fs=n(3632),hs=n(411),gs=n(1298);const bs=(0,hs.w)("ChR0eXBlcy92MS90eXBlcy5wcm90bxIIdHlwZXMudjEiKAoJTGFiZWxQYWlyEgwKBG5hbWUYASABKAkSDQoFdmFsdWUYAiABKAkiewoLUHJvZmlsZVR5cGUSCgoCSUQYASABKAkSDAoEbmFtZRgCIAEoCRITCgtzYW1wbGVfdHlwZRgEIAEoCRITCgtzYW1wbGVfdW5pdBgFIAEoCRITCgtwZXJpb2RfdHlwZRgGIAEoCRITCgtwZXJpb2RfdW5pdBgHIAEoCSItCgZMYWJlbHMSIwoGbGFiZWxzGAEgAygLMhMudHlwZXMudjEuTGFiZWxQYWlyIk4KBlNlcmllcxIjCgZsYWJlbHMYASADKAsyEy50eXBlcy52MS5MYWJlbFBhaXISHwoGcG9pbnRzGAIgAygLMg8udHlwZXMudjEuUG9pbnQiWwoFUG9pbnQSDQoFdmFsdWUYASABKAESEQoJdGltZXN0YW1wGAIgASgDEjAKC2Fubm90YXRpb25zGAMgAygLMhsudHlwZXMudjEuUHJvZmlsZUFubm90YXRpb24iLwoRUHJvZmlsZUFubm90YXRpb24SCwoDa2V5GAEgASgJEg0KBXZhbHVlGAIgASgJIlAKEkxhYmVsVmFsdWVzUmVxdWVzdBIMCgRuYW1lGAEgASgJEhAKCG1hdGNoZXJzGAIgAygJEg0KBXN0YXJ0GAMgASgDEgsKA2VuZBgEIAEoAyIkChNMYWJlbFZhbHVlc1Jlc3BvbnNlEg0KBW5hbWVzGAEgAygJIkEKEUxhYmVsTmFtZXNSZXF1ZXN0EhAKCG1hdGNoZXJzGAEgAygJEg0KBXN0YXJ0GAIgASgDEgsKA2VuZBgDIAEoAyIjChJMYWJlbE5hbWVzUmVzcG9uc2USDQoFbmFtZXMYASADKAkikQEKCUJsb2NrSW5mbxIMCgR1bGlkGAEgASgJEhAKCG1pbl90aW1lGAIgASgDEhAKCG1heF90aW1lGAMgASgDEi0KCmNvbXBhY3Rpb24YBCABKAsyGS50eXBlcy52MS5CbG9ja0NvbXBhY3Rpb24SIwoGbGFiZWxzGAUgAygLMhMudHlwZXMudjEuTGFiZWxQYWlyIkIKD0Jsb2NrQ29tcGFjdGlvbhINCgVsZXZlbBgBIAEoBRIPCgdzb3VyY2VzGAIgAygJEg8KB3BhcmVudHMYAyADKAkiXAoSU3RhY2tUcmFjZVNlbGVjdG9yEiUKCWNhbGxfc2l0ZRgBIAMoCzISLnR5cGVzLnYxLkxvY2F0aW9uEh8KBmdvX3BnbxgCIAEoCzIPLnR5cGVzLnYxLkdvUEdPIhgKCExvY2F0aW9uEgwKBG5hbWUYASABKAkiOgoFR29QR08SFgoOa2VlcF9sb2NhdGlvbnMYASABKA0SGQoRYWdncmVnYXRlX2NhbGxlZXMYAiABKAgiGAoWR2V0UHJvZmlsZVN0YXRzUmVxdWVzdCJqChdHZXRQcm9maWxlU3RhdHNSZXNwb25zZRIVCg1kYXRhX2luZ2VzdGVkGAEgASgIEhsKE29sZGVzdF9wcm9maWxlX3RpbWUYAiABKAMSGwoTbmV3ZXN0X3Byb2ZpbGVfdGltZRgDIAEoAyprChlUaW1lU2VyaWVzQWdncmVnYXRpb25UeXBlEiQKIFRJTUVfU0VSSUVTX0FHR1JFR0FUSU9OX1RZUEVfU1VNEAASKAokVElNRV9TRVJJRVNfQUdHUkVHQVRJT05fVFlQRV9BVkVSQUdFEAFiBnByb3RvMw");const ys=(0,hs.w)("CiFzZXR0aW5ncy92MS9yZWNvcmRpbmdfcnVsZXMucHJvdG8SC3NldHRpbmdzLnYxIiUKF0dldFJlY29yZGluZ1J1bGVSZXF1ZXN0EgoKAmlkGAEgASgJIkQKGEdldFJlY29yZGluZ1J1bGVSZXNwb25zZRIoCgRydWxlGAEgASgLMhouc2V0dGluZ3MudjEuUmVjb3JkaW5nUnVsZSIbChlMaXN0UmVjb3JkaW5nUnVsZXNSZXF1ZXN0IkcKGkxpc3RSZWNvcmRpbmdSdWxlc1Jlc3BvbnNlEikKBXJ1bGVzGAEgAygLMhouc2V0dGluZ3MudjEuUmVjb3JkaW5nUnVsZSL4AQoaVXBzZXJ0UmVjb3JkaW5nUnVsZVJlcXVlc3QSCgoCaWQYASABKAkSEwoLbWV0cmljX25hbWUYAiABKAkSEAoIbWF0Y2hlcnMYAyADKAkSEAoIZ3JvdXBfYnkYBCADKAkSLAoPZXh0ZXJuYWxfbGFiZWxzGAUgAygLMhMudHlwZXMudjEuTGFiZWxQYWlyEhIKCmdlbmVyYXRpb24YBiABKAMSPQoRc3RhY2t0cmFjZV9maWx0ZXIYByABKAsyHS5zZXR0aW5ncy52MS5TdGFja3RyYWNlRmlsdGVySACIAQFCFAoSX3N0YWNrdHJhY2VfZmlsdGVyIkcKG1Vwc2VydFJlY29yZGluZ1J1bGVSZXNwb25zZRIoCgRydWxlGAEgASgLMhouc2V0dGluZ3MudjEuUmVjb3JkaW5nUnVsZSIoChpEZWxldGVSZWNvcmRpbmdSdWxlUmVxdWVzdBIKCgJpZBgBIAEoCSIdChtEZWxldGVSZWNvcmRpbmdSdWxlUmVzcG9uc2UilgIKDVJlY29yZGluZ1J1bGUSCgoCaWQYASABKAkSEwoLbWV0cmljX25hbWUYAiABKAkSFAoMcHJvZmlsZV90eXBlGAMgASgJEhAKCG1hdGNoZXJzGAQgAygJEhAKCGdyb3VwX2J5GAUgAygJEiwKD2V4dGVybmFsX2xhYmVscxgGIAMoCzITLnR5cGVzLnYxLkxhYmVsUGFpchISCgpnZW5lcmF0aW9uGAcgASgDEj0KEXN0YWNrdHJhY2VfZmlsdGVyGAggASgLMh0uc2V0dGluZ3MudjEuU3RhY2t0cmFjZUZpbHRlckgAiAEBEhMKC3Byb3Zpc2lvbmVkGAkgASgIQhQKEl9zdGFja3RyYWNlX2ZpbHRlciJrChBTdGFja3RyYWNlRmlsdGVyEkUKDWZ1bmN0aW9uX25hbWUYASABKAsyKS5zZXR0aW5ncy52MS5TdGFja3RyYWNlRmlsdGVyRnVuY3Rpb25OYW1lSACIAQFCEAoOX2Z1bmN0aW9uX25hbWUiYwocU3RhY2t0cmFjZUZpbHRlckZ1bmN0aW9uTmFtZRIVCg1mdW5jdGlvbl9uYW1lGAEgASgJEiwKC21ldHJpY190eXBlGAIgASgOMhcuc2V0dGluZ3MudjEuTWV0cmljVHlwZSKQAgoSUmVjb3JkaW5nUnVsZVN0b3JlEgoKAmlkGAEgASgJEhMKC21ldHJpY19uYW1lGAIgASgJEh4KFnByb21ldGhldXNfZGF0YV9zb3VyY2UYAyABKAkSEAoIbWF0Y2hlcnMYBCADKAkSEAoIZ3JvdXBfYnkYBSADKAkSLAoPZXh0ZXJuYWxfbGFiZWxzGAYgAygLMhMudHlwZXMudjEuTGFiZWxQYWlyEhIKCmdlbmVyYXRpb24YByABKAMSPQoRc3RhY2t0cmFjZV9maWx0ZXIYCCABKAsyHS5zZXR0aW5ncy52MS5TdGFja3RyYWNlRmlsdGVySACIAQFCFAoSX3N0YWNrdHJhY2VfZmlsdGVyIlkKE1JlY29yZGluZ1J1bGVzU3RvcmUSLgoFcnVsZXMYASADKAsyHy5zZXR0aW5ncy52MS5SZWNvcmRpbmdSdWxlU3RvcmUSEgoKZ2VuZXJhdGlvbhgCIAEoAyoXCgpNZXRyaWNUeXBlEgkKBVRPVEFMEAAyuwMKFVJlY29yZGluZ1J1bGVzU2VydmljZRJhChBHZXRSZWNvcmRpbmdSdWxlEiQuc2V0dGluZ3MudjEuR2V0UmVjb3JkaW5nUnVsZVJlcXVlc3QaJS5zZXR0aW5ncy52MS5HZXRSZWNvcmRpbmdSdWxlUmVzcG9uc2UiABJnChJMaXN0UmVjb3JkaW5nUnVsZXMSJi5zZXR0aW5ncy52MS5MaXN0UmVjb3JkaW5nUnVsZXNSZXF1ZXN0Gicuc2V0dGluZ3MudjEuTGlzdFJlY29yZGluZ1J1bGVzUmVzcG9uc2UiABJqChNVcHNlcnRSZWNvcmRpbmdSdWxlEicuc2V0dGluZ3MudjEuVXBzZXJ0UmVjb3JkaW5nUnVsZVJlcXVlc3QaKC5zZXR0aW5ncy52MS5VcHNlcnRSZWNvcmRpbmdSdWxlUmVzcG9uc2UiABJqChNEZWxldGVSZWNvcmRpbmdSdWxlEicuc2V0dGluZ3MudjEuRGVsZXRlUmVjb3JkaW5nUnVsZVJlcXVlc3QaKC5zZXR0aW5ncy52MS5EZWxldGVSZWNvcmRpbmdSdWxlUmVzcG9uc2UiAGIGcHJvdG8z",[bs]),vs=(0,gs.Z)(ys,9),Es=(0,gs.Z)(ys,10);var Ss=function(e){return e[e.TOTAL=0]="TOTAL",e}({});function ws(e,t,n,r,o,a,i){try{var s=e[a](i),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 a=e.apply(t,n);function i(e){ws(a,r,o,i,s,"next",e)}function s(e){ws(a,r,o,i,s,"throw",e)}i(void 0)}))}}const Ps=new class extends q{get(){var e=this,t=()=>super.fetch;return Os((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 a=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:a,readonly:e.provisioned}}(e))):[]))}))()}create(e){var t=this,n=()=>super.fetch;return Os((function*(){const r=e.serviceName?[`{ service_name="${e.serviceName}" }`]:[];let o={metricName:e.metricName,matchers:[...r,`{ __profile_type__="${e.profileType}"}`,...e.matchers||[]],groupBy:e.groupBy||[]};return e.functionName&&(o.stacktraceFilter=(0,fs.v)(vs,{functionName:(0,fs.v)(Es,{functionName:e.functionName,metricType:Ss.TOTAL})})),n().call(t,"/settings.v1.RecordingRulesService/UpsertRecordingRule",{method:"POST",body:JSON.stringify(o)}).then((e=>e.json()))}))()}remove(e){var t=this,n=()=>super.fetch;return Os((function*(){return n().call(t,"/settings.v1.RecordingRulesService/DeleteRecordingRule",{method:"POST",body:JSON.stringify({id:e.id})}).then((e=>e.json()))}))()}};var xs=n(6667);function Cs(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function Ts({enabled:e}={}){const t=(0,E.jE)(),{isFetching:n,error:r,data:o}=(0,K.I)({enabled:e,queryKey:["recording_rules"],queryFn:()=>Ps.get()}),{mutateAsync:a}=(0,xs.n)({mutationFn:e=>Ps.create(e),networkMode:"always"}),{mutateAsync:i}=(0,xs.n)({mutationFn:function(){var e,n=(e=function*(e){yield Ps.remove(e),yield t.invalidateQueries({queryKey:["recording_rules"]})},function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){Cs(a,r,o,i,s,"next",e)}function s(e){Cs(a,r,o,i,s,"throw",e)}i(void 0)}))});return function(e){return n.apply(this,arguments)}}(),networkMode:"always"});return{isFetching:n,error:Ps.isAbortError(r)?null:r,recordingRules:o,mutate:a,remove:i}}function As(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function Ns(){const{recordingRules:e,error:t,mutate:n}=Ts();return{data:{recordingRules:e,fetchError:t},actions:{save(e){return(t=function*(){try{yield n(e),Ve([`Recording rule ${e.metricName} created successfully!`])}catch(t){$e(t,[`Failed to save recording rule ${e.metricName}.`])}},function(){var e=this,n=arguments;return new Promise((function(r,o){var a=t.apply(e,n);function i(e){As(a,r,o,i,s,"next",e)}function s(e){As(a,r,o,i,s,"throw",e)}i(void 0)}))})();var t}}}}function ks(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function js(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Rs(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){js(e,t,n[t])}))}return e}function Is(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 Ds="profiles_recorded_";class _s extends Lt.Bs{constructor(){super({})}}js(_s,"Component",(function({model:e,isModalOpen:t,onDismiss:n,onCreated:o,functionName:a}){const[s,l]=(0,S.useState)([]),{actions:c}=Ns(),u=Xr(Lt.jh.findByKeyAndType(e,"profileMetricId",ao).state.value),d=function(e){const t=Lt.jh.findByKeyAndType(e,"serviceName",co).state.value,n=Lt.jh.findByKeyAndType(e,"profiles-explorer",sp).useState().explorationType;return n===ip.ALL_SERVICES||n===ip.FAVORITES?void 0:t}(e),p=Lt.jh.findByKeyAndType(e,"filters",xo).state.filters,m=p.map((e=>`${e.key}${e.operator}"${e.value}"`)).join(", "),f=(null==d?void 0:d.toString())||"",h=!f,{register:g,handleSubmit:b,control:y,formState:{errors:v}}=(0,ps.mN)({mode:"onChange",shouldUnregister:!0,values:{functionName:a,metricName:"",labels:h?[{label:"service_name",value:"service_name"}]:[],serviceName:f,matcher:"",profileType:u.id}}),E=function(){var e,t=(e=function*(e){const t={id:"",metricName:Ds+e.metricName,serviceName:e.serviceName,profileType:e.profileType,matchers:m?[`{${m}}`]:[],groupBy:e.labels?e.labels.map((e=>{var t;return null!==(t=e.value)&&void 0!==t?t:""})):[],functionName:e.functionName,readonly:!1};yield c.save(t),o()},function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){ks(a,r,o,i,s,"next",e)}function s(e){ks(a,r,o,i,s,"throw",e)}i(void 0)}))});return function(e){return t.apply(this,arguments)}}();return(0,ms.A)((()=>{const t=Lt.jh.getTimeRange(e).state.value;mn.listLabels({query:`{${m}}`,from:1e3*t.from.unix(),to:1e3*t.to.unix()}).then((e=>{let t=e.map((e=>e.value));h&&(t=["service_name",...t]),l(t)}))})),w().createElement(i.Modal,{title:"Create recording rule",isOpen:t,onDismiss:n,"data-testid":"Create recording rule modal"},w().createElement("form",{onSubmit:b(E)},w().createElement(i.Field,{label:"Metric name",description:`Prometheus metric name (automatically prefixed with ${Ds}).`,error:Ls(v.metricName),invalid:!!v.metricName},w().createElement("div",{className:(0,r.css)({display:"flex"})},w().createElement("div",{className:(0,r.css)({alignContent:"center",fontFamily:"monospace"})},Ds),w().createElement(i.Input,Rs({className:(0,r.css)({input:{fontFamily:"monospace",paddingLeft:0}}),placeholder:`${u.type}_${(f||"name").toString().replace(/[^a-zA-Z0-9_]/g,"_")}`,"aria-label":"Metric name",required:!0,autoFocus:!0},g("metricName",{required:"Metric name is required.",pattern:{value:/^[a-zA-Z_][a-zA-Z0-9_]*$/,message:"Invalid metric name."}}))))),w().createElement(i.Field,{label:"Additional labels",description:"Additional profiling labels to forward to the metric"},w().createElement(ps.xI,{name:"labels",control:y,render:({field:e})=>w().createElement(i.MultiSelect,Is(Rs({},e),{options:s.map((e=>({label:e,value:e}))),toggleAllOptions:{enabled:!0},closeMenuOnSelect:!1,hideSelectedOptions:!1}))})),w().createElement(i.Divider,null),w().createElement(i.Field,{label:"Service name","data-testid":"Create recording rule modal service name field"},f?w().createElement("div",null,`${f}`):w().createElement(i.Text,{element:"span",color:"secondary"},"All services")),w().createElement("input",Rs({type:"text",hidden:!0},g("serviceName"))),w().createElement(i.Field,{label:"Profile type"},w().createElement("div",null,`${u.group}/${u.type}`)),w().createElement("input",Rs({type:"text",hidden:!0},g("profileType"))),w().createElement(i.Field,{label:"Function name",description:"Optional function name to filter the recording rule"},w().createElement(i.Input,Rs({"aria-label":"Function name",placeholder:"Leave empty for total aggregation"},g("functionName")))),w().createElement(i.Field,{label:"Filters",description:"Filters selected in the main view will be applied to this rule"},w().createElement("div",null,0===p.length?"No filters selected":m)),w().createElement(i.Modal.ButtonRow,null,w().createElement(i.Button,{variant:"secondary",fill:"outline",onClick:n,"aria-label":"Cancel"},"Cancel"),w().createElement(i.Button,{variant:"primary",type:"submit"},"Create"))))}));const Ls=e=>{const t=(0,i.useStyles2)(Fs);if(void 0!==e&&void 0!==e.message)return"pattern"===e.type?w().createElement("span",null,w().createElement("span",null,"Metric name is invalid, it must have the following properties:"),w().createElement("ul",{className:t.errorList},w().createElement("li",null,"Only contain alphanumeric characters or underscores"),w().createElement("li",null,"Must not begin with a number"))):w().createElement("span",null,e.message)},Fs=e=>({errorList:r.css`
padding-left: ${e.spacing(2)};
`});class Bs extends o.BusEventWithPayload{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(Bs,"type","enable-sync-timeranges");class $s extends o.BusEventWithPayload{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}($s,"type","sync-refresh");class Ms extends o.BusEventWithPayload{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(Ms,"type","sync-timeranges");class Vs extends Lt.KE{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(Vs,"Component",(function({model:e}){const{hidePicker:t,isOnCanvas:n}=e.useState(),r=Lt.jh.getTimeRange(e),o=r.getTimeZone(),a=r.useState();return t?null:w().createElement(i.TimeRangePicker,{isOnCanvas:null==n||n,value:a.value,onChange:r.onTimeRangeChange,timeZone:o,fiscalYearStartMonth:a.fiscalYearStartMonth,onMoveBackward:e.onMoveBackward,onMoveForward:e.onMoveForward,onZoom:e.onZoom,onChangeTimeZone:r.onTimeZoneChange,onChangeFiscalYearStartMonth:e.onChangeFiscalYearStartMonth,isSynced:!1})}));const Us=/^\d+[yYmMsSwWhHdD]$/;function Gs(e){if("string"!=typeof e)return null;if(-1!==e.indexOf("now"))return e;if(Us.test(e))return e;if(8===e.length){const t=(0,o.toUtc)(e,"YYYYMMDD");if(t.isValid())return t.toISOString()}else if(15===e.length){const t=(0,o.toUtc)(e,"YYYYMMDDTHHmmss");if(t.isValid())return t.toISOString()}else if(24===e.length){return(0,o.toUtc)(e).toISOString()}const t=parseInt(e,10);return isNaN(t)?null:(0,o.toUtc)(t).toISOString()}function qs(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Ks(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 zs extends o.MutableDataFrame{addRange(e){this.add(Ks(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){qs(e,t,n[t])}))}return e}({},e),{isRegion:!0}))}constructor(){super(),[{name:"time",type:o.FieldType.time},{name:"timeEnd",type:o.FieldType.time},{name:"isRegion",type:o.FieldType.boolean},{name:"color",type:o.FieldType.other},{name:"text",type:o.FieldType.string}].forEach((e=>this.addField(e)))}}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}function Hs(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){Ws(e,t,n[t])}))}return e}function Ys(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 Zs=function(e){return e.ANNOTATIONS="annotations",e.DEFAULT="default",e}({});const Xs={from:(0,o.dateTime)(0),to:(0,o.dateTime)(0),raw:{from:"",to:""}};class Js extends Lt.Bs{onActivate(){var e;this.setState((0,Vt.omit)(this.getAncestorTimeRange().state,"key")),this._subs.add(this.getAncestorTimeRange().subscribeToState((e=>{this.setState((0,Vt.omit)(e,"key"))}))),this._subs.add(null===(e=this.getTimeseries().state.$data)||void 0===e?void 0:e.subscribeToState(((e,t)=>{var n,r,a,i,s,l;e.data&&e.data.state===o.LoadingState.Done&&((null===(n=e.data.annotations)||void 0===n?void 0:n.length)||(null===(a=t.data)||void 0===a||null===(r=a.annotations)||void 0===r?void 0:r.length)?!(null===(i=e.data.annotations)||void 0===i?void 0:i.length)&&(null===(l=t.data)||void 0===l||null===(s=l.annotations)||void 0===s?void 0:s.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 Lt.jh.getTimeRange(this.parent.parent)}getTimeseries(){try{const e=Lt.jh.getAncestor(this,Lt.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 a=new zs;a.addRange({color:t,text:n,time:1e3*e.from.unix(),timeEnd:1e3*e.to.unix()}),null==r||r.setState({data:Ys(Hs({},o),{annotations:[a]})})}setAnnotationTimeRange(e,t=!1){this.setState({annotationTimeRange:e}),t&&this.updateTimeseriesAnnotation()}nullifyAnnotationTimeRange(){this.setAnnotationTimeRange(Xs)}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,a;this.setAnnotationTimeRange(this.buildAnnotationTimeRange(null!==(o=Gs(t))&&void 0!==o?o:r.from,null!==(a=Gs(n))&&void 0!==a?a:r.to))}buildAnnotationTimeRange(e,t){return function(e,t,n,r,a){const i=a&&"now"===t;return{from:o.dateMath.parse(e,!1,n,r),to:o.dateMath.parse(i?"now-"+a: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(Hs({from:Xs.raw.from,to:Xs.raw.to,value:Xs,annotationTimeRange:Xs},e)),Ws(this,"_variableDependency",new Lt.Sh(this,{variableNames:["dataSource","serviceName"],onReferencedVariableValueChanged:()=>{this.nullifyAnnotationTimeRange(),this.updateTimeseriesAnnotation()}})),Ws(this,"_urlSync",new Lt.So(this,{keys:["diffFrom","diffTo"]})),this.addActivationHandler(this.onActivate.bind(this))}}class Qs extends o.BusEventWithPayload{}function el(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}(Qs,"type","switch-timerange-selection-mode");var tl=function(e){return e.TIMEPICKER="timepicker",e.FLAMEGRAPH="flame-graph",e}({});class nl extends Lt.Bs{constructor(){super({mode:"flame-graph"}),el(this,"onChange",(e=>{this.setState({mode:e}),this.publishEvent(new Qs({mode:e}),!0)}))}}el(nl,"OPTIONS",[{label:"Time picker",value:"timepicker"},{label:"Flame graph",value:"flame-graph"}]),el(nl,"Component",(({model:e})=>{const t=(0,i.useStyles2)(rl),{mode:n}=e.useState();return w().createElement("div",{className:t.container},w().createElement("label",{className:t.label},w().createElement("span",null,"Range selection mode "),w().createElement(i.Tooltip,{content:w().createElement("div",{className:t.tooltip},w().createElement("div",null,"Use these buttons to change the behaviour when selecting a range with the mouse on the time series:"),w().createElement("dl",null,w().createElement("dt",null,"Time picker"),w().createElement("dd",null,"Time range zoom in (default behaviour)"),w().createElement("dt",null,"Flame graph"),w().createElement("dd",null,"Time range for building the flame graph (the stack traces will be retrieved only for the selected range)"))),placement:"top"},w().createElement(i.Icon,{name:"question-circle"}))),w().createElement(i.RadioButtonGroup,{size:"sm",options:nl.OPTIONS,value:n,onChange:e.onChange,"aria-label":"Range selection mode"}))}));const rl=e=>({container:r.css`
display: flex;
flex-direction: column;
`,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 ol({filterKey:e}){return _o(new Lt.dt({datasource:Qr,queries:[{refId:`$profileMetricId-$serviceName-${e}}`,queryType:"metrics",profileTypeId:"$profileMetricId",labelSelector:`{service_name="$serviceName",$${e}}`}]}))}var al=n(4308),il=n.n(al);const sl={COLOR:il()("#d066d4"),OVERLAY:il()("#d066d4").alpha(.3)},ll={COLOR:il()("#1398f6"),OVERLAY:il()("#1398f6").alpha(.3)};function cl(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ul(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){cl(e,t,n[t])}))}return e}function dl(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 pl extends Lt.Bs{onActivate(e,t,n){const{$timeRange:r,timeseriesPanel:o,filterKey:a}=this.state;if(t&&this.setDiffRange(null),e&&r.setState((0,Vt.omit)(this.getAncestorTimeRange().state,"key")),n.length){Lt.jh.findByKey(this,a).setState({filters:n})}o.updateItem({label:this.buildTimeseriesTitle()});const i=this.subscribeToEvents();return()=>{i.unsubscribe()}}static buildTimeSeriesPanel({target:e,filterKey:t,title:n,color:r}){const o=new ca({item:{index:0,value:e,label:"",queryRunnerParams:{},panelType:Ao.TIMESERIES},data:new Lt.Es({$data:ol({filterKey:t}),transformations:[Bo,$o]}),overrides:e=>pl.buildSeriesOverrides(e,r),headerActions:()=>[new nl]});return pl.configureTimeRange(o,e,n),o}static buildSeriesOverrides(e,t){return e.map((e=>{const n=e.fields[1],r=Io(e,"allValuesSum")||0,a=[{id:"displayName",value:`${pl.getProperLabel(e)} = ${pl.formatTotalValue(r,n.config.unit||"short")}`},{id:"color",value:{mode:"fixed",fixedColor:t}}];return{matcher:{id:o.FieldMatcherID.byFrameRefID,options:e.refId},properties:a}}))}static getProperLabel(e){const t=Vo("",e).match(/^(avg|total)/);return t?t[1]:"total"}static formatTotalValue(e,t){const n=t||"short",r=(0,o.getValueFormat)(n)(e);return`${r.text}${r.suffix}`}static configureTimeRange(e,t,n){e.state.body.setState({$timeRange:new Js({key:`${t}-annotation-timerange`,mode:Zs.ANNOTATIONS,annotationColor:t===lt.BASELINE?sl.OVERLAY.toString():ll.OVERLAY.toString(),annotationTitle:`${n} flame graph range`})})}static getDiffRange(e){var t,n,r,o;let a,i;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})=>(a="time"===e?t[0]:a,i="timeEnd"===e?t[0]:i,a&&i))),[a,i,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 Lt.jh.getTimeRange(this.parent.parent)}subscribeToEvents(){var e;const{target:t,timeseriesPanel:n,$timeRange:r}=this.state,o=n.state.body.state.$timeRange,a=this.subscribeToEvent(Qs,(e=>{o.setState({mode:e.payload.mode===tl.FLAMEGRAPH?Zs.ANNOTATIONS:Zs.DEFAULT})})),i=o.subscribeToState(((e,n)=>{this.state.timeRangeSyncEnabled&&e.annotationTimeRange!==n.annotationTimeRange&&this.publishEvent(new Ms({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 Ms({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(),i.unsubscribe(),a.unsubscribe(),null==l||l.unsubscribe()}}}buildTimeseriesTitle(){const e=Co(this,"profileMetricId"),{description:t}=Xr(e);return t||ra(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(Xi(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:a}=t.state.value;if(this.updateTitle(""),e)return void this.setDiffRange({from:r.toISOString(),to:a.toISOString()});const i=a.diff(r),s=Math.min(Math.round(.25*i),864e5);n===lt.BASELINE?this.setDiffRange({from:r.toISOString(),to:(0,o.dateTime)(r).add(s).toISOString()}):this.setDiffRange({from:(0,o.dateTime)(a).subtract(s).toISOString(),to:a.toISOString()})}updateTitle(e=""){const t=this.state.target===lt.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===lt.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=>dl(ul({},t),{step:e})));n.setState({queries:r}),n.runQueries()}constructor({target:e,useAncestorTimeRange:t,clearDiffRange:n,filters:r}){const o=e===lt.BASELINE?"filtersBaseline":"filtersComparison",a=e===lt.BASELINE?"Baseline":"Comparison",i=e===lt.BASELINE?sl.COLOR.toString():ll.COLOR.toString();super({key:`${e}-panel`,target:e,filterKey:o,title:a,color:i,$timeRange:new Lt.JZ(ul({key:`${e}-panel-timerange`},Xi("now-1h","now"))),timePicker:new Vs({isOnCanvas:!0}),refreshPicker:new Lt.WM({isOnCanvas:!0}),timeseriesPanel:pl.buildTimeSeriesPanel({target:e,filterKey:o,title:a,color:i}),timeRangeSyncEnabled:!1}),cl(this,"_variableDependency",new Lt.Sh(this,{variableNames:["profileMetricId"],onReferencedVariableValueChanged:()=>{this.state.timeseriesPanel.updateItem({label:this.buildTimeseriesTitle()})}})),cl(this,"onClickTimeRangeSync",(()=>{const{target:e,timeRangeSyncEnabled:t,$timeRange:n,timeseriesPanel:r}=this.state,o=r.state.body.state.$timeRange;this.publishEvent(new Bs({source:e,enable:!t,timeRange:n.state,annotationTimeRange:o.state.annotationTimeRange}),!0)})),cl(this,"onClickRefresh",(()=>{this.publishEvent(new $s({source:this.state.target}),!0)})),this.addActivationHandler(this.onActivate.bind(this,t,n,r))}}cl(pl,"Component",(({model:e})=>{const{target:t,color:n,title:o,timeseriesPanel:a,timePicker:s,refreshPicker:l,filterKey:c,timeRangeSyncEnabled:u}=e.useState(),d=(0,i.useStyles2)(ml,n),p=Lt.jh.findByKey(e,c);return w().createElement("div",{className:d.panel,"data-testid":`panel-${t}`},w().createElement("div",{className:d.panelHeader},w().createElement("h6",null,w().createElement("div",{className:d.colorCircle}),o),w().createElement("div",{className:d.timeControls},w().createElement(s.Component,{model:s}),w().createElement("div",{onClick:e.onClickRefresh},w().createElement(l.Component,{model:l})),w().createElement(i.IconButton,{className:(0,r.cx)(d.syncButton,u&&"active"),name:"link","aria-label":u?"Unsync time ranges":"Sync time ranges",tooltip:u?"Unsync time ranges":"Sync time ranges",onClick:e.onClickTimeRangeSync}))),w().createElement("div",{className:d.filter},w().createElement(p.Component,{model:p})),w().createElement("div",{className:d.timeseries},a&&w().createElement(a.Component,{model:a})))}));const ml=(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;
}
`});function fl(){const[e,t]=(0,S.useState)(null),[n,r]=(0,S.useState)();return{onOpen(e){r((()=>e))},isOpen:t=>t===e,open(e){t(e),null==n||n()},close(){t(null)}}}const hl=Object.freeze({collapsedFlamegraphs:!1,maxNodes:16384,enableFlameGraphDotComExport:!0,enableFunctionDetails:!0,enableMetricsFromProfiles:!1});function gl(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function bl(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){gl(a,r,o,i,s,"next",e)}function s(e){gl(a,r,o,i,s,"throw",e)}i(void 0)}))}}class yl extends q{get(){var e=this,t=()=>super.fetch;return bl((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===yl.PLUGIN_SETTING_NAME));return n?JSON.parse(n.value):{}}))}))()}set(e){var t=this,n=()=>super.fetch;return bl((function*(){return n().call(t,"/settings.v1.SettingsService/Set",{method:"POST",body:JSON.stringify({setting:{name:yl.PLUGIN_SETTING_NAME,value:JSON.stringify(e)}})}).then((e=>e.json()))}))()}}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(yl,"PLUGIN_SETTING_NAME","pluginSettings");const vl=()=>new yl;function El({enabled:e}={}){const t=vl(),{isFetching:n,error:r,data:o}=(0,K.I)({enabled:e,queryKey:["settings","ds-uid-"+q.selectDefaultDataSource().uid],queryFn:()=>t.get().then((e=>Object.keys(hl).reduce(((e,t)=>{var n,r,o;return null!==(o=(n=e)[r=t])&&void 0!==o||(n[r]=hl[t]),e}),e)))}),{mutateAsync:a}=(0,xs.n)({mutationFn:e=>t.set(e),networkMode:"always"});return{isFetching:n,error:t.isAbortError(r)?null:r,settings:o,mutate:a}}function Sl({severity:e,title:t,message:n,error:r,errorContext:o}){return r&&j.error(r,o),w().createElement(i.Alert,{title:t,severity:e},r&&w().createElement(w().Fragment,null,r.message,w().createElement("br",null)),n)}var wl=n(7945);function Ol({children:e,delay:t}){const[n,r]=(0,S.useState)(!1);return(0,S.useEffect)((()=>{window.setTimeout((()=>{r(!0)}),t)}),[e,t]),w().createElement(w().Fragment,null,n?e:null)}function Pl({menu:e,title:t,placement:n="bottom",offset:o,dragClassCancel:a,menuButtonClass:s,onVisibleChange:l,onOpenMenu:c}){const u=t?wl.Tp.components.Panels.Panel.menu(t):"panel-menu-button",d=(0,S.useCallback)((e=>(e&&c&&c(),l)),[c,l]),p=t?`Menu for panel with title ${t}`:"Menu for panel with no title";return w().createElement(i.Dropdown,{overlay:e,placement:n,offset:o,onVisibleChange:d},w().createElement(i.ToolbarButton,{"aria-label":p,title:"Menu",icon:"ellipsis-v",iconSize:"md",narrow:!0,"data-testid":u,className:(0,r.cx)(s,a)}))}function xl({menu:e,title:t,dragClass:n,children:o,offset:a=-32,onOpenMenu:s}){const l=(0,i.useStyles2)(Cl),c=(0,S.useRef)(null),u=wl.Tp.components.Panels.Panel.HoverWidget,d=(0,S.useCallback)((e=>{var t;null===(t=c.current)||void 0===t||t.setPointerCapture(e.pointerId)}),[]),p=(0,S.useCallback)((e=>{var t;null===(t=c.current)||void 0===t||t.releasePointerCapture(e.pointerId)}),[]),[m,f]=(0,S.useState)(!1);return void 0===o||0===w().Children.count(o)?null:w().createElement("div",{className:(0,r.cx)(l.container,{"show-on-hover":!m}),style:{top:`${a}px`},"data-testid":u.container},n&&w().createElement("div",{className:(0,r.cx)(l.square,l.draggable,n),onPointerDown:d,onPointerUp:p,ref:c,"data-testid":u.dragIcon},w().createElement(i.Icon,{name:"expand-arrows",className:l.draggableIcon})),!t&&w().createElement("h6",{className:(0,r.cx)(l.untitled,{[l.draggable]:!!n},n)},"Untitled"),o,e&&w().createElement(Pl,{menu:e,title:t,placement:"bottom",menuButtonClass:l.menuButton,onVisibleChange:f,onOpenMenu:s}))}function Cl(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 Tl(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Al(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){Tl(e,t,n[t])}))}return e}function Nl(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 kl(e,t){if(null==e)return{};var n,r,o=function(e,t){if(null==e)return{};var n,r,o={},a=Object.keys(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)>=0||(o[n]=e[n]);return o}(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(o[n]=e[n])}return o}const jl=(0,S.forwardRef)(((e,t)=>{var{className:n,children:o,href:a,onClick:s,target:l,title:c}=e,u=kl(e,["className","children","href","onClick","target","title"]);const d=(0,i.useStyles2)(Rl);return a?w().createElement("a",Al({ref:t,href:a,onClick:s,target:l,title:c,className:(0,r.cx)(d.linkItem,n)},u),o):s?w().createElement(i.Button,{ref:t,className:(0,r.cx)(d.item,n),variant:"secondary",fill:"text",onClick:s},o):w().createElement("span",Al({ref:t,className:(0,r.cx)(d.item,n)},u),o)}));jl.displayName="TitleItem";const Rl=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":Nl(Al({},Il(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 Il(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 Dl({description:e,className:t}){const n=(0,i.useStyles2)(_l);return""!==e?w().createElement(i.Tooltip,{interactive:!0,content:()=>{const t="function"==typeof e?e():e;return w().createElement("div",{className:"panel-info-content markdown-html"},w().createElement("div",{dangerouslySetInnerHTML:{__html:t}}))}},w().createElement(jl,{className:(0,r.cx)(t,n.description)},w().createElement(i.Icon,{name:"info-circle",size:"md"}))):null}const _l=()=>({description:(0,r.css)({code:{whiteSpace:"normal",wordWrap:"break-word"},"pre > code":{display:"block"}})});function Ll({message:e,onClick:t,ariaLabel:n="status"}){const r=(0,i.useStyles2)(Fl);return w().createElement(i.ToolbarButton,{className:r.buttonStyles,onClick:t,variant:"destructive",icon:"exclamation-triangle",iconSize:"md",tooltip:e||"","aria-label":n})}const Fl=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 Bl({children:e,padding:t="md",title:n="",description:a="",displayMode:s="default",titleItems:l,menu:c,dragClass:u,dragClassCancel:d,hoverHeader:p=!1,hoverHeaderOffset:m,loadingState:f,statusMessage:h,statusMessageOnClick:g,actions:b,onCancelQuery:y,onOpenMenu:v}){const E=(0,i.useTheme2)(),O=(0,i.useStyles2)(Ul),[P,x]=(0,S.useState)(0),C=(0,S.useRef)(null);(0,S.useEffect)((()=>{C.current&&x(C.current.offsetWidth)}),[C]);const T=!p,A=Ml(E,T),{contentStyle:N}=Vl(t,E),k={height:A,cursor:u?"move":"auto"},j={};"transparent"===s&&(j.backgroundColor="transparent",j.border="none");const R=n?wl.Tp.components.Panels.Panel.title(n):"Panel",I=w().createElement(w().Fragment,null,n&&w().createElement("h6",{title:n,className:O.title},n),w().createElement("div",{className:(0,r.cx)(O.titleItems,d),"data-testid":"title-items-container"},w().createElement(Dl,{description:a,className:d}),l),f===o.LoadingState.Streaming&&w().createElement(i.Tooltip,{content:y?"Stop streaming":"Streaming"},w().createElement(jl,{className:d,"data-testid":"panel-streaming",onClick:y},w().createElement(i.Icon,{name:"circle-mono",size:"md",className:O.streaming}))),f===o.LoadingState.Loading&&y&&w().createElement(Ol,{delay:2e3},w().createElement(i.Tooltip,{content:"Cancel query"},w().createElement(jl,{className:(0,r.cx)(d,O.pointer),"data-testid":"panel-cancel-query",onClick:y},w().createElement(i.Icon,{name:"sync-slash",size:"md"})))),w().createElement("div",{className:O.rightAligned},b&&w().createElement("div",{className:O.rightActions},$l(b,(e=>e)))));return w().createElement("div",{className:O.container,style:j,"data-testid":R},w().createElement("div",{className:O.loadingBarContainer},f===o.LoadingState.Loading?w().createElement(i.LoadingBar,{width:P,ariaLabel:"Panel loading bar"}):null),p&&w().createElement(w().Fragment,null,w().createElement(xl,{menu:c,title:n,offset:m,dragClass:u,onOpenMenu:v},I),h&&w().createElement("div",{className:O.errorContainerFloating},w().createElement(Ll,{message:h,onClick:g,ariaLabel:"Panel status"}))),T&&w().createElement("div",{className:(0,r.cx)(O.headerContainer,u),style:k,"data-testid":"header-container"},h&&w().createElement("div",{className:d},w().createElement(Ll,{message:h,onClick:g,ariaLabel:"Panel status"})),I,c&&w().createElement(Pl,{menu:c,title:n,placement:"bottom-end",menuButtonClass:(0,r.cx)(O.menuItem,d,"show-on-hover"),onOpenMenu:v})),w().createElement("div",{className:O.content,style:N,ref:C},e))}const $l=(e,t)=>{const n=w().Children.toArray(e).filter(Boolean);return n.length>0?t(n):null},Ml=(e,t)=>t?e.spacing.gridSize*e.components.panel.headerHeight:0,Vl=(e,t)=>({contentStyle:{padding:("md"===e?t.components.panel.padding:0)*t.spacing.gridSize}}),Ul=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%"})}},Gl=e=>({panelWrap:r.css`
margin-bottom: ${e.spacing(1)};
`});function ql({isLoading:e,title:t,description:n,children:r,className:a="",headerActions:s,dataTestId:l}){const c=(0,i.useStyles2)(Gl),u=e?o.LoadingState.Loading:o.LoadingState.Done;return w().createElement("div",{className:`${a} ${c.panelWrap}`,"data-testid":l||"panel"},w().createElement(Bl,{loadingState:u,title:t,description:n,actions:s},r))}var Kl=n(6030);function zl({children:e,onClick:t,disabled:n,interactionName:r}){const o=(0,i.useStyles2)(Wl),{isEnabled:a,error:s,isFetching:l}=function(){const{data:e,isFetching:t,error:n}=(0,K.I)({queryKey:["llm"],queryFn:()=>Kl.Sn()});return n&&j.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."),w().createElement(i.Button,{className:o.aiButton,size:"md",fill:"text",icon:c,disabled:!a||n,tooltip:u,tooltipPlacement:"top",onClick:e=>{Ie(r),t(e)}},e)}const Wl=()=>({aiButton:r.css`
padding: 0 4px;
`});var Hl=n(7879);const Yl=e=>{const t=document.querySelector('[placeholder^="Search"]');if(null===t)return void j.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}))},Zl={overrides:{code:{component:({children:e})=>{const t=(0,i.useStyles2)(Jl);return"string"==typeof e&&e.includes("\n")?w().createElement("code",null,e):w().createElement("code",{className:t.searchLink,title:"Search for this node",onClick:Yl},e)}}}};function Xl({reply:e}){var t;const n=(0,i.useStyles2)(Jl);return w().createElement("div",{className:n.container},null==e||null===(t=e.messages)||void 0===t?void 0:t.filter((e=>"system"!==e.role)).map((e=>w().createElement(w().Fragment,null,w().createElement("div",{className:n.reply},w().createElement(Hl.Ay,{options:Zl},e.content||"")),w().createElement("hr",null)))),w().createElement("div",{className:n.reply},w().createElement(Hl.Ay,{options:Zl},e.text)))}const Jl=()=>({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;
}
`}),Ql=()=>({textarea:r.css`
margin-bottom: 8px;
`,sendButton:r.css`
float: right;
border-top-left-radius: 0;
border-bottom-left-radius: 0;
`});function ec({onSubmit:e}){const t=(0,i.useStyles2)(Ql),{question:n,onChangeInput:r,onClickSend:o}=function(e){const[t,n]=(0,S.useState)(""),r=(0,S.useCallback)((e=>{n(e.target.value)}),[]),o=(0,S.useCallback)((()=>{const r=t.trim();r&&(e(r),n(""))}),[t,e]);return{question:t,onChangeInput:r,onClickSend:o}}(e);return w().createElement("div",null,w().createElement(i.TextArea,{className:t.textarea,placeholder:"Ask a follow-up question...",value:n,onChange:r,onKeyDown:e=>{"Enter"!==e.code||e.shiftKey||o()}}),w().createElement(i.Button,{className:t.sendButton,onClick:o},"Send"))}var tc=n(9178);const nc={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`}},rc=({system:e,user:t,profileType:n,profiles:r})=>{const o=nc.system[e];if("function"!=typeof o)throw new Error(`Cannot find system prompt "${e}"!`);const a=nc.user[t];if("function"!=typeof a)throw new Error(`Cannot find user prompt "${t}"!`);return{system:o(n,r),user:a(n,r)}};function oc(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}class ac extends Xt{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 a=t.apply(e,n);function i(e){oc(a,r,o,i,s,"next",e)}function s(e){oc(a,r,o,i,s,"throw",e)}i(void 0)}))})()}constructor(e){super(e)}}function ic(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class sc extends Lt.Bs{validateFetchParams(e,t){let n,r=t;return 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=[]),{params:r,error:n}}constructor(){super({key:"ai-panel"}),ic(this,"useSceneAiPanel",((e,t)=>{const n=Lt.jh.findByKeyAndType(this,"dataSource",mo).useState().value,{params:r,error:o}=this.validateFetchParams(e,t),{error:a,isFetching:i,profiles:s}=function(e,t){const n=ns.build(e,ac),{isFetching:r,error:o,data:a}=(0,K.I)({queryKey:["dot-profiles",e,...t.flatMap((({query:e,timeRange:t})=>[e,t.from.unix(),t.to.unix()])),100],queryFn:()=>Promise.all(t.map((({query:e,timeRange:t})=>n.get({query:e,timeRange:t,format:"dot",maxNodes:100}).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,""))))))});return{isFetching:r,error:o,profiles:a||[]}}(n,r),l=Xr(Co(this,"profileMetricId")).type,{reply:c,error:u,retry:d}=function(e,t){const[n,r]=(0,S.useState)(""),[o,a]=(0,S.useState)(!1),[i,s]=(0,S.useState)(!1),[l,c]=(0,S.useState)([]),[u,d]=(0,S.useState)(null),[p,m]=(0,S.useState)(),f=(0,S.useCallback)((e=>{c(e),d(null),r(""),a(!0),s(!1);const t=tc.qH({model:"gpt-4-1106-preview",messages:e}).pipe(tc.qA()).subscribe({next:r,error(e){d(e),a(!1),s(!0),m(void 0)},complete(){a(!1),s(!0),m(void 0)}});m(t)}),[]),h=(0,S.useCallback)((e=>{const t=[{role:"assistant",content:n},{role:"user",content:e}];try{f([...l,...t])}catch(e){d(e)}}),[l,n,f]);return(0,S.useEffect)((()=>{if(!t.length||l.length>0)return;const n=rc({system:"empty",user:2===t.length?"diff":"single",profileType:e,profiles:t});try{f([{role:"system",content:n.system},{role:"system",content:n.user}])}catch(e){d(e)}}),[l.length,e,t,t.length,f]),(0,S.useEffect)((()=>()=>{p&&(p.unsubscribe(),m(void 0))}),[p]),{reply:{text:n,hasStarted:o,hasFinished:i,messages:l,askFollowupQuestion:h},retry(){if(l.length>0)try{f(l)}catch(e){d(e)}},error:u}}(l,s);return{data:{validationError:o,isLoading:i||!i&&!a&&!u&&!c.text.trim(),fetchError:a,llmError:u,reply:c,shouldDisplayReply:Boolean((null==c?void 0:c.hasStarted)||(null==c?void 0:c.hasFinished)),shouldDisplayFollowUpForm:!a&&!u&&Boolean(null==c?void 0:c.hasFinished)},actions:{retry:d,submitFollowupQuestion(e){c.askFollowupQuestion(e)}}}}))}}ic(sc,"Component",(({model:e,isDiff:t,fetchParams:n,onClose:r})=>{const o=(0,i.useStyles2)(lc),{data:a,actions:s}=e.useSceneAiPanel(t,n);return w().createElement(ql,{className:o.sidePanel,title:"Flame graph analysis",isLoading:a.isLoading,headerActions:w().createElement(i.IconButton,{title:"Close panel",name:"times-circle",variant:"secondary","aria-label":"close",onClick:r}),dataTestId:"ai-panel"},w().createElement("div",{className:o.content},a.validationError&&w().createElement(Sl,{severity:"error",title:"Validation error!",error:a.validationError}),a.fetchError&&w().createElement(Sl,{severity:"error",title:"Error while loading profile data!",message:"Sorry for any inconvenience, please try again later.",error:a.fetchError}),a.shouldDisplayReply&&w().createElement(Xl,{reply:a.reply}),a.isLoading&&w().createElement(w().Fragment,null,w().createElement(i.Spinner,{inline:!0})," Analyzing..."),a.llmError&&w().createElement(i.Alert,{title:"An error occured while generating content using OpenAI!",severity:"warning"},w().createElement("div",null,w().createElement("div",null,w().createElement("p",null,a.llmError.message),w().createElement("p",null,"Sorry for any inconvenience, please retry or if the problem persists, contact your organization admin."))),w().createElement(i.Button,{className:o.retryButton,variant:"secondary",fill:"outline",onClick:()=>s.retry()},"Retry")),a.shouldDisplayFollowUpForm&&w().createElement(ec,{onSubmit:s.submitFollowupQuestion})))}));const lc=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 cc extends o.BusEventWithPayload{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(cc,"type","diff-auto-select");class uc extends o.BusEventWithPayload{}function dc(){const{searchParams:e,pushNewUrl:t}=function(){const e=(0,Ae.useNavigate)(),t=(0,Ae.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 r=Number(null!==(n=e.get("maxNodes"))&&void 0!==n?n:""),o=e=>{t({maxNodes:String(e)})};return function(e,t){const{isFetching:n,error:r,settings:o}=El({enabled:!e});if(!e&&!n)r?(Me(["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."]),j.error(r),t(hl.maxNodes)):t(o.maxNodes)}(r>0,o),[r,o]}function pc(e,t,n,r,o,a,i){try{var s=e[a](i),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}(uc,"type","diff-choose-preset");class mc extends Xt{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 a=t.apply(e,n);function i(e){pc(a,r,o,i,s,"next",e)}function s(e){pc(a,r,o,i,s,"throw",e)}i(void 0)}))})()}constructor(e){super(e)}}function fc(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function hc(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 gc({enabled:e,dataSourceUid:t,baselineTimeRange:n,baselineQuery:r,comparisonTimeRange:o,comparisonQuery:a}){const[i]=dc(),s=ns.build(t,mc),{isFetching:l,error:c,data:u,refetch:d}=(0,K.I)({placeholderData:e=>e,enabled:Boolean(e&&i),queryKey:["diff-profile",t,r,n.from.unix(),n.to.unix(),a,o.from.unix(),o.to.unix(),i],queryFn:()=>{s.abort();const e={leftQuery:r,leftTimeRange:n,rightQuery:a,rightTimeRange:o,maxNodes:i};return s.get(e).then((e=>({profile:{version:e.version,flamebearer:e.flamebearer,metadata:e.metadata}})))}});return hc(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){fc(e,t,n[t])}))}return e}({isFetching:l,error:s.isAbortError(c)?null:c},u),{refetch:d})}function bc({onClickAutoSelect:e,onClickChoosePreset:t,onOpenLearnHow:n}){const r=(0,i.useStyles2)(yc),[o,a]=(0,S.useState)(!1);return w().createElement(Sl,{severity:"info",title:"Select both the baseline and the comparison flame graph ranges to view the diff flame graph",message:w().createElement("div",{className:r.infoMsg},w().createElement("p",null,"How?"),w().createElement("p",null,w().createElement(i.Button,{variant:"primary",onClick:e},"Auto-select")," ","or"," ",w().createElement(i.Button,{variant:"primary",fill:"text",className:r.textButton,onClick:t},"choose a preset")),w().createElement("p",null,"Alternatively:"),w().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)}},w().createElement("div",{className:r.collapseContent},w().createElement("ol",null,w().createElement("li",null,"Ensure that the “Flame graph” range selection mode is selected"),w().createElement("li",null,"Use your mouse to select the desired time ranges on both the baseline and the comparison time series")),w().createElement("img",{src:"public/plugins/grafana-pyroscope-app/img/8cdf4d2e2df8326311ab.gif",alt:"How to view the diff flame graph"}))))})}const yc=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 vc(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class Ec extends Lt.Bs{buildTitle(){const e=Co(this,"serviceName"),t=Xr(Co(this,"profileMetricId")).type;return w().createElement(w().Fragment,null,w().createElement(te,{size:"small"}),"Diff flame graph for ",e," (",t,")")}constructor(){super({key:"diff-flame-graph",aiPanel:new sc}),vc(this,"useSceneDiffFlameGraph",(()=>{const{aiPanel:e}=this.useState(),{baselineTimeRange:t,comparisonTimeRange:n}=this.parent.useDiffTimeRanges(),r=po(this,"filtersBaseline"),o=po(this,"filtersComparison"),{settings:a,error:i}=El(),s=Lt.jh.findByKeyAndType(this,"dataSource",mo).useState().value,l=Boolean(r&&o&&t.from.unix()&&t.to.unix()&&n.from.unix()&&n.to.unix()),{isFetching:c,error:u,profile:d}=gc({enabled:l,dataSourceUid:s,baselineTimeRange:t,baselineQuery:r,comparisonTimeRange:n,comparisonQuery:o}),p=l&&!c&&!u&&0===(null==d?void 0:d.flamebearer.numTicks),m=Boolean(l&&!u&&!p&&d),f=!l;return{data:{title:this.buildTitle(),isLoading:c,fetchProfileError:u,noProfileDataAvailable:p,shouldDisplayFlamegraph:m,hasMissingSelections:f,profile:d,settings:a,fetchSettingsError:i,ai:{panel:e,fetchParams:[{query:r,timeRange:t},{query:o,timeRange:n}]}},actions:{}}})),vc(this,"onClickAutoSelect",(()=>{Ie("g_pyroscope_app_diff_auto_select_clicked"),this.publishEvent(new cc({wholeRange:!1}),!0)})),vc(this,"onClickChoosePreset",(()=>{Ie("g_pyroscope_app_diff_choose_preset_clicked"),this.publishEvent(new uc({}),!0)})),vc(this,"onOpenLearnHow",(()=>{Ie("g_pyroscope_app_diff_learn_how_clicked")}))}}vc(Ec,"Component",(({model:e})=>{var t,n;const r=(0,i.useStyles2)(Sc),{data:o}=e.useSceneDiffFlameGraph(),a=fl(),s=o.isLoading||o.hasMissingSelections||o.noProfileDataAvailable;(0,S.useEffect)((()=>{s&&a.close()}),[s,a]),o.fetchSettingsError&&Me(["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 l=(0,S.useMemo)((()=>w().createElement(w().Fragment,null,o.title,o.isLoading&&w().createElement(i.Spinner,{inline:!0,className:r.spinner}))),[o.isLoading,o.title,r.spinner]);return w().createElement("div",{className:r.flex},w().createElement(ql,{dataTestId:"diff-flame-graph-panel",className:r.flamegraphPanel,title:l,isLoading:o.isLoading,headerActions:w().createElement(zl,{disabled:s||a.isOpen("ai"),onClick:()=>a.open("ai"),interactionName:"g_pyroscope_app_explain_flamegraph_clicked"},"Explain Diff Flame Graph")},o.hasMissingSelections&&w().createElement(bc,{onClickAutoSelect:e.onClickAutoSelect,onClickChoosePreset:e.onClickChoosePreset,onOpenLearnHow:e.onOpenLearnHow}),o.fetchProfileError&&w().createElement(Sl,{severity:"error",title:"Error while loading profile data!",error:o.fetchProfileError}),o.noProfileDataAvailable&&w().createElement(Sl,{severity:"warning",title:"No profile data available",message:"Please verify that you've selected adequate filters and time ranges."}),o.shouldDisplayFlamegraph&&w().createElement(St,{diff:!0,profile:o.profile,enableFlameGraphDotComExport:null===(t=o.settings)||void 0===t?void 0:t.enableFlameGraphDotComExport,collapsedFlamegraphs:null===(n=o.settings)||void 0===n?void 0:n.collapsedFlamegraphs,showAnalyzeWithAssistant:!1})),a.isOpen("ai")&&w().createElement(o.ai.panel.Component,{model:o.ai.panel,isDiff:!0,fetchParams:o.ai.fetchParams,onClose:a.close}))}));const Sc=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)};
`}),wc="https://grafana.qualtrics.com/jfe/form/SV_6Gav4IUU6jcYfd4",Oc=()=>{const e=(0,i.useStyles2)(Pc);return w().createElement("div",{className:e.wrapper},w().createElement("a",{href:wc,className:e.feedback,title:"Share your thoughts about Profiles in Grafana.",target:"_blank",rel:"noreferrer noopener"},w().createElement(i.Icon,{name:"comment-alt-message"})," Give feedback"))},Pc=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 xc(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class Cc extends Lt.Bs{onActivate(){[lt.BASELINE,lt.COMPARISON].forEach((e=>{this._subs.add(Lt.jh.findByKeyAndType(this,`${e}-panel`,pl).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)(Tc),{value:n,isSelectOpen:r,isModalOpen:o}=e.useState();return w().createElement(w().Fragment,null,w().createElement("div",{className:t.presetsContainer},w().createElement(i.Select,{className:t.select,placeholder:"Choose a preset",value:n,options:Cc.PRESETS,onChange:e.onChangePreset,isOpen:r,onOpenMenu:e.onOpenSelect,onCloseMenu:e.onCloseSelect}),w().createElement(i.Button,{icon:"save",variant:"secondary",tooltip:"Save the current time ranges and filters as a custom preset",onClick:e.onClickSave})),w().createElement(i.Modal,{title:"Custom user presets",isOpen:o,closeOnEscape:!0,closeOnBackdropClick:!0,onDismiss:e.closeModal},w().createElement("p",null,"This feature, which would allow you to save the current time ranges and filters, is currently not implemented."),w().createElement("p",null,"Please let us know if you would be interested to use it by"," ",w().createElement("a",{href:wc,target:"_blank",rel:"noreferrer noopener",className:t.link},"leaving us your feedback.")),w().createElement("p",null,"Thank you!"),w().createElement(i.Modal.ButtonRow,null,w().createElement(i.Button,{variant:"secondary",fill:"outline",onClick:e.closeModal},"Cancel"),w().createElement(i.Button,{onClick:e.closeModal,disabled:!0},"Save"))))}constructor(){super({name:"compare-presets",label:"Comparison presets",value:null,isModalOpen:!1,isSelectOpen:!1}),xc(this,"_variableDependency",new Lt.Sh(this,{variableNames:["dataSource","serviceName"],onReferencedVariableValueChanged:()=>{this.reset()}})),xc(this,"onChangePreset",(e=>{var t;if(Ie("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 cc({wholeRange:"auto-select-whole"===e.value}),!0);[lt.BASELINE,lt.COMPARISON].forEach((t=>{const n=Lt.jh.findByKeyAndType(this,`${t}-panel`,pl);n.toggleTimeRangeSync(!1),n.applyPreset(e[t])})),this.setState({value:e.value})}else this.setState({value:null,isModalOpen:!0})})),xc(this,"onClickSave",(()=>{Ie("g_pyroscope_app_diff_preset_save_clicked"),this.setState({isModalOpen:!0})})),xc(this,"closeModal",(()=>{this.setState({isModalOpen:!1})})),xc(this,"onOpenSelect",(()=>{setTimeout((()=>this.openSelect()),0)})),xc(this,"onCloseSelect",(()=>{this.closeSelect()})),this.addActivationHandler(this.onActivate.bind(this))}}xc(Cc,"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 Tc=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 Ac(){return e=>{const t=new Map,n=e.subscribeToEvent(Ut,(n=>{var r;const o=null===(r=n.payload.series)||void 0===r?void 0:r[0];(null==o?void 0:o.refId)?(t.set(o.refId,Math.max(...o.fields[1].values)),function(e,t){const n=Lt.jh.findAllObjects(e,(e=>e instanceof Lt.Eb&&"timeseries"===e.state.pluginId));for(const e of n)e.clearFieldConfigCache(),e.setState({fieldConfig:(0,Vt.merge)((0,Vt.cloneDeep)(e.state.fieldConfig),{defaults:{max:t}})})}(e,Math.max(...t.values()))):j.warn("Missing refId! Cannot sync y-axis on the timeseries.",n.payload.series)}));return()=>{n.unsubscribe()}}}class Nc extends Lt.Bs{onActivate(){a.locationService.partial({},!0);const e=Lt.jh.findByKeyAndType(this,"profileMetricId",ao);return e.setState({query:ao.QUERY_SERVICE_NAME_DEPENDENT}),e.update(!0),this.subscribeToEvents(),()=>{e.setState({query:ao.QUERY_DEFAULT}),e.update(!0)}}subscribeToEvents(){this._subs.add(this.subscribeToEvent(cc,(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(uc,(()=>{this.state.presetsPicker.openSelect()}))),this._subs.add(this.subscribeToEvent(Bs,(e=>{const{source:t,enable:n,timeRange:r,annotationTimeRange:o}=e.payload,{baselinePanel:a,comparisonPanel:i}=this.state,s=t===lt.BASELINE?i:a;n&&this.syncTimeRanges(s,r,o),i.toggleTimeRangeSync(n),a.toggleTimeRangeSync(n)}))),this._subs.add(this.subscribeToEvent(Ms,(e=>{const{source:t,timeRange:n,annotationTimeRange:r}=e.payload,{baselinePanel:o,comparisonPanel:a}=this.state,i=t===lt.BASELINE?a:o;this.syncTimeRanges(i,n,r)}))),this._subs.add(this.subscribeToEvent($s,(e=>{const{source:t}=e.payload,{baselinePanel:n,comparisonPanel:r}=this.state;(t===lt.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:[Lt.jh.findByKeyAndType(this,"serviceName",co),Lt.jh.findByKeyAndType(this,"profileMetricId",ao),this.state.presetsPicker],gridControls:[]}}static Component({model:e}){const t=(0,i.useStyles2)(kc),{baselinePanel:n,comparisonPanel:r,body:o}=e.useState();return w().createElement("div",{className:t.container},w().createElement("div",{className:t.columns},w().createElement(n.Component,{model:n}),w().createElement(r.Component,{model:r})),w().createElement(o.Component,{model:o}))}constructor({useAncestorTimeRange:e,clearDiffRange:t,baselineFilters:n,comparisonFilters:r}){super({key:"explore-diff-flame-graph",baselinePanel:new pl({target:lt.BASELINE,useAncestorTimeRange:Boolean(e),clearDiffRange:Boolean(t),filters:n||[]}),comparisonPanel:new pl({target:lt.COMPARISON,useAncestorTimeRange:Boolean(e),clearDiffRange:Boolean(t),filters:r||[]}),$behaviors:[new Lt.Gg.K2({key:"metricCrosshairSync",sync:o.DashboardCursorSync.Crosshair}),Ac()],body:new Ec,presetsPicker:new Cc}),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 kc=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 jc(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function Rc(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){jc(a,r,o,i,s,"next",e)}function s(e){jc(a,r,o,i,s,"throw",e)}i(void 0)}))}}class Ic extends Xt{githubLogin(e){var t=this;return Rc((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 Rc((function*(){const t=yield e.fetch("/vcs.v1.VCSService/GithubApp",{method:"POST",body:JSON.stringify({})});return yield t.json()}))()}}function Dc(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class _c{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 j.error(e,{info:"Failed to base64 decode GitSession value"})}const{payload:n,isLegacy:r}=_c.tryDecode(t);return r?new _c(e,864e13):new _c(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){Dc(this,"oauthTokenMetadata",void 0),Dc(this,"expiry",void 0),this.oauthTokenMetadata=e,this.expiry=new Date(t)}}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}const Fc="pyroscope_git_session";class Bc{getCookie(){return this.syncCookieWithBrowser(),this.sessionCookie}setCookie(e){e.startsWith(`${Fc}=`)||(e=`${Fc}=${e}`);const t=Bc.getCookieFromJar(e,Fc);void 0!==t&&(this.deleteLegacyCookie(),this.rawCookie=t,this.sessionCookie=_c.decode(t.value),document.cookie=`${e}; path=/`)}deleteCookie(){document.cookie=`${Fc}=; 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=Bc.getCookieFromJar(document.cookie,Fc);(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=_c.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(){Lc(this,"rawCookie",void 0),Lc(this,"sessionCookie",void 0)}}const $c=new Bc;const Mc=800,Vc=950;function Uc(e,t,n){const r=function(e,t,n){const r=(o=a.config.appSubUrl||"/").endsWith("/")?o.slice(0,-1):o;var o;const i=`${window.location.origin}${r}${p}${m.GITHUB_CALLBACK}`,s=new URL("/login/oauth/authorize","https://github.com");return s.searchParams.set("client_id",e),n&&s.searchParams.set("redirect_uri",n),s.searchParams.set("scope","repo"),s.searchParams.set("state",btoa(JSON.stringify({redirect_uri:i,nonce:t}))),s.toString()}(e,t,n),{top:o}=window;var i,s;const l=(null!==(i=null==o?void 0:o.outerWidth)&&void 0!==i?i:0)/2+(null!==(s=null==o?void 0:o.screenX)&&void 0!==s?s:0)-Mc/2;var c,u;const d=(null!==(c=null==o?void 0:o.outerHeight)&&void 0!==c?c:0)/2+(null!==(u=null==o?void 0:o.screenY)&&void 0!==u?u:0)-Vc/2;return window.open(r,"GitHub Login",`toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=${Mc}, height=${Vc}, top=${d}, left=${l}`)}function Gc(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function qc(){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){j.error(e,{info:"Failed to refresh GitHub user token"}),$c.deleteCookie()}try{const{clientID:t,callbackURL:n}=yield e.githubApp();o(Uc(t,iu,n))}catch(e){$e(e,["Failed to start login flow.",e.message])}},qc=function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){Gc(a,r,o,i,s,"next",e)}function s(e){Gc(a,r,o,i,s,"throw",e)}i(void 0)}))},qc.apply(this,arguments)}function Kc(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function zc(){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 a;try{a=JSON.parse(atob(o))}catch(e){throw new Error("Invalid state parameter!")}if(a.nonce!==n)throw new Error("Invalid nonce parameter!");return(yield e.githubLogin(r)).cookie},zc=function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){Kc(a,r,o,i,s,"next",e)}function s(e){Kc(a,r,o,i,s,"throw",e)}i(void 0)}))},zc.apply(this,arguments)}function Wc(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function Hc({vcsClient:e,externalWindow:t,setExternalWindow:n,setSessionCookie:r,nonce:o}){(0,S.useEffect)((()=>{const a=function(){var i,s=(i=function*(){if(t&&!t.closed){try{const a=function(e){try{return new URL(e.location.href).searchParams}catch(e){return null}}(t);if(null!==a){const i=yield function(e,t,n){return zc.apply(this,arguments)}(e,a,o);if(i)return r(i),t.close(),void n(null)}}catch(e){return $e(e,["Error while login in with GitHub!",e.message]),t.close(),void n(null)}window.setTimeout(a,700)}else n(null)},function(){var e=this,t=arguments;return new Promise((function(n,r){var o=i.apply(e,t);function a(e){Wc(o,n,r,a,s,"next",e)}function s(e){Wc(o,n,r,a,s,"throw",e)}a(void 0)}))});return function(){return s.apply(this,arguments)}}();return t&&a(),()=>{t&&(t.close(),n(null))}}),[t,n,r,o,e])}function Yc(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function Zc(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){Yc(a,r,o,i,s,"next",e)}function s(e){Yc(a,r,o,i,s,"throw",e)}i(void 0)}))}}const Xc={isLoginInProgress:!1,isLoggedIn:!1,isSessionExpired:!1,login:Zc((function*(){})),logout:()=>{}},Jc=(0,S.createContext)(Xc);function Qc(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function eu(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){Qc(a,r,o,i,s,"next",e)}function s(e){Qc(a,r,o,i,s,"throw",e)}i(void 0)}))}}function tu(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const nu=Object.freeze({sha:"<unknown>",date:void 0,author:{login:"unknown author",avatarURL:""},message:"",URL:""});class ru extends Xt{getFile(e,t,n,r){var o=this;return eu((function*(){return(yield o.postWithRefresh("/vcs.v1.VCSService/GetFile",JSON.stringify({repositoryURL:e,ref:t,localPath:n,rootPath:r}))).json()}))()}getCommits(e){var t=this;return eu((function*(){return yield Promise.all(e.map((({repositoryUrl:e,gitRef:n})=>e&&n?t.getCommit(e,n).catch((t=>(j.error(t,{info:`Error while fetching commit from repo "${e}" (${n})!'`}),nu))):nu)))}))()}refresh(){var e=this;return eu((function*(){return e.refreshSession()}))()}getCommit(e,t){var n=this;return eu((function*(){var r;const o=yield n.postWithRefresh("/vcs.v1.VCSService/GetCommit",JSON.stringify({repositoryURL:e,ref:t})),a=yield o.json();return(r=a).date&&(r.date=new Date(a.date)),a}))()}postWithRefresh(e,t){var n=this;return eu((function*(){var r;if(n.isRefreshing)return n.queueRequest(e,t);if(null===(r=n.sessionManager.getCookie())||void 0===r?void 0:r.isUserTokenExpired(ru.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 eu((function*(){return n.fetch(e,{method:"POST",body:t})}))()}refreshSession(){var e=this;return eu((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 eu((function*(){return new Promise(((r,o)=>{n.pendingQueue.push((a=>{a?o(a):r(n.post(e,t))}))}))}))()}flushQueue(e=void 0){this.pendingQueue.forEach((t=>t(e))),this.pendingQueue=[]}constructor(e){super(e),tu(this,"sessionManager",void 0),tu(this,"pendingQueue",void 0),tu(this,"isRefreshing",void 0),this.sessionManager=$c,this.isRefreshing=!1,this.pendingQueue=[]}}function ou(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function au(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){ou(a,r,o,i,s,"next",e)}function s(e){ou(a,r,o,i,s,"throw",e)}i(void 0)}))}}tu(ru,"BIAS_MS",3e5);const iu=btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(32)))),su="grafana-pyroscope-app.gitHubIntegration.dataSourceUid";function lu({dataSourceUid:e,children:t}){const n=ns.build(e,Ic),r=ns.build(e,ru),[o,a]=(0,S.useState)(Xc.isLoginInProgress),[i,s]=function(){const[e,t]=(0,S.useState)($c.getCookie());return[e,e=>{e?($c.setCookie(e),t($c.getCookie())):($c.deleteCookie(),t(void 0))}]}(),[l,c]=(0,S.useState)();(0,S.useEffect)((()=>{localStorage.getItem(su)!==e&&(s(""),localStorage.setItem(su,e||""))}),[e]),Hc({vcsClient:n,externalWindow:l,setExternalWindow:c,setSessionCookie:s,nonce:iu});const u=!!l&&!l.closed;u!==o&&a(u);const d=(0,S.useCallback)(au((function*(){try{yield function(e,t,n,r,o){return qc.apply(this,arguments)}(n,r,i,l,c)}catch(e){$e(e,["Failed to login to GitHub",e.message])}})),[n,r,i,l]);return w().createElement(Jc.Provider,{value:{isLoginInProgress:o,isLoggedIn:Boolean(i&&!i.isUserTokenExpired()),isSessionExpired:Boolean(null==i?void 0:i.isUserTokenExpired()),login:d,logout:()=>s("")}},t)}var cu=n(9105);function uu(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var du=function(e){return e.USER="user",e.LABELS="labels",e}({});const pu=(0,S.createContext)(void 0);function mu({children:e}){const[t,n]=(0,cu.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){uu(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 a=null==t||null===(o=t[e])||void 0===o?void 0:o[n];let i;return a?i="user":r&&(i="labels"),{functionVersion:a||r,functionVersionOrigin:i}}};return w().createElement(pu.Provider,{value:r},e)}function fu(e,t,n){const{saveOverride:r,deleteOverride:o,deleteAllOverrides:a,getFunctionVersion:i}=function(){const e=(0,S.useContext)(pu);if(void 0===e)throw new Error("useFunctionVersionContext must be used within a FunctionVersionProvider");return e}(),{functionVersion:s,functionVersionOrigin:l}=i(e,t,n);return{saveOverride:r,deleteOverride:o,deleteAllOverrides:a,functionVersion:s,functionVersionOrigin:l}}class hu extends o.BusEventWithPayload{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(hu,"type","remove-span-selector");var gu=n(219);const bu={metricsFromProfiles:!!a.config.featureToggles.metricsFromProfiles,grafanaAssistantInProfilesDrilldown:!!a.config.featureToggles.grafanaAssistantInProfilesDrilldown};function yu(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function vu(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){yu(e,t,n[t])}))}return e}function Eu({filters:e,maxNodes:t,spanSelector:n}){const r=e?[...e]:[];r.unshift({key:"service_name",operator:"=",value:"$serviceName"});const o=r.map((({key:e,operator:t,value:n})=>`${e}${t}"${n}"`)).join(",");return _o(new Lt.dt({datasource:Qr,queries:[vu({refId:"profile",queryType:"profile",profileTypeId:"$profileMetricId",labelSelector:`{${o},$filters}`,maxNodes:t},n&&{spanSelector:[n]})]}))}var Su=n(585);function wu(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Ou(e,t,n,r){var o,a=arguments.length,i=a<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)i=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(i=(a<3?o(i):a>3?o(t,n,i):o(t,n))||i);return a>3&&i&&Object.defineProperty(t,n,i),i}class Pu extends Su.Message{constructor(e,t,n,r,o){super(),wu(this,"profile_typeID",void 0),wu(this,"label_selector",void 0),wu(this,"start",void 0),wu(this,"end",void 0),wu(this,"max_nodes",void 0),this.profile_typeID=e,this.label_selector=t,this.start=n,this.end=r,this.max_nodes=o}}function xu(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function Cu(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){xu(a,r,o,i,s,"next",e)}function s(e){xu(a,r,o,i,s,"throw",e)}i(void 0)}))}}Ou([Su.Field.d(1,"string")],Pu.prototype,"profile_typeID",void 0),Ou([Su.Field.d(2,"string")],Pu.prototype,"label_selector",void 0),Ou([Su.Field.d(3,"int64")],Pu.prototype,"start",void 0),Ou([Su.Field.d(4,"int64")],Pu.prototype,"end",void 0),Ou([Su.Field.d(5,"int64")],Pu.prototype,"max_nodes",void 0);class Tu extends Xt{static buildPprofRequest(e,t,n){const{profileMetricId:r,labelsSelector:o}=Do(e),a=1e3*t.from.unix(),i=1e3*t.to.unix(),s=new Pu(r,o,a,i,n);return Pu.encode(s).finish()}selectMergeProfile({query:e,timeRange:t,maxNodes:n}){var r=this;return Cu((function*(){return(yield r.fetch("/querier.v1.QuerierService/SelectMergeProfile",{method:"POST",headers:{"content-type":"application/proto"},body:new Blob([Tu.buildPprofRequest(e,t,n)])})).blob()}))()}selectMergeProfileJson({profileMetricId:e,labelsSelector:t,start:n,end:r,stackTrace:o,maxNodes:a}){var i=this;return Cu((function*(){return(yield i.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:a})})).json()}))()}}function Au(e,t){const{serviceId:n,profileMetricId:r}=Do(e),o=`${t.from.format("YYYY-MM-DD_HHmm")}-to-${t.to.format("YYYY-MM-DD_HHmm")}`;return`${n.replace(/\//g,"-")}_${r}_${o}`}function Nu(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}const ku=new class extends G{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 a=n.apply(e,t);function i(e){Nu(a,r,o,i,s,"next",e)}function s(e){Nu(a,r,o,i,s,"throw",e)}i(void 0)}))})()}constructor(){super("https://flamegraph.com/api",{"content-type":"application/json"})}};function ju(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function Ru(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){ju(a,r,o,i,s,"next",e)}function s(e){ju(a,r,o,i,s,"throw",e)}i(void 0)}))}}function Iu(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class Du extends Lt.Bs{fetchFlamebearerProfile({dataSourceUid:e,query:t,timeRange:n,maxNodes:r}){return Ru((function*(){const o=ns.build(e,ac);let a;try{a=yield o.get({query:t,timeRange:n,format:"json",maxNodes:r||hl.maxNodes})}catch(e){return $e(e,["Error while loading flamebearer profile data!",e.message]),null}return a}))()}fetchPprofProfile({dataSourceUid:e,query:t,timeRange:n,maxNodes:r}){return Ru((function*(){const o=ns.build(e,Tu);let a;try{const e=yield o.selectMergeProfile({query:t,timeRange:n,maxNodes:r||hl.maxNodes});a=yield new Response(e.stream().pipeThrough(new CompressionStream("gzip"))).blob()}catch(e){return $e(e,["Failed to export to pprof!",e.message]),null}return a}))()}constructor(){super({key:"export-flame-graph-menu"}),Iu(this,"useSceneExportMenu",(({query:e,timeRange:t})=>{const n=Lt.jh.findByKeyAndType(this,"dataSource",mo).useState().value,[r]=dc(),{settings:o}=El();var a=this;const i=function(){var o=Ru((function*(){Ie("g_pyroscope_app_export_profile",{format:"json"});const o=yield a.fetchFlamebearerProfile({dataSourceUid:n,query:e,timeRange:t,maxNodes:r});if(!o)return;const i=`${Au(e,t)}.json`,s=`data:text/json;charset=utf-8,${encodeURIComponent(JSON.stringify(o))}`;at()(s,i)}));return function(){return o.apply(this,arguments)}}();var s=this;const l=function(){var o=Ru((function*(){Ie("g_pyroscope_app_export_profile",{format:"pprof"});const o=yield s.fetchPprofProfile({dataSourceUid:n,query:e,timeRange:t,maxNodes:r});if(!o)return;const a=`${Au(e,t)}.pb.gz`;at()(o,a)}));return function(){return o.apply(this,arguments)}}();var c=this;const u=function(){var o=Ru((function*(){Ie("g_pyroscope_app_export_profile",{format:"flamegraph.com"});const o=yield c.fetchFlamebearerProfile({dataSourceUid:n,query:e,timeRange:t,maxNodes:r});if(o)try{const n=yield ku.upload(Au(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 $e(e,["Failed to export to flamegraph.com!",e.message])}}));return function(){return o.apply(this,arguments)}}();return{data:{shouldDisplayFlamegraphDotCom:Boolean(null==o?void 0:o.enableFlameGraphDotComExport)},actions:{downloadPng:()=>{Ie("g_pyroscope_app_export_profile",{format:"png"});const n=`${Au(e,t)}.png`;document.querySelector('canvas[data-testid="flameGraph"]').toBlob((e=>{if(e)at()(e,n);else{const e=new Error("Error while creating the image, no blob.");$e(e,["Failed to export to png!",e.message])}}),"image/png")},downloadJson:i,downloadPprof:l,uploadToFlamegraphDotCom:u}}}))}}function _u(){return(0,S.useContext)(Jc)}function Lu(e){const{login:t,isSessionExpired:n}=_u(),{settings:r}=El(),a=null==r?void 0:r.enableFunctionDetails,[i,s]=(0,S.useState)([]),l=(0,S.useCallback)((({item:r},i)=>a&&0!==r.level?[{label:"Function details",icon:"info-circle",onClick:()=>{Ie("g_pyroscope_app_function_details_clicked"),s(function(e,t){let n=[];const r=t.fields.find((({name:e})=>"label"===e));if(!r)return n;const a=(0,o.getDisplayProcessor)({field:r,theme:(0,o.createTheme)()});let i=e;for(;i&&i.level>0;){var s;for(const e of i.itemIndexes)n.unshift(a(r.values[e]).text);i=null===(s=i.parents)||void 0===s?void 0:s[0]}return n}(r,i)),e.open("function-details"),n&&t()}}]:[]),[a,n,t,e]);return{data:{stacktrace:i},actions:{getExtraFlameGraphMenuItems:l}}}Iu(Du,"Component",(({model:e,query:t,timeRange:n})=>{const{actions:r}=e.useSceneExportMenu({query:t,timeRange:n});return w().createElement(i.Dropdown,{overlay:w().createElement(i.Menu,null,w().createElement(i.Menu.Item,{label:"png",onClick:r.downloadPng}),w().createElement(i.Menu.Item,{label:"json",onClick:r.downloadJson}),w().createElement(i.Menu.Item,{label:"pprof",onClick:r.downloadPprof}))},w().createElement(i.Button,{icon:"download-alt",size:"sm",variant:"secondary",fill:"outline","aria-label":"Export profile data",tooltip:"Export profile data"}))}));const Fu="gpt-4-1106-preview",Bu=({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 $u(e){const{reply:t,error:n}=function(e){const[t,n]=(0,S.useState)(""),[r,o]=(0,S.useState)(!1),[a,i]=(0,S.useState)(!1),[s,l]=(0,S.useState)([]),[c,u]=(0,S.useState)(null),d=(0,S.useCallback)((e=>{l(e),u(null),n(""),o(!0),i(!1),tc.qH({model:Fu,messages:e}).pipe(tc.qA()).subscribe({next:n,error(e){u(e),o(!1),i(!0)},complete(){o(!1),i(!0)}})}),[]),p=(0,S.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,S.useEffect)((()=>{if(s.length>0)return;const t=Bu(e);try{d([{role:"system",content:t.user}])}catch(e){u(e)}}),[s.length,e,d]),{reply:{text:t,hasStarted:r,hasFinished:a,messages:s,askFollowupQuestion:p},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 Mu=()=>({title:r.css`
margin: -4px 0 4px 0;
`,content:r.css``});function Vu({suggestionPromptInputs:e}){const t=(0,i.useStyles2)(Mu),{data:n,actions:r}=$u(e);return w().createElement(w().Fragment,null,w().createElement("h6",{className:t.title},"Code Optimization Suggestions"),w().createElement("div",{className:t.content},n.isLoading&&w().createElement(w().Fragment,null,w().createElement(i.Spinner,{inline:!0})," Analyzing..."),n.fetchError&&w().createElement(Sl,{severity:"error",title:"Error while fetching profiles!",message:"Sorry for any inconvenience, please try again later."}),n.llmError&&w().createElement(Sl,{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&&w().createElement(Xl,{reply:n.reply}),n.shouldDisplayFollowUpForm&&w().createElement(ec,{onSubmit:r.submitFollowupQuestion})))}const Uu=5;function Gu(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 qu(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Ku(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){qu(e,t,n[t])}))}return e}function zu(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 Wu(e,t){const{isLoggedIn:n}=_u(),{version:r}=t,[o,a]=(0,S.useState)(!1);var i,s,l;const{fileInfo:c,error:u,isFetching:d}=function({enabled:e,dataSourceUid:t,repository:n,gitRef:r,localPath:o,rootPath:a}){const i=ns.build(t,ru),{isFetching:s,error:l,data:c}=(0,K.I)({enabled:Boolean(e&&o),queryKey:["vcs-file",n,r,o,a],queryFn:()=>i.getFile(n,r,o,a).then((e=>({content:e.content,URL:e.URL}))).then((e=>({URL:e.URL,content:atob(e.content)})))});return{isFetching:s,error:i.isAbortError(l)?null:l,fileInfo:c}}({enabled:n,dataSourceUid:e,localPath:t.fileName,repository:null!==(i=null==r?void 0:r.repository)&&void 0!==i?i:"",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:""}),{snippetLines:p,allLines:m}=(0,S.useMemo)((()=>(null==c?void 0:c.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 a,i;return{line:e,number:r,cum:null!==(a=null==o?void 0:o.cum)&&void 0!==a?a:0,flat:null!==(i=null==o?void 0:o.flat)&&void 0!==i?i:0}}));if(0===t.size)return{snippetLines:[],allLines:o};const a=Math.max(0,n[0].line-Uu-1),i=Math.min(r.length,n[n.length-1].line+Uu);return{snippetLines:o.slice(a,i),allLines:o}}(c.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-Uu-1),r=t[t.length-1].line+Uu+1,o=[];for(let t=n+1;t<r;t++){const n=e.get(t);var a,i;o.push({line:void 0,number:t,cum:null!==(a=null==n?void 0:n.cum)&&void 0!==a?a:0,flat:null!==(i=null==n?void 0:n.flat)&&void 0!==i?i:0})}return{snippetLines:o,allLines:[]}}(t.callSites)),[null==c?void 0:c.content,t.callSites]);return{data:{fetchError:u,openAiSuggestions:o,isLoadingCode:d,unit:t.unit,githubUrl:(null==c?void 0:c.URL)?Gu(c.URL,t.startLine):void 0,snippetLines:p.map((e=>{var t;return zu(Ku({},e),{line:null!==(t=e.line)&&void 0!==t?t:"???"})})),allLines:m.map((e=>{var t;return zu(Ku({},e),{line:null!==(t=e.line)&&void 0!==t?t:"???"})})),noCodeAvailable:Boolean(u)||!m.some((e=>e.line))},actions:{setOpenAiSuggestions:a}}}function Hu(e){switch(e){case"nanoseconds":return(0,o.getValueFormat)("ns");case"microseconds":return(0,o.getValueFormat)("µs");case"milliseconds":return(0,o.getValueFormat)("ms");case"seconds":return(0,o.getValueFormat)("s");case"count":return(0,o.getValueFormat)("short");default:return(0,o.getValueFormat)(e)}}const Yu=({lines:e,unit:t,githubUrl:n,isLoadingCode:o,noCodeAvailable:a,onOptimizeCodeClick:s})=>{const l=(0,i.useStyles2)(ed),c=Hu(t),u=e=>{if(e<=0)return".";const t=c(e);return t.suffix?t.text+t.suffix:t.text};Xu(e);const[d,p]=e.reduce((([e,t],{flat:n,cum:r})=>[e+n,t+r]),[0,0]);return w().createElement("div",{"data-testid":"function-details-code-container"},w().createElement("div",{className:l.container},w().createElement("div",{className:l.header},w().createElement("div",{className:l.breakdownLabel},w().createElement("h6",null,"Breakdown per line"),w().createElement("span",null,o&&w().createElement(i.Spinner,{inline:!0}),!o&&a&&"(file information unavailable)")),w().createElement("div",{className:l.buttons},w().createElement(i.LinkButton,{disabled:Boolean(o||!n),href:n,target:"_blank",icon:"github",fill:"text"},"View on GitHub"),w().createElement(zl,{onClick:s,disabled:o||a,interactionName:"g_pyroscope_app_optimize_code_clicked"},"Optimize Code")))),w().createElement("pre",{className:l.codeBlock,"data-testid":"function-details-code"},w().createElement("div",{className:(0,r.cx)(l.highlighted,l.codeBlockHeader)},Zu("Total:",u(d),u(p)," (self, total)")),e.map((({line:e,number:t,cum:n,flat:r})=>w().createElement("div",{key:e+t+n+r,className:r+n>0?l.highlighted:""},Zu(`${t} `,u(r),u(n),e))))))},Zu=(e,t,n,r)=>{const o=e.padStart(7," ")+t.padStart(12," ")+n.padStart(12," ");return r?`${o} ${r}`:o},Xu=e=>{if(0===e.length)return;let t=Ju(e[0].line);for(let n=1;n<e.length;n++){const{line:r}=e[n];if(""===r.trim())continue;const o=Ju(r);t=Qu(t,o)}if(t)for(let n=0;n<e.length;n++)e[n].line=e[n].line.substring(t.length)},Ju=e=>{const t=e.match(/^[ \t]*/);var n;return null!==(n=null==t?void 0:t[0])&&void 0!==n?n:""},Qu=(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)},ed=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 td({dataSourceUid:e,functionDetails:t}){var n,r;const{data:o,actions:a}=Wu(e,t);return o.fetchError&&404!==(null===(r=o.fetchError)||void 0===r||null===(n=r.response)||void 0===n?void 0:n.status)&&$e(o.fetchError,["Failed to fetch file information!",o.fetchError.message]),w().createElement(w().Fragment,null,w().createElement(Yu,{lines:o.snippetLines,unit:o.unit,githubUrl:o.githubUrl,isLoadingCode:o.isLoadingCode,noCodeAvailable:o.noCodeAvailable,onOptimizeCodeClick:()=>{var e;a.setOpenAiSuggestions(!0),null===(e=document.getElementById("ai-suggestions-panel"))||void 0===e||e.scrollIntoView({behavior:"smooth"})}}),w().createElement("h6",{id:"ai-suggestions-panel",style:{height:0,marginBottom:0}}),o.openAiSuggestions?w().createElement(Vu,{suggestionPromptInputs:{functionDetails:t,lines:o.allLines}}):null)}const nd=e=>({ellipsis:r.css`
color: ${e.colors.primary.text};
text-overflow: ellipsis;
overflow: hidden;
direction: rtl;
white-space: nowrap;
`}),rd=({enableIntegration:e,repository:t})=>{const n=(0,i.useStyles2)(nd),{isLoginInProgress:r,isLoggedIn:o,login:a,logout:s}=_u();return e?r?w().createElement(w().Fragment,null,w().createElement(i.Spinner,null),w().createElement("span",null,"Connecting to GitHub...")):o?w().createElement(w().Fragment,null,w().createElement(i.Icon,{name:"github",size:"lg"}),w().createElement("a",{className:n.ellipsis,href:t.commitUrl,target:"_blank",rel:"noreferrer",title:"View commit"},w().createElement(i.Icon,{name:"external-link-alt"})," ",t.commitName),w().createElement(i.IconButton,{name:"signout",onClick:()=>s(),"aria-label":"Disconnect from GitHub",title:"Disconnect from GitHub"})):w().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):w().createElement(w().Fragment,null,"-")};function od(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ad(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 id(e,t){const n=e.map((e=>{var n;return ad(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){od(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 sd="https://github.com/";function ld(e,t){if(!(null==t?void 0:t.repository))return null;const n=t.repository,r=n.replace(sd,""),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 cd=(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:nu}};function ud(e,t,n,r,o,a,i){const s=new Set;a.locationId.forEach(((l,c)=>{const u=n.get(l);u&&u.line.forEach((n=>{const d=r.get(n.functionId);if(!d)return;if(t.stringTable[Number(d.name)]!==e)return;if(s.has(l))return;s.add(l);const p=i.get(u.mappingId)||cd(t,d,o.get(u.mappingId));i.set(u.mappingId,function(e,t,n,r){const o=Number(t.line),a=e.callSites.get(o)||{line:Number(t.line),flat:0,cum:0},i=0===r?n:0,s=n;return a.flat+=i,a.cum+=s,e.callSites.set(o,a),e}(p,n,Number(a.value[0]),c))}))}))}function dd(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function pd(){var e;return e=function*(e,t,n){const r=ns.build(e,ru),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},pd=function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){dd(a,r,o,i,s,"next",e)}function s(e){dd(a,r,o,i,s,"throw",e)}i(void 0)}))},pd.apply(this,arguments)}const md=e=>Array.from(e.callSites.values()).reduce(((e,{cum:t})=>e+t),0),fd=(e,t)=>md(t)-md(e);function hd(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function gd(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){hd(a,r,o,i,s,"next",e)}function s(e){hd(a,r,o,i,s,"throw",e)}i(void 0)}))}}const bd={repository:"",git_ref:"HEAD",root_path:""};function yd({dataSourceUid:e,query:t,timeRange:n,stackTrace:r}){const{profileMetricId:o,labelsSelector:a,serviceId:i}=Do(t),[s,l]=[n.from.unix(),n.to.unix()],{isLoggedIn:c}=_u(),u=ns.build(e,Tu),{functionVersion:d}=fu(e,i,bd),{isFetching:p,error:m,data:f}=(0,K.I)({enabled:Boolean(o&&a&&r.length>0&&s>0&&l>0),queryKey:["function-details",o,a,s,l,r,c,d],queryFn:gd((function*(){const t=yield u.selectMergeProfileJson({profileMetricId:o,labelsSelector:a,start:s,end:l,stackTrace:r,maxNodes:500}),n=function(e,t){var n,r,o,a;const i=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===(a=t.sample)||void 0===a||a.filter((e=>void 0!==e.locationId)).forEach((n=>ud(e,t,s,l,c,n,i))),Array.from(i.values())}(r[r.length-1],t).sort(fd);return c?function(e,t,n){return pd.apply(this,arguments)}(e,n,d||bd):n}))}),h=(0,S.useMemo)((()=>(null==f?void 0:f.length)?f:[{name:r.at(-1),startLine:void 0,fileName:"",callSites:new Map,unit:"",commit:nu}]),[f,r]);return{isFetching:p,error:u.isAbortError(m)?null:m,functionsDetails:h}}const vd=[60,3600,86400,604800,2592e3,31536e3,1/0],Ed=["second","minute","hour","day","week","month","year"],Sd=new Intl.RelativeTimeFormat("en-US",{numeric:"auto"});const wd=new Intl.DateTimeFormat("en-US",{year:"numeric",month:"long",day:"2-digit"});function Od(e){return e?`${wd.format(e)} (${function(e){const t=e.getTime(),n=Math.round((t-Date.now())/1e3),r=vd.findIndex((e=>e>Math.abs(n))),o=r?vd[r-1]:1;return Sd.format(Math.floor(n/o),Ed[r])}(e)})`:"?"}const Pd=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 xd({commit:e}){const t=(0,i.useStyles2)(Pd),{author:n,samples:r}=e,o=n.login,a=n.avatarURL,s=Hu(r.unit)(r.current),l=Math.round(r.current/r.total*100);return w().createElement("div",{className:t.container},w().createElement("div",{className:t.firstLine},w().createElement("span",{className:t.sha},kd(e.sha)),w().createElement("span",{className:t.sample},s.text,s.suffix," (",l,"%)")),w().createElement("div",{className:t.secondLine},a&&w().createElement("img",{className:t.avatar,src:a,alt:o}),w().createElement("span",null,o," on ",Od(e.date))),w().createElement("span",{className:t.message},jd(e.message)))}const Cd=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 Td({commit:e}){const t=(0,i.useStyles2)(Cd);return w().createElement("div",{className:t.container},w().createElement("span",{className:t.sha},kd(e.sha)),w().createElement("div",{className:t.message},w().createElement("span",null,jd(e.message))))}function Ad({commits:e,selectedCommit:t,onChange:n}){return w().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:Nd,onChange:e=>{e.value&&n(e.value)}})}function Nd(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?w().createElement(Td,{commit:r}):w().createElement(xd,{commit:r})}const kd=e=>e===nu.sha?e:e.substring(0,7),jd=e=>e.split("\n")[0],Rd=({onDismiss:e})=>w().createElement(i.Alert,{severity:"info",title:"Integrate with Github",buttonContent:"Dismiss",onRemove:e},w().createElement("p",null,"This language supports integration with ",w().createElement(i.Icon,{name:"github"})," GitHub."),w().createElement("p",null,"To activate this feature, you will need to add two new labels when sending profiles"," ",w().createElement("code",null,"service_repository")," and ",w().createElement("code",null,"service_git_ref"),"."," "),w().createElement("p",null,"They should respectively be set to the full repository GitHub URL and the current"," ",w().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."),w().createElement(i.Icon,{name:"document-info"})," ",w().createElement(i.TextLink,{href:"https://grafana.com/docs/grafana-cloud/monitor-applications/profiles/pyroscope-github-integration/",external:!0},"Learn more"));function Id({isLoading:e,children:t}){return e?w().createElement(i.Spinner,{inline:!0}):w().createElement(w().Fragment,null,t)}const Dd=(0,S.memo)(Id);function _d(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Ld(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){_d(e,t,n[t])}))}return e}function Fd(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 Bd=e=>{var t,n,r,o;const{serviceName:s,version:l,datasourceUid:c,saveOverrides:u,functionVersionOrigin:d}=e,[p,m]=w().useState(!1),{register:f,handleSubmit:h,formState:{errors:g},reset:b}=(0,ps.mN)({mode:"onChange"});return w().createElement(w().Fragment,null,w().createElement(i.Button,{"aria-label":"override repository settings",variant:"secondary",fill:"text",size:"sm",icon:"pen",onClick:()=>{m(!0),b(l)}},d===du.USER?w().createElement(i.Text,{element:"span",color:"secondary"},"(user set)"):""),p&&w().createElement(i.Modal,{title:d===du.USER?"Edit repository details override":"Add new repository details override",isOpen:p,onDismiss:()=>m(!1)},w().createElement("form",{onSubmit:h((e=>{u(c,s,{repository:e.repository,git_ref:e.git_ref||"HEAD",root_path:e.root_path||""}),m(!1)}))},w().createElement(i.Alert,{severity:"info",title:"Github Integration labels"},w().createElement("p",null,"To activate GitHub Integration feature, you will need to add two new labels when sending profiles:",w().createElement("code",null,"service_repository")," and ",w().createElement("code",null,"service_git_ref"),"."),w().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.")),w().createElement(i.Field,{label:"Data source"},w().createElement(a.DataSourcePicker,{current:c,disabled:!0})),w().createElement(i.Field,{label:"Service name"},w().createElement(i.Input,{disabled:!0,value:s})),w().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()},w().createElement(i.Input,Fd(Ld({},f("repository",{required:"Repository name is required"})),{placeholder:"Enter GitHub repo name, https://github.com/org/repo"}))),w().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()},w().createElement(i.Input,Fd(Ld({},f("git_ref")),{placeholder:"HEAD"}))),w().createElement(i.Field,{label:"Path to root"},w().createElement(i.Input,Fd(Ld({},f("root_path")),{placeholder:"Enter root path"}))),w().createElement(i.Stack,{direction:"row"},w().createElement(i.Button,{type:"submit"},d===du.USER?"Edit":"Add"),d===du.USER&&w().createElement(i.Button,{type:"button",variant:"destructive",onClick:()=>{e.deleteOverride(c,s),b(),m(!1)}},"Delete override"),w().createElement(i.ConfirmButton,{confirmVariant:"destructive",confirmText:"Remove all",onConfirm:()=>{e.deleteAllOverrides(),b(),m(!1)}},"Remove all overrides")))))};function $d(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function Md(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Vd(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){Md(e,t,n[t])}))}return e}function Ud(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 Gd extends Lt.Bs{constructor(){super({key:"function-details-panel"}),Md(this,"useSceneFunctionDetailsPanel",((e,t)=>{var n;const r=Lt.jh.findByKeyAndType(this,"dataSource",mo).useState().value,o=Lt.jh.findByKeyAndType(this,"dataSource",mo).useState().text,a=Co(this,"serviceName"),i=po(this,"filters"),{functionsDetails:s,error:l,isFetching:c}=yd({dataSourceUid:r,query:i,timeRange:t,stackTrace:e}),{saveOverride:u,deleteOverride:d,functionVersion:p,deleteAllOverrides:m,functionVersionOrigin:f}=fu(r,a,s[0].version),[h,g]=(0,S.useState)(),[b,y]=(0,S.useState)(s[0]),[v,E]=(0,S.useState)(_.has(_.KEYS.GITHUB_INTEGRATION));s&&h!==s&&(g(s),b!==s[0]&&y(s[0]));const w=((null==p?void 0:p.repository)||"").startsWith(sd);const O=null==b||null===(n=b.fileName)||void 0===n?void 0:n.endsWith(".go"),P=!v&&!w&&O,x=(0,S.useMemo)((()=>s.map((e=>Array.from(e.callSites.values()).reduce(((e,{cum:t})=>e+t),0))).reduce(((e,t)=>e+t),0)),[s]),C=id(s,x),T=C.find((({sha:e})=>{var t;return e===(null==b||null===(t=b.commit)||void 0===t?void 0:t.sha)}));return{data:{serviceName:a,dataSourceName:o,isLoading:c,fetchFunctionDetailsError:l,functionDetails:Ud(Vd({},b),{version:Vd({},null==b?void 0:b.version,p)}),functionVersionOrigin:f,repository:ld(w,p),commits:C,selectedCommit:T,isGitHubSupported:O,shouldDisplayGitHubBanner:P,dataSourceUid:r},actions:{deleteFunctionOverride(e,t){d(e,t)},deleteFunctionAllOverrides(){m()},saveFunctionDetails(e,t,n){u(e,t,n)},selectCommit(e){const t=s.find((({commit:t})=>t.sha===e.sha));y(t)},copyFilePathToClipboard(){return(e=function*(){try{(null==b?void 0:b.fileName)&&(yield navigator.clipboard.writeText(b.fileName),Ve(["File path copied to clipboard!"]))}catch(e){}},function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){$d(a,r,o,i,s,"next",e)}function s(e){$d(a,r,o,i,s,"throw",e)}i(void 0)}))})();var e},dismissGitHubBanner(){_.set(_.KEYS.GITHUB_INTEGRATION,{}),E(!0)}}}}))}}Md(Gd,"LABEL_WIDTH",16),Md(Gd,"Component",(({model:e,timeRange:t,stackTrace:n,onClose:r})=>{const o=(0,i.useStyles2)(qd),{data:a,actions:s}=e.useSceneFunctionDetailsPanel(n,t);return w().createElement(ql,{className:o.sidePanel,title:"Function Details",isLoading:!1,headerActions:w().createElement(i.IconButton,{name:"times-circle",variant:"secondary","aria-label":"close",onClick:r}),dataTestId:"function-details-panel"},w().createElement("div",{className:o.content},a.fetchFunctionDetailsError&&w().createElement(Sl,{severity:"error",title:"Error while fetching function details!",error:a.fetchFunctionDetailsError}),w().createElement("div",{className:o.container},w().createElement("div",{className:o.row,"data-testid":"row-function-name"},w().createElement(i.InlineLabel,{width:Gd.LABEL_WIDTH},"Function name"),w().createElement(i.Tooltip,{content:a.functionDetails.name,placement:"top"},w().createElement("span",{className:o.textValue},a.functionDetails.name))),w().createElement("div",{className:o.row,"data-testid":"row-start-line"},w().createElement(i.InlineLabel,{tooltip:"The line where this function definition starts",width:Gd.LABEL_WIDTH},"Start line"),w().createElement("span",{className:o.textValue},w().createElement(Dd,{isLoading:a.isLoading},void 0!==a.functionDetails.startLine?a.functionDetails.startLine:"-"))),w().createElement("div",{className:o.row,"data-testid":"row-file-path"},w().createElement(i.InlineLabel,{tooltip:"File path where that function is defined",width:Gd.LABEL_WIDTH},"File"),w().createElement(Dd,{isLoading:a.isLoading},a.functionDetails.fileName?w().createElement(w().Fragment,null,w().createElement(i.Tooltip,{content:a.functionDetails.fileName,placement:"top"},w().createElement("span",{className:o.textValue},"","/"===(null==(l=a.functionDetails.fileName)?void 0:l[0])?l.substring(1)+"/":l)),w().createElement(i.IconButton,{name:"clipboard-alt",tooltip:"Copy to clipboard",onClick:s.copyFilePathToClipboard})):"-")),a.shouldDisplayGitHubBanner&&w().createElement("div",{className:o.row,"data-testid":"row-github-banner"},w().createElement(Rd,{onDismiss:s.dismissGitHubBanner})),w().createElement("div",{className:o.row,"data-testid":"row-repository"},w().createElement(i.InlineLabel,{tooltip:"The repository configured for the selected service",width:Gd.LABEL_WIDTH},"Repository"),w().createElement(Dd,{isLoading:a.isLoading},a.repository?a.repository.isGitHub?w().createElement(rd,{enableIntegration:a.isGitHubSupported,repository:a.repository}):w().createElement(i.TextLink,{href:a.repository.url,external:!0},a.repository.url):"-"),!a.isLoading&&w().createElement(Bd,{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})),w().createElement("div",{className:o.row,"data-testid":"row-commit"},w().createElement(i.InlineLabel,{width:Gd.LABEL_WIDTH,tooltip:"The version of the application (commit) where the function is defined. Use the dropdown menu to target a specific commit."},"Commit"),w().createElement(Dd,{isLoading:a.isLoading},w().createElement(Ad,{commits:a.commits,selectedCommit:a.selectedCommit,onChange:s.selectCommit})))),w().createElement(td,{dataSourceUid:a.dataSourceUid,functionDetails:a.functionDetails})));var l}));const qd=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 Kd(e){const{spanSelector:t,removeSpanSelector:n}=e,r=(0,i.useStyles2)(zd);return w().createElement("div",{className:r.container},w().createElement(i.Tooltip,{content:`You have added a span selector to the flamegraph query (${t}).`,placement:"top"},w().createElement("span",null,"Span selector added")),w().createElement(i.Button,{size:"md",fill:"text",variant:"secondary",icon:"times",tooltip:"Remove span selector from query",tooltipPlacement:"top",onClick:()=>{n()}}))}const zd=()=>({container:r.css`
padding: 0 4px;
`});function Wd(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class Hd extends Lt.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)===o.LoadingState.Done&&this.setState({lastTimeRange:e.data.timeRange})})))}));return()=>{t.unsubscribe(),null==e||e.unsubscribe()}}buildTitle(){const e=Co(this,"serviceName"),t=Xr(Co(this,"profileMetricId")).type;return w().createElement(w().Fragment,null,w().createElement(te,{size:"small"}),"Flame graph for ",e," (",t,")")}removeSpanSelector(){this.publishEvent(new hu({}),!0)}constructor(){super({key:"flame-graph",$data:new Lt.dt({datasource:Qr,queries:[]}),lastTimeRange:void 0,exportMenu:new Du,aiPanel:new sc,functionDetailsPanel:new Gd,createRecordingRuleModal:new _s}),Wd(this,"useSceneFlameGraph",(e=>{var t,n,r,a,s;const{isLight:l}=(0,i.useTheme2)(),c=(0,S.useMemo)((()=>()=>(0,o.createTheme)({colors:{mode:l?"light":"dark"}})),[l]),[u]=dc(),{settings:d,error:p}=El(),{$data:m,lastTimeRange:f,exportMenu:h,aiPanel:g,functionDetailsPanel:b,createRecordingRuleModal:y}=this.useState();p&&Me(["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,S.useEffect)((()=>{u&&this.setState({$data:Eu({maxNodes:u,spanSelector:e})})}),[u,e]);const v=m.useState(),E=null==v||null===(t=v.data)||void 0===t?void 0:t.state,w=E===o.LoadingState.Error?(null==v||null===(r=v.data)||void 0===r||null===(n=r.errors)||void 0===n?void 0:n[0])||new Error("Unknown error!"):null,O=E===o.LoadingState.Loading,P=null==v||null===(s=v.data)||void 0===s||null===(a=s.series)||void 0===a?void 0:a[0],x=Number(null==P?void 0:P.length)>1,C=po(this,"filters");return{data:{title:this.buildTitle(),isLoading:O,isFetchingProfileData:O,hasProfileData:x,profileData:P,spanSelector:e,fetchProfileError:w,settings:d,export:{menu:h,query:C,timeRange:f},ai:{panel:g,fetchParams:[{query:C,timeRange:f}]},gitHub:{panel:b,timeRange:f},recordingRules:{modal:y}},actions:{getTheme:c}}})),this.addActivationHandler(this.onActivate.bind(this))}}Wd(Hd,"Component",(({model:e})=>{var t;const n=(0,i.useStyles2)(Yd),r=Co(e,"spanSelector"),{data:o,actions:a}=e.useSceneFlameGraph(r),s=fl(),l=Lu(s),{settings:c}=El(),[u,d]=(0,S.useState)({isOpen:!1}),p=(m=e=>{d({isOpen:!0,functionName:e})},{data:{},actions:{getExtraFlameGraphMenuItems:(0,S.useCallback)((({item:e,label:t})=>[{label:"Create recording rule",icon:"download-alt",onClick:()=>m("total"===t&&0===e.level?void 0:t)}]),[m])}});var m;const{isAvailable:f}=(0,gu.useAssistant)(),h=bu.grafanaAssistantInProfilesDrilldown&&f&&!localStorage.getItem("grafana-pyroscope-app.forceShowAIButton"),g=o.isLoading||!o.hasProfileData;(0,S.useEffect)((()=>{g&&s.close()}),[g,s]);const b=(0,S.useMemo)((()=>w().createElement(w().Fragment,null,o.title,o.isLoading&&w().createElement(i.Spinner,{inline:!0,className:n.spinner}))),[o.isLoading,o.title,n.spinner]);return w().createElement("div",{className:n.flex},w().createElement(ql,{dataTestId:"flame-graph-panel",className:n.flamegraphPanel,title:b,isLoading:o.isLoading,headerActions:w().createElement(w().Fragment,null,r&&w().createElement(Kd,{spanSelector:r,removeSpanSelector:()=>e.removeSpanSelector()}),!h&&w().createElement(zl,{disabled:g||s.isOpen("ai"),onClick:()=>s.open("ai"),interactionName:"g_pyroscope_app_explain_flamegraph_clicked"},"Explain Flame Graph"))},o.fetchProfileError&&w().createElement(Sl,{severity:"error",title:"Error while loading profile data!",error:o.fetchProfileError}),!o.fetchProfileError&&w().createElement(rt.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)&&bu.metricsFromProfiles?p.actions.getExtraFlameGraphMenuItems(e,t):[]],extraHeaderElements:w().createElement(o.export.menu.Component,{model:o.export.menu,query:o.export.query,timeRange:o.export.timeRange}),keepFocusOnDataChange:!0})),s.isOpen("ai")&&w().createElement(o.ai.panel.Component,{model:o.ai.panel,fetchParams:o.ai.fetchParams,onClose:s.close}),s.isOpen("function-details")&&w().createElement(o.gitHub.panel.Component,{model:o.gitHub.panel,timeRange:o.gitHub.timeRange,stackTrace:l.data.stacktrace,onClose:s.close}),w().createElement(o.recordingRules.modal.Component,{model:o.recordingRules.modal,isModalOpen:u.isOpen,functionName:u.functionName,onDismiss:()=>d({isOpen:!1}),onCreated:()=>{d({isOpen:!1})}}))}));const Yd=e=>({flex:r.css`
display: flex;
`,flamegraphPanel:r.css`
min-width: 0;
flex-grow: 1;
`,spinner:r.css`
margin-left: ${e.spacing(1)};
`});class Zd extends Lt.Bs{onActivate(e){e&&this.initVariables(e);const t=Lt.jh.findByKeyAndType(this,"profileMetricId",ao);return t.setState({query:ao.QUERY_SERVICE_NAME_DEPENDENT}),t.update(!0),()=>{t.setState({query:ao.QUERY_DEFAULT}),t.update(!0)}}initVariables(e){const{serviceName:t,profileMetricId:n,filters:r}=e.queryRunnerParams;if(t){Lt.jh.findByKeyAndType(this,"serviceName",co).changeValueTo(t)}if(n){Lt.jh.findByKeyAndType(this,"profileMetricId",ao).changeValueTo(n)}if(r){Lt.jh.findByKeyAndType(this,"filters",xo).setState({filters:r})}}getVariablesAndGridControls(){return{variables:[Lt.jh.findByKeyAndType(this,"serviceName",co),Lt.jh.findByKeyAndType(this,"profileMetricId",ao),Lt.jh.findByKeyAndType(this,"filters",xo)],gridControls:[]}}static Component({model:e}){const t=(0,i.useStyles2)(Xd),{mainTimeseries:n,body:r}=e.useState();return w().createElement("div",{className:t.flex},w().createElement("div",{className:t.mainTimeseries},w().createElement(n.Component,{model:n})),w().createElement(r.Component,{model:r}))}constructor({item:e}){super({key:"explore-service-flame-graph",mainTimeseries:new bi({item:e,headerActions:e=>[new Xa({type:"view-labels",item:e}),new Fa({item:e})]}),body:new Hd}),this.addActivationHandler(this.onActivate.bind(this,e))}}const Xd=e=>({flex:r.css`
display: flex;
flex-direction: column;
width: 100%;
gap: ${e.spacing(1)};
`,mainTimeseries:r.css`
height: ${bi.MIN_HEIGHT}px;
`});function Jd(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function Qd(){return ep.apply(this,arguments)}function ep(){var e;return e=function*(){Ie("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",Ji().from),t.get("to")||t.set("to",Ji().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(o.dateMath.parse(n).valueOf()))})),e}().toString()),Ve(["Link copied to clipboard!"])}catch(e){j.error(e,{info:"Error while creating the shareable link!"})}},ep=function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){Jd(a,r,o,i,s,"next",e)}function s(e){Jd(a,r,o,i,s,"throw",e)}i(void 0)}))},ep.apply(this,arguments)}function tp({options:e,value:t,onChange:n}){const o=(0,i.useStyles2)(np),a=e.findIndex((e=>e.value===t));return w().createElement("div",{className:o.explorationTypeContainer,"data-testid":"exploration-types"},w().createElement("div",{className:o.label},"Exploration"),w().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 p=[c&&"active","primary"===u&&"primary"];return w().createElement(S.Fragment,{key:s.value},w().createElement(i.Button,{className:(0,r.cx)(o.button,...p),variant:u,size:"sm","aria-label":s.label,icon:s.icon,onClick:c?L:()=>n(s.value),tooltip:s.description,tooltipPlacement:"top","data-testid":c?"is-active":void 0},s.label),l<e.length-3&&w().createElement("div",{className:a!==e.length-1&&l<=a-1?(0,r.cx)(o.arrow,"arrow",...p):o.arrow}))}))))}const np=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 rp(e){const t=null===a.useChromeHeaderHeight||void 0===a.useChromeHeaderHeight?void 0:(0,a.useChromeHeaderHeight)(),n=(0,i.useStyles2)(op,null!=t?t:0),{data:o,actions:s}=function({explorationType:e,controls:t,body:n,$variables:r,onChangeExplorationType:o}){const[a,i]=e===ip.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(),d=s.useState().value,f=(0,Ae.useNavigate)();return{data:{explorationType:e,dataSourceVariable:s,timePickerControl:a,refreshPickerControl:i,sceneVariables:c,gridControls:u,body:n,dataSourceUid:d,serviceName:e!==ip.ALL_SERVICES&&e!==ip.FAVORITES?Co(r,"serviceName"):void 0},actions:{onChangeExplorationType:o,onClickShareLink:Qd,onClickRecordingRules:(0,S.useCallback)((()=>{Ie("g_pyroscope_app_open_recording_rules_view"),f(`${p}${m.RECORDING_RULES}`,{state:{referrer:window.location.href}})}),[f]),onClickAdHoc:(0,S.useCallback)((()=>{Ie("g_pyroscope_app_upload_ad_hoc_clicked"),f(`${p}${m.ADHOC}`,{state:{referrer:window.location.href}})}),[f]),onClickUserSettings:(0,S.useCallback)((()=>{Ie("g_pyroscope_app_user_settings_clicked"),f(`${p}${m.SETTINGS}`,{state:{referrer:window.location.href}})}),[f])}}}(e),{settings:l}=El(),{explorationType:c,dataSourceVariable:u,timePickerControl:d,refreshPickerControl:f,sceneVariables:h,gridControls:g,serviceName:b}=o,{component:y}=(0,a.usePluginComponent)("grafana-o11yinsights-app/insights-launcher/v1"),v=w().createElement(i.Menu,null,w().createElement(i.Menu.Item,{ariaLabel:"View recording rules",label:"View recording rules",onClick:s.onClickRecordingRules}),w().createElement(i.Menu.Item,{ariaLabel:"Add recording rule",label:"Add recording rule",onClick:e.onCreateRecordingRule}));return w().createElement("div",{className:n.header,"data-testid":"allControls"},w().createElement(Oc,null),w().createElement("div",{className:n.appControls,"data-testid":"appControls"},w().createElement("div",{className:n.appControlsLeft},w().createElement(tp,{options:sp.EXPLORATION_TYPE_OPTIONS,value:c,onChange:s.onChangeExplorationType})),w().createElement("div",{className:n.appControlsRight},y&&w().createElement(i.ErrorBoundary,null,(({error:e})=>e?void 0:w().createElement(y,{dataSourceUid:u.getValueText(),serviceName:b}))),d&&w().createElement(d.Component,{key:d.state.key,model:d}),f&&w().createElement(f.Component,{key:f.state.key,model:f}),w().createElement("div",{className:n.appMiscButtons},(null==l?void 0:l.enableMetricsFromProfiles)&&bu.metricsFromProfiles&&w().createElement(w().Fragment,null,w().createElement(i.Dropdown,{overlay:v},w().createElement(i.IconButton,{name:"gf-prometheus",tooltip:"Recording rules","aria-label":"Recording rules"}))),w().createElement(i.IconButton,{name:"upload",tooltip:"Upload ad hoc profiles",onClick:s.onClickAdHoc}),w().createElement(i.IconButton,{name:"cog",tooltip:"View/edit tenant settings",onClick:s.onClickUserSettings}),w().createElement(i.IconButton,{name:"share-alt",tooltip:"Copy shareable link to the clipboard",onClick:s.onClickShareLink}),w().createElement(le,null)))),w().createElement("div",{id:`scene-controls-${c}`,className:n.sceneControls,"data-testid":"sceneControls"},w().createElement(i.Field,{label:u.state.label,className:(0,r.cx)(n.sceneVariable,u.state.name),"data-testid":u.state.name},w().createElement(u.Component,{model:u})),h.map((e=>w().createElement(i.Field,{key:e.state.name,label:"Filters"===e.state.label?w().createElement("div",{className:n.sceneVariableLabel},w().createElement(i.Icon,{name:"filter",className:n.icon}),e.state.label):e.state.label,className:(0,r.cx)(n.sceneVariable,e.state.name),"data-testid":e.state.name},w().createElement(e.Component,{model:e})))),g.map((e=>w().createElement(i.Field,{key:e.state.key,id:e.state.key,className:n.gridControl,label:""},w().createElement(e.Component,{model:e}))))))}const op=(e,t)=>({header:r.css`
background-color: ${e.colors.background.canvas};
position: sticky;
top: ${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)};
`,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 ap(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var ip=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 sp extends Lt.Bs{onActivate(){const e=this.subscribeToVariableChanges(),t=this.subscribeToEvents();return this.state.explorationType||this.setExplorationType({type:sp.DEFAULT_EXPLORATION_TYPE}),()=>{t.unsubscribe(),e.unsubscribe()}}getUrlState(){return{explorationType:this.state.explorationType}}updateFromUrl(e){if("string"==typeof e.explorationType&&e.explorationType!==this.state.explorationType){const t=e.explorationType;this.setExplorationType({type:Object.values(ip).includes(t)?t:sp.DEFAULT_EXPLORATION_TYPE})}}registerRuntimeDataSources(){try{Lt.Go.registerRuntimeDataSource({dataSource:new ds}),Lt.Go.registerRuntimeDataSource({dataSource:new Da}),Lt.Go.registerRuntimeDataSource({dataSource:new Jo})}catch(e){const{message:t}=e;/A runtime data source with uid (.+) has already been registered/.test(t)||$e(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=Lt.jh.findByKeyAndType(this,"dataSource",mo).subscribeToState(((e,t)=>{e.value&&e.value!==t.value&&(xo.resetAll(this),this.resetSpanSelector())})),t=Lt.jh.findByKeyAndType(this,"serviceName",co).subscribeToState(((e,t)=>{e.value&&e.value!==t.value&&(xo.resetAll(this),e.options.some((e=>e.value===t.value))&&this.resetSpanSelector())})),n=Lt.jh.findByKeyAndType(this,"profileMetricId",ao).subscribeToState(((e,t)=>{e.value&&e.value!==t.value&&this.resetSpanSelector()})),r=Lt.jh.findByKeyAndType(this,"filters",xo).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(za,(e=>{this.setExplorationType({type:"profiles",comesFromUserAction:!0,item:e.payload.item})})),t=this.subscribeToEvent(Ka,(e=>{this.setExplorationType({type:"labels",comesFromUserAction:!0,item:e.payload.item})})),n=this.subscribeToEvent(qa,(e=>{this.setExplorationType({type:"flame-graph",comesFromUserAction:!0,item:e.payload.item})})),r=this.subscribeToEvent(yi,(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(hu,(()=>{this.resetSpanSelector()}));return{unsubscribe(){r.unsubscribe(),n.unsubscribe(),t.unsubscribe(),e.unsubscribe(),o.unsubscribe()}}}setExplorationType({type:e,comesFromUserAction:t,item:n,bodySceneOptions:r}){t&&(Ft(),this.resetVariables(e)),this.setState({explorationType:e,body:this.buildBodyScene(e,n,r)})}resetSpanSelector(){Lt.jh.findByKeyAndType(this,"spanSelector",Qi).reset()}resetVariables(e){Lt.jh.findByKeyAndType(this,"quick-filter",Aa).reset(),Lt.jh.findByKeyAndType(this,"groupBy",fi).changeValueTo(fi.DEFAULT_VALUE),Lt.jh.findByKeyAndType(this,"panel-type-switcher",No).reset(),this.resetSpanSelector(),["labels","flame-graph","diff-flame-graph"].includes(e)||Lt.jh.findByKeyAndType(this,"filters",xo).reset()}buildBodyScene(e,t,n){let r;switch(e){case"profiles":r=new Zi({item:t});break;case"labels":r=new Yi({item:t});break;case"flame-graph":r=new Zd({item:t});break;case"diff-flame-graph":r=new Nc(n||{});break;case"favorites":r=new si;break;default:r=new Qa}return new Lt.n1({direction:"column",primary:r})}static Component({model:e}){const t=(0,i.useStyles2)(lp),{data:n,actions:r}=e.useProfilesExplorer(),{explorationType:o,controls:a,body:s,$variables:l,dataSourceUid:c}=n,[u,d]=(0,S.useState)({isOpen:!1}),{createRecordingRuleModal:p}=e.useState();return w().createElement(mu,null,w().createElement(lu,{dataSourceUid:c},w().createElement(rp,{explorationType:o,controls:a,body:s,$variables:l,onChangeExplorationType:r.onChangeExplorationType,onCreateRecordingRule:()=>{d({isOpen:!0})}}),w().createElement("div",{className:t.body,"data-testid":"sceneBody"},s&&w().createElement(s.Component,{model:s})),u.isOpen&&w().createElement(_s.Component,{model:p,isModalOpen:u.isOpen,functionName:u.functionName,onDismiss:()=>d({isOpen:!1}),onCreated:()=>{d({isOpen:!1})}})))}constructor(){super({key:"profiles-explorer",explorationType:void 0,body:void 0,$timeRange:new Lt.JZ(Ji()),$variables:new Lt.Pj({variables:[new mo,new co,new ao,new xo({key:"filters"}),new xo({key:"filtersBaseline"}),new xo({key:"filtersComparison"}),new fi,new Qi]}),createRecordingRuleModal:new _s,controls:[new Lt.KE({isOnCanvas:!0}),new Lt.WM({isOnCanvas:!0})],gridControls:[new Aa({placeholder:""}),new No,new Pa,new Ca]}),ap(this,"_urlSync",new Lt.So(this,{keys:["explorationType"]})),ap(this,"onChangeExplorationType",(e=>{Ie("g_pyroscope_app_exploration_type_clicked",{explorationType:e}),this.setExplorationType({type:e,comesFromUserAction:!0})})),ap(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}}})),(0,Lt.Is)().initSync(this),this.registerRuntimeDataSources(),this.addActivationHandler(this.onActivate.bind(this))}}ap(sp,"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"}]),ap(sp,"DEFAULT_EXPLORATION_TYPE",sp.EXPLORATION_TYPE_OPTIONS[0].value);const lp=()=>({body:r.css`
position: relative;
z-index: 0;
background: transparent;
`});function cp(){const e=(0,S.useMemo)((()=>new sp),[]);return De("explore"),w().createElement(e.Component,{model:e})}function up({rule:e,confirm:t}){const[n,r]=w().useState(!1);return w().createElement(w().Fragment,null,w().createElement(i.IconButton,{name:"trash-alt",onClick:()=>r(!0),variant:"destructive","aria-label":"Delete recording rule"}),w().createElement(i.ConfirmModal,{isOpen:n,title:"Delete recording rule",body:`Are you sure you want to delete ${e.metricName} recording rule?`,confirmText:"Yes",onConfirm:()=>{t(),r(!1)},onDismiss:()=>r(!1)}))}function dp(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function pp(){const{recordingRules:e,error:t,remove:n,isFetching:r}=Ts();return{data:{recordingRules:e,fetchError:t,isFetching:r},actions:{removeRecordingRule(e){return(t=function*(){try{yield n(e),Ve([`Recording rule ${e.metricName} deleted!`])}catch(t){$e(t,[`Failed to delete recording rule ${e.metricName}.`])}},function(){var e=this,n=arguments;return new Promise((function(r,o){var a=t.apply(e,n);function i(e){dp(a,r,o,i,s,"next",e)}function s(e){dp(a,r,o,i,s,"throw",e)}i(void 0)}))})();var t}}}}function mp(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function fp(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 hp(){const e=(0,i.useStyles2)(gp),{data:t,actions:n}=pp(),{recordingRules:o}=t;if(t.isFetching)return w().createElement(me,null);const a=[{id:"metricName",header:"Name",sortType:"alphanumeric"},{id:"serviceName",header:"Service Name",sortType:"alphanumeric",cell:e=>e.row.original.serviceName||w().createElement(i.Text,{element:"span",color:"secondary"},"All services")},{id:"profileType",header:"Profile Type",sortType:"alphanumeric"},{id:"functionName",header:"Function Name",sortType:"alphanumeric",cell:e=>e.row.original.functionName||w().createElement(i.Text,{element:"span",color:"secondary"},"Total (all functions)")},{id:"groupBy",header:"Labels",cell:t=>{var n;const r=null===(n=t.row.original.groupBy)||void 0===n?void 0:n.filter((e=>!e.match(/^__\S+__$/)));return r&&0!==r.length?w().createElement(i.TagList,{className:e.tagList,displayMax:4,tags:r}):w().createElement(i.Text,{element:"span",color:"secondary"},"None")}},{id:"actions",header:"Actions",disableGrow:!0,cell:e=>{const t=e.row.original;return t.readonly?w().createElement(i.Tooltip,{content:"This rule is provisioned with tenant settings and cannot be deleted."},w().createElement(i.Icon,{name:"info-circle"})):w().createElement(up,{rule:t,confirm:()=>n.removeRecordingRule(t)})}}],s=(o||[]).map((e=>{const t=Xr(e.profileType);return fp(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){mp(e,t,n[t])}))}return e}({},e),{profileType:`${t.group}/${t.type}`})})),l=!s||0===s.length;let c=null;return c=t.fetchError?w().createElement(bp,{error:t.fetchError}):l?w().createElement(i.EmptyState,{message:"No recording rules",variant:"not-found",button:w().createElement(Ne,null)},'Open a flame graph, click on the "total" block at the top and select "Create recording rule" from the context menu to define a new rule.'):w().createElement("div",null,w().createElement(i.InteractiveTable,{className:(0,r.css)({marginBottom:"32px"}),columns:a,pageSize:10,data:s||[],getRowId:e=>e.id}),w().createElement(Ne,null)),w().createElement(w().Fragment,null,w().createElement(pe,{title:"Recording rules"}),c)}const gp=()=>({tagList:r.css`
flex-direction: row;
justify-content: start;
`});function bp({error:e}){var t;let n="Error while retrieving recording rules";return 404===(null===(t=e.response)||void 0===t?void 0:t.status)?n="This feature requires Pyroscope with recording_rules flag enabled.":e.message&&(n=e.message),w().createElement(i.EmptyState,{message:"Error while retrieving recording rules",variant:"not-found",button:w().createElement(Ne,null)},n)}function yp(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function vp(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Ep(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){vp(e,t,n[t])}))}return e}function Sp(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 wp(){const{settings:e,error:t,mutate:n}=El(),r=dc()[1],[o,a]=(0,S.useState)(null!=e?e:hl);return(0,S.useEffect)((()=>{e&&a(e)}),[e]),{data:Sp(Ep({},o),{fetchError:t}),actions:{toggleCollapsedFlamegraphs(){a((e=>Sp(Ep({},e),{collapsedFlamegraphs:!e.collapsedFlamegraphs})))},updateMaxNodes(e){a((t=>Sp(Ep({},t),{maxNodes:Number(e.target.value)})))},toggleEnableFlameGraphDotComExport(){a((e=>Sp(Ep({},e),{enableFlameGraphDotComExport:!e.enableFlameGraphDotComExport})))},toggleEnableFunctionDetails(){a((e=>Sp(Ep({},e),{enableFunctionDetails:!e.enableFunctionDetails})))},toggleEnableMetricsFromProfiles(){a((e=>Sp(Ep({},e),{enableMetricsFromProfiles:!e.enableMetricsFromProfiles})))},saveSettings(){return(e=function*(){r(o.maxNodes);try{yield n(o),Ve(["Plugin settings successfully saved!"])}catch(e){$e(e,["Error while saving the plugin settings!","Please try again later, sorry for the inconvenience."])}},function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){yp(a,r,o,i,s,"next",e)}function s(e){yp(a,r,o,i,s,"throw",e)}i(void 0)}))})();var e}}}}function Op({children:e}){const t=(0,i.useStyles2)(Pp),{data:n,actions:o}=wp();return n.fetchError&&$e(n.fetchError,["Error while retrieving the plugin settings!","Please try to reload the page, sorry for the inconvenience."]),w().createElement("form",{className:t.settingsForm,onSubmit:function(e){e.preventDefault(),o.saveSettings()}},w().createElement(i.FieldSet,{label:"Flame graph","data-testid":"flamegraph-settings"},w().createElement(i.InlineFieldRow,null,w().createElement(i.InlineField,{label:"Collapsed flame graphs",labelWidth:24},w().createElement(i.InlineSwitch,{label:"Toggle collapsed flame graphs",name:"collapsed-flamegraphs",value:n.collapsedFlamegraphs,onChange:o.toggleCollapsedFlamegraphs}))),w().createElement(i.InlineFieldRow,null,w().createElement(i.InlineField,{label:"Maximum number of nodes",tooltip:"",labelWidth:24},w().createElement(i.Input,{name:"max-nodes",type:"number",min:"1",value:n.maxNodes,onChange:o.updateMaxNodes})))),w().createElement(i.FieldSet,{label:"Function details","data-testid":"function-details-settings"},w().createElement(i.InlineFieldRow,null,w().createElement(i.InlineField,{label:"Enable function details",labelWidth:24,tooltip:w().createElement("div",{className:t.tooltip},w().createElement("p",null,"The function details feature enables mapping of resource usage to lines of source code. If the GitHub integration is configured, then the source code will be downloaded from GitHub."),w().createElement("p",null,w().createElement("a",{href:"https://grafana.com/docs/grafana-cloud/monitor-applications/profiles/pyroscope-github-integration/",target:"_blank",rel:"noreferrer noopener"},"Learn more"))),interactive:!0},w().createElement(i.InlineSwitch,{label:"Toggle function details",name:"function-details-feature",value:n.enableFunctionDetails,onChange:o.toggleEnableFunctionDetails})))),bu.metricsFromProfiles&&w().createElement(i.FieldSet,{label:"Metrics from profiles","data-testid":"metrics-from-profiles"},w().createElement(i.Alert,{severity:"info",title:"",className:(0,r.css)({maxWidth:"1000px"})},n.enableMetricsFromProfiles?w().createElement(w().Fragment,null,w().createElement("p",null,"Disabling this feature only hides it from the UI. No existing recording rules are removed. These rules will remain active and continue to export metrics, which will still impact your bill."),w().createElement("p",null,"To stop exporting data, delete all related recording rules before disabling this feature.")):w().createElement("p",null,"Enabling this feature lets you define recording rules from Profiles Drilldown. Any recording rules you create will send new metrics to your Grafana Cloud instance, increasing your data usage in Grafana Mimir and potentially affecting your bill.")),w().createElement(i.InlineFieldRow,null,w().createElement(i.InlineField,{label:"Enable metrics from profiles",tooltip:"Allows creating recording rules from profiles",labelWidth:30},w().createElement(i.InlineSwitch,{label:"Enable metrics from profiles",name:"metrics-from-profiles",value:n.enableMetricsFromProfiles,onChange:o.toggleEnableMetricsFromProfiles})))),e)}const Pp=e=>({settingsForm:r.css`
& > fieldset {
border: 0 none;
border-bottom: 1px solid ${e.colors.border.weak};
padding-left: 0;
}
& > fieldset > legend {
font-size: ${e.typography.h4.fontSize};
}
`,buttons:r.css`
display: flex;
gap: ${e.spacing(1)};
margin-top: ${e.spacing(3)};
`,tooltip:r.css`
p {
margin: ${e.spacing(1)};
}
a {
color: ${e.colors.text.link};
}
em {
font-style: normal;
font-weight: ${e.typography.fontWeightBold};
}
`}),xp="grafana-pyroscope-app/settings/v1";function Cp(){var e;const[t]=dc(),[n,r]=(0,S.useState)(0),o=(0,Ae.useNavigate)(),i=(0,Ae.useLocation)(),s=(0,S.useRef)(null===(e=i.state)||void 0===e?void 0:e.referrer),{components:l,isLoading:c}=(0,a.usePluginComponents)({extensionPointId:xp});return{data:{activeTab:n,components:l,isLoading:c},actions:{setActiveTab(e){r(e)},goBack(){if(!s.current)return void o(`${p}${m.EXPLORE}`);const e=new URL(s.current);t&&e.searchParams.set("maxNodes",String(t)),o(`${e.pathname}${e.search}`)}}}}function Tp(){const e=(0,i.useStyles2)(Ap),{data:t,actions:n}=Cp();if(De("settings"),t.isLoading)return w().createElement("div",null,"Loading...");const r=[{title:"UI Settings",content:w().createElement(Op,null,w().createElement("div",{className:e.buttons},w().createElement(i.Button,{variant:"primary",type:"submit"},"Save settings"),w().createElement(Ne,{onClick:n.goBack})))}],o={datasourceUid:q.selectDefaultDataSource().uid,backButton:w().createElement("div",{className:e.buttons},w().createElement(Ne,{onClick:n.goBack}))},a=[...r,...t.components.map((e=>{var t;return{title:(null===(t=e.meta)||void 0===t?void 0:t.title)||"Unknown Extension",content:w().createElement(e,o)}}))];return w().createElement(w().Fragment,null,w().createElement(pe,{title:"Profiles settings (tenant)"}),a.length>1&&w().createElement(w().Fragment,null,w().createElement(i.TabsBar,null,a.map(((e,r)=>w().createElement(i.Tab,{key:`settings-tab-${r}`,label:e.title,active:t.activeTab===r,onChangeTab:()=>n.setActiveTab(r)})))),w().createElement(i.Space,{v:2})),a[t.activeTab].content)}const Ap=e=>({buttons:r.css`
display: flex;
gap: ${e.spacing(1)};
margin-top: ${e.spacing(3)};
`});function Np(){return w().createElement(Ae.Routes,null,w().createElement(Ae.Route,{path:m.EXPLORE,element:w().createElement(cp,null)}),w().createElement(Ae.Route,{path:m.ADHOC,element:w().createElement(It,null)}),w().createElement(Ae.Route,{path:m.SETTINGS,element:w().createElement(Tp,null)}),w().createElement(Ae.Route,{path:m.RECORDING_RULES,element:w().createElement(hp,null)}),w().createElement(Ae.Route,{path:m.GITHUB_CALLBACK,element:w().createElement(_t,null)}),w().createElement(Ae.Route,{path:"/*",element:w().createElement(Ae.Navigate,{to:`${p}${m.EXPLORE}`,replace:!0})}))}function kp({error:e}){return w().createElement(a.PluginPage,{layout:o.PageLayoutType.Canvas},w().createElement("div",{className:"pyroscope-app"},w().createElement(pe,{title:"Grafana Profiles Drilldown"}),w().createElement(Sl,{severity:"error",title:"Fatal error!",message:"Please try reloading the page or, if the problem persists, contact your organization admin. Sorry for the inconvenience.",error:e,errorContext:{handheldBy:"React error boundary"}})))}function jp(){const e=(0,i.useStyles2)(Rp),[t,n]=(0,S.useState)();return t?w().createElement(kp,{error:t}):w().createElement(i.ErrorBoundary,{onError:n},(()=>w().createElement(E.Ht,{client:s},w().createElement(Te,null,w().createElement("div",{className:e.pageContainer},w().createElement(a.PluginPage,{layout:o.PageLayoutType.Custom},w().createElement("div",{className:"pyroscope-app"},w().createElement(Np,null))))))))}!function(){if(v())return;const e=function(){const e=g();if(e&&b.has(e))return b.get(e)}();if(!e)return;const{environment:t,faroUrl:n,appName:r}=e,{apps:o,bootData:i,buildInfo:s}=a.config,u=o[d].version,m=i.user.email,h=`v${s.version} (${s.edition})`;var E;E=(0,l.p)({url:n,app:{name:r,release:u,version:f,environment:t,namespace:h},user:{email:m},instrumentations:[...(0,c.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(p)?(e.meta.view={name:new URLSearchParams(null===(r=e.meta.page)||void 0===r?void 0:r.url).get("explorationType")||""},e):null}}),y=E}();const Rp=e=>({pageContainer:r.css`
display: flex;
flex-direction: column;
padding: ${e.spacing(1)} ${e.spacing(2)} ${e.spacing(2)} ${e.spacing(2)};
flex-basis: 100%;
flex-grow: 1;
`})}}]);
//# sourceMappingURL=133.js.map?_cache=493b83f22c40807ec531