import*as Common from"../common/common.js";import*as Host from"../host/host.js";import*as SDK from"../sdk/sdk.js";import{Memory}from"./LineLevelProfile.js";let liveHeapProfileInstance;export class LiveHeapProfile{constructor(){this._running=!1,this._sessionId=0,this._loadEventCallback=()=>{},this._setting=Common.Settings.Settings.instance().moduleSetting("memoryLiveHeapProfile"),this._setting.addChangeListener((e=>e.data?this._startProfiling():this._stopProfiling())),this._setting.get()&&this._startProfiling()}static instance(e={forceNew:null}){const{forceNew:o}=e;return liveHeapProfileInstance&&!o||(liveHeapProfileInstance=new LiveHeapProfile),liveHeapProfileInstance}run(){return Promise.resolve()}modelAdded(e){e.startSampling(1e4)}modelRemoved(e){}async _startProfiling(){if(this._running)return;this._running=!0;const e=this._sessionId;SDK.SDKModel.TargetManager.instance().observeModels(SDK.HeapProfilerModel.HeapProfilerModel,this),SDK.SDKModel.TargetManager.instance().addModelListener(SDK.ResourceTreeModel.ResourceTreeModel,SDK.ResourceTreeModel.Events.Load,this._loadEventFired,this);do{const o=SDK.SDKModel.TargetManager.instance().models(SDK.HeapProfilerModel.HeapProfilerModel),s=await Promise.all(o.map((e=>e.getSamplingProfile())));if(e!==this._sessionId)break;Memory.instance().reset();for(let e=0;e<s.length;++e){const t=s[e];t&&Memory.instance().appendHeapProfile(t,o[e].target())}await Promise.race([new Promise((e=>setTimeout(e,Host.InspectorFrontendHost.isUnderTest()?10:5e3))),new Promise((e=>{this._loadEventCallback=e}))])}while(e===this._sessionId);SDK.SDKModel.TargetManager.instance().unobserveModels(SDK.HeapProfilerModel.HeapProfilerModel,this),SDK.SDKModel.TargetManager.instance().removeModelListener(SDK.ResourceTreeModel.ResourceTreeModel,SDK.ResourceTreeModel.Events.Load,this._loadEventFired,this);for(const o of SDK.SDKModel.TargetManager.instance().models(SDK.HeapProfilerModel.HeapProfilerModel))o.stopSampling();Memory.instance().reset()}_stopProfiling(){this._running&&(this._running=!1,this._sessionId++)}_loadEventFired(){this._loadEventCallback()}}