import*as c from"./../../core/common/common.js";import*as T from"./../../core/host/host.js";import*as f from"./../../core/i18n/i18n.js";import*as I from"./../../core/platform/platform.js";import*as a from"./../../core/sdk/sdk.js";import*as S from"./../emulation/emulation.js";import*as r from"./web-vitals-injected/spec/spec.js";var h={lcpEmulationWarning:"Simulating a new device after the page loads can affect LCP. Reload the page after simulating a new device for accurate LCP data.",lcpVisibilityWarning:"LCP value may be inflated because the page started loading in the background."},y=f.i18n.registerUIStrings("models/live-metrics/LiveMetrics.ts",h),g=f.i18n.getLocalizedString.bind(void 0,y),l="DevTools Performance Metrics",u,m=class{static#t;static async get(){if(!this.#t){let e=new URL("./web-vitals-injected/web-vitals-injected.generated.js",import.meta.url),t=await fetch(e);this.#t=await t.text()}return this.#t}},M=class p extends c.ObjectWrapper.ObjectWrapper{#t=!1;#e;#d;#c;#s;#a;#r;#i=new Map;#l=new Map;#n=[];#u;#I=new c.Mutex.Mutex;#m=S.DeviceModeModel.DeviceModeModel.tryInstance();constructor(){super();let e=a.TargetManager.TargetManager.instance();e.observeTargets(this,{scoped:!0}),e.addModelListener(a.ResourceTreeModel.ResourceTreeModel,a.ResourceTreeModel.Events.PrimaryPageChanged,this.#S,this)}#S(e){let t=a.TargetManager.TargetManager.instance().primaryPageTarget();t&&(t!==this.#e||e.data.type==="Activation")&&(this.#g(),this.#o(),this.#y(t))}async#y(e){this.#e&&await this.disable(),this.#e=e,await this.enable()}static instance(e={forceNew:!1}){let{forceNew:t}=e;return(!u||t)&&(u=new p),u}get lcpValue(){return this.#s}get clsValue(){return this.#a}get inpValue(){return this.#r}get interactions(){return this.#i}get layoutShifts(){return this.#n}async logInteractionScripts(e){if(!this.#e)return!1;let t=this.#c;if(!t)return!1;let i=[];for(let n of e.longAnimationFrameTimings)for(let s of n.scripts){let o=s.startTime+s.duration;if(o<e.startTime)continue;let d=Math.round(o-Math.max(e.startTime,s.startTime));i.push({"Blocking duration":d,"Invoker type":s.invokerType||null,Invoker:s.invoker||null,Function:s.sourceFunctionName||null,Source:s.sourceURL||null,"Char position":s.sourceCharPosition||null})}try{let n=r.LOAF_LIMIT*r.SCRIPTS_PER_LOAF_LIMIT,s=i.length===n?` (limited to ${n})`:"",o=e.longAnimationFrameTimings.length===r.LOAF_LIMIT?` (limited to last ${r.LOAF_LIMIT})`:"";await this.#e.runtimeAgent().invoke_evaluate({expression:`
          console.group('[DevTools] Long animation frames for ${e.duration}ms ${e.interactionType} interaction');
          console.log('Scripts${s}:');
          console.table(${JSON.stringify(i)});
          console.log('Intersecting long animation frame events${o}:', ${JSON.stringify(e.longAnimationFrameTimings)});
          console.groupEnd();
        `,contextId:t})}catch{return!1}return!0}#f(){this.#u=Date.now()}async#h(e,t){if(!this.#e)return null;let i=this.#e.model(a.RuntimeModel.RuntimeModel);if(!i)return null;let n=this.#e.model(a.DOMModel.DOMModel);if(!n)return null;let{result:s}=await this.#e.runtimeAgent().invoke_evaluate({expression:`window.getNodeForIndex(${e})`,contextId:t});if(!s)return null;let o;try{o=i.createRemoteObject(s);let d=await n.pushObjectAsNodeToFrontend(o);return d||null}catch{return null}finally{o?.release()}}#o(){this.dispatchEventToListeners("status",{lcp:this.#s,cls:this.#a,inp:this.#r,interactions:this.#i,layoutShifts:this.#n})}setStatusForTesting(e){this.#s=e.lcp,this.#a=e.cls,this.#r=e.inp,this.#i=e.interactions,this.#n=e.layoutShifts,this.#o()}async#p(e){let t=e.data,i=[this.#s?.nodeRef,...this.#i.values().map(o=>o.nodeRef),...this.#n.flatMap(o=>o.affectedNodeRefs)].filter(o=>!!o),n=new Set(i.map(o=>o.backendNodeId())),s=await t.pushNodesByBackendIdsToFrontend(n);if(s){for(let o=0;o<i.length;o++){let d=s.get(i[o].backendNodeId());d&&(i[o]=d)}this.#o()}}async#D(e,t){switch(e.name){case"LCP":{let i=[],n={value:e.value,phases:e.phases,warnings:i};if(e.nodeIndex!==void 0){let s=await this.#h(e.nodeIndex,t);s&&(n.nodeRef=s)}this.#u&&Date.now()-this.#u<500&&i.push(g(h.lcpEmulationWarning)),e.startedHidden&&i.push(g(h.lcpVisibilityWarning)),this.#s=n;break}case"CLS":{let i={value:e.value,clusterShiftIds:e.clusterShiftIds};this.#a=i;break}case"INP":{let i={value:e.value,phases:e.phases,interactionId:`interaction-${e.entryGroupId}-${e.startTime}`};this.#r=i;break}case"InteractionEntry":{let i=I.MapUtilities.getWithDefault(this.#l,e.entryGroupId,()=>[]),n=i.find(s=>Math.abs(s.nextPaintTime-e.nextPaintTime)<8);if(n||(n={interactionId:`interaction-${e.entryGroupId}-${e.startTime}`,interactionType:e.interactionType,duration:e.duration,eventNames:[],phases:e.phases,startTime:e.startTime,nextPaintTime:e.nextPaintTime,longAnimationFrameTimings:e.longAnimationFrameEntries},i.push(n),this.#i.set(n.interactionId,n)),n.eventNames.includes(e.eventName)||n.eventNames.push(e.eventName),e.nodeIndex!==void 0){let s=await this.#h(e.nodeIndex,t);s&&(n.nodeRef=s)}break}case"LayoutShift":{let i=e.affectedNodeIndices.map(o=>this.#h(o,t)),n=(await Promise.all(i)).filter(o=>!!o),s={score:e.score,uniqueLayoutShiftId:e.uniqueLayoutShiftId,affectedNodeRefs:n};this.#n.push(s);break}case"reset":{this.#g();break}}this.#o()}#g(){this.#s=void 0,this.#a=void 0,this.#r=void 0,this.#i.clear(),this.#l.clear(),this.#n=[]}#x(e){if(!this.#e)return!1;let i=this.#e.model(a.RuntimeModel.RuntimeModel)?.executionContext(e);if(!i?.frameId)return!1;let s=this.#e.model(a.ResourceTreeModel.ResourceTreeModel)?.mainFrame?.id;return!!(s&&i.frameId===s)}async#M(e){let{data:t}=e;t.name===r.EVENT_BINDING_NAME&&await this.#I.run(async()=>{let i=JSON.parse(t.payload);if(i.name==="reset"){if(!this.#x(t.executionContextId))return;this.#c=t.executionContextId}this.#c===t.executionContextId&&await this.#D(i,t.executionContextId)})}async#T(){let e=this.#e;if(!e)return;let t=e.model(a.RuntimeModel.RuntimeModel);if(!t)return;let i=t.executionContexts().filter(n=>n.name===l&&!n.isDefault).map(n=>e.runtimeAgent().invoke_evaluate({expression:`window?.${r.INTERNAL_KILL_SWITCH}?.()`,contextId:n.id}));await Promise.all(i)}clearInteractions(){this.#i.clear(),this.#l.clear(),this.#o()}clearLayoutShifts(){this.#n=[],this.#o()}async targetAdded(e){e===a.TargetManager.TargetManager.instance().primaryPageTarget()&&(this.#e=e,await this.enable())}async targetRemoved(e){e===this.#e&&(await this.disable(),this.#e=void 0)}async enable(){if(T.InspectorFrontendHost.isUnderTest()||!this.#e||this.#t||this.#e.type()!==a.Target.Type.FRAME)return;let e=this.#e.model(a.DOMModel.DOMModel);if(!e)return;e.addEventListener(a.DOMModel.Events.DocumentUpdated,this.#p,this);let t=this.#e.model(a.RuntimeModel.RuntimeModel);if(!t)return;t.addEventListener(a.RuntimeModel.Events.BindingCalled,this.#M,this),await t.addBinding({name:r.EVENT_BINDING_NAME,executionContextName:l}),await this.#T();let i=await m.get();if(!this.#e)return;let{identifier:n}=await this.#e?.pageAgent().invoke_addScriptToEvaluateOnNewDocument({source:i,worldName:l,runImmediately:!0});this.#d=n,this.#m?.addEventListener("Updated",this.#f,this),this.#t=!0}async disable(){if(!this.#e||!this.#t)return;this.#c=void 0,await this.#T();let e=this.#e.model(a.RuntimeModel.RuntimeModel);e&&(await e.removeBinding({name:r.EVENT_BINDING_NAME}),e.removeEventListener(a.RuntimeModel.Events.BindingCalled,this.#M,this));let t=this.#e.model(a.DOMModel.DOMModel);t&&t.removeEventListener(a.DOMModel.Events.DocumentUpdated,this.#p,this),this.#d&&await this.#e.pageAgent().invoke_removeScriptToEvaluateOnNewDocument({identifier:this.#d}),this.#d=void 0,this.#m?.removeEventListener("Updated",this.#f,this),this.#t=!1}};export{M as LiveMetrics};
//# sourceMappingURL=live-metrics.js.map
