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