UNPKG

@react-native/debugger-frontend

Version:
2 lines (1 loc) • 28 kB
import*as e from"../../../core/sdk/sdk.js";import*as t from"../types/types.js";import*as n from"../../../core/platform/platform.js";import*as r from"../helpers/helpers.js";import*as i from"../handlers/handlers.js";import*as a from"../../../core/common/common.js";const s=new Map,o=new Map;async function l(t,n){const r=s.get(t)?.get(n);if(void 0!==r)return r;const i=e.TargetManager.TargetManager.instance().primaryPageTarget(),a=i?.model(e.DOMModel.DOMModel);if(!a)return null;const o=await a.pushNodesByBackendIdsToFrontend(new Set([n])),l=o?.get(n)||null,c=s.get(t)||new Map;return c.set(n,l),s.set(t,c),l}const c=new WeakMap;function d(e,n){const r=c.get(n);if(r)return r;const i=new Set;if(t.Events.isLayout(n))n.args.endData?.layoutRoots.forEach((e=>i.add(e.nodeId)));else if(t.Events.isSyntheticLayoutShift(n)&&n.args.data?.impacted_nodes)n.args.data.impacted_nodes.forEach((e=>i.add(e.node_id)));else if(t.Events.isLargestContentfulPaintCandidate(n)&&void 0!==n.args.data?.nodeId)i.add(n.args.data.nodeId);else if(t.Events.isPaint(n)&&void 0!==n.args.data.nodeId)i.add(n.args.data.nodeId);else if(t.Events.isPaintImage(n)&&void 0!==n.args.data.nodeId)i.add(n.args.data.nodeId);else if(t.Events.isScrollLayer(n)&&void 0!==n.args.data.nodeId)i.add(n.args.data.nodeId);else if(t.Events.isSyntheticAnimation(n)&&void 0!==n.args.data.beginEvent.args.data.nodeId)i.add(n.args.data.beginEvent.args.data.nodeId);else if(t.Events.isDecodeImage(n)){const t=e.ImagePainting.paintImageForEvent.get(n);void 0!==t?.args.data.nodeId&&i.add(t.args.data.nodeId)}else if(t.Events.isDrawLazyPixelRef(n)&&n.args?.LazyPixelRef){const t=e.ImagePainting.paintImageByDrawLazyPixelRef.get(n.args.LazyPixelRef);void 0!==t?.args.data.nodeId&&i.add(t.args.data.nodeId)}else t.Events.isParseMetaViewport(n)&&void 0!==n.args?.data.node_id&&i.add(n.args.data.node_id);return c.set(n,i),i}async function u(t,n){const r=o.get(t)?.get(n);if(r)return r;const i=e.TargetManager.TargetManager.instance().primaryPageTarget(),a=i?.model(e.DOMModel.DOMModel);if(!a)return new Map;const s=await a.pushNodesByBackendIdsToFrontend(new Set(n))||new Map,l=o.get(t)||new Map;return l.set(n,s),o.set(t,l),s}const h=new Map,p=new Map;var m=Object.freeze({__proto__:null,clearCacheForTesting:function(){s.clear(),o.clear(),h.clear(),p.clear()},domNodeForBackendNodeID:l,domNodesForMultipleBackendNodeIds:u,extractRelatedDOMNodesFromEvent:async function(e,t){const n=d(e,t);return n.size?await u(e,Array.from(n)):null},nodeIdsForEvent:d,normalizedImpactedNodesForLayoutShift:async function(t,n){const r=p.get(t)?.get(n);if(r)return r;const i=n.args?.data?.impacted_nodes;if(!i)return[];let a=null;const s=e.TargetManager.TargetManager.instance().primaryPageTarget(),o=await(s?.runtimeAgent().invoke_evaluate({expression:"window.devicePixelRatio"}));if("number"===o?.result.type&&(a=o?.result.value??null),!a)return i;const l=[];for(const e of i){const t={...e};for(let n=0;n<e.old_rect.length;n++)t.old_rect[n]/=a;for(let n=0;n<e.new_rect.length;n++)t.new_rect[n]/=a;l.push(t)}const c=p.get(t)||new Map;return c.set(n,l),p.set(t,c),l},sourcesForLayoutShift:async function(e,t){const n=h.get(e)?.get(t);if(n)return n;const r=t.args.data?.impacted_nodes;if(!r)return[];const i=[];await Promise.all(r.map((async t=>{const n=await l(e,t.node_id);n&&i.push({previousRect:new DOMRect(t.old_rect[0],t.old_rect[1],t.old_rect[2],t.old_rect[3]),currentRect:new DOMRect(t.new_rect[0],t.new_rect[1],t.new_rect[2],t.new_rect[3]),node:n})})));const a=h.get(e)||new Map;return a.set(t,i),h.set(e,a),i}});const f=new WeakMap;var g=Object.freeze({__proto__:null,frameClosestToTimestamp:function(e,t){const r=n.ArrayUtilities.nearestIndexFromEnd(e.frames,(e=>e.screenshotEvent.ts<t));return null===r?null:e.frames[r]},fromParsedTrace:function(e,t){const r=[],i=void 0!==t?t:e.Meta.traceBounds.min,a=e.Meta.traceBounds.range,s=f.get(e)?.get(i);if(s)return s;const o=e.Screenshots.screenshots??e.Screenshots.legacySyntheticScreenshots??[];for(const e of o){if(e.ts<i)continue;const t={index:r.length,screenshotEvent:e};r.push(t)}const l={zeroTime:i,spanTime:a,frames:Array.from(r)};return n.MapUtilities.getWithDefault(f,e,(()=>new Map)).set(i,l),l}});const v=new Set(["(program)","(idle)","(root)"]);var T=Object.freeze({__proto__:null,calculateWindow:function(e,n){if(!n.length)return e;const i=n.filter((e=>!(t.Events.isProfileCall(e)&&(v.has(e.callFrame.functionName)||!e.callFrame.functionName))));if(0===i.length)return e;function a(e,t){let n=e;const a=i[n],s=r.Timing.eventTimingsMicroSeconds(a);let o=(s.startTime+s.endTime)/2,l=0;const c=Math.sign(t-e);for(let a=e;a!==t;a+=c){const e=i[a],t=r.Timing.eventTimingsMicroSeconds(e),s=(t.startTime+t.endTime)/2;l<.1*Math.abs(o-s)&&(n=a,o=s,l=0),l+=t.duration}return n}const s=a(i.length-1,0),o=a(0,s),l=r.Timing.eventTimingsMicroSeconds(i[o]),c=r.Timing.eventTimingsMicroSeconds(i[s]);let d=l.startTime,u=c.endTime;const h=u-d;return h<.1*e.range?e:(d=t.Timing.Micro(Math.max(d-.05*h,e.min)),u=t.Timing.Micro(Math.min(u+.05*h,e.max)),{min:d,max:u,range:t.Timing.Micro(u-d)})}});var S=Object.freeze({__proto__:null,forNewRecording:async function(t,n,r,i){try{if(t)return{dataOrigin:"CPUProfile"};const a=e.CPUThrottlingManager.CPUThrottlingManager.instance().hasPrimaryPageTargetSet()?await Promise.race([e.CPUThrottlingManager.CPUThrottlingManager.instance().getHardwareConcurrency(),new Promise((e=>{setTimeout((()=>e(void 0)),1e3)}))]):void 0,s=e.CPUThrottlingManager.CPUThrottlingManager.instance().cpuThrottlingRate(),o=e.NetworkManager.MultitargetNetworkManager.instance().isThrottling()?e.NetworkManager.MultitargetNetworkManager.instance().networkConditions():void 0;let l,c;return o&&(l={download:o.download,upload:o.upload,latency:o.latency,packetLoss:o.packetLoss,packetQueueLength:o.packetQueueLength,packetReordering:o.packetReordering,targetLatency:o.targetLatency},c="function"==typeof o.title?o.title():o.title),{source:"DevTools",startTime:n?new Date(n).toJSON():void 0,emulatedDeviceTitle:r,cpuThrottling:1!==s?s:void 0,networkThrottling:c,networkThrottlingConditions:l,hardwareConcurrency:a,dataOrigin:"TraceEvents",cruxFieldData:i}}catch{return{}}}});function I(e){const t=(e=e.replace(/\?$/,"")).lastIndexOf("node_modules");return-1!==t&&(e=e.substring(t)),e}function k(e){for(const[t,n]of e){if(n.duplicates.sort(((e,t)=>t.attributedSize-e.attributedSize)),n.duplicates.length>1){const e=n.duplicates[0].attributedSize;n.duplicates=n.duplicates.filter((t=>t.attributedSize/e>=.1))}n.duplicates=n.duplicates.filter((e=>e.attributedSize>=512)),n.duplicates.length<=1?e.delete(t):n.estimatedDuplicateBytes=n.duplicates.slice(1).reduce(((e,t)=>e+t.attributedSize),0)}}function M(e,t,n=0){const r=e.indexOf(t,n);return-1===r?e.length:r}function C(e){const t=e.split("node_modules/"),n=M(e=t[t.length-1],"/");return"@"===e[0]?e.slice(0,M(e,"/",n+1)):e.slice(0,n)}function E(e){return new Map([...e].sort(((e,t)=>t[1].estimatedDuplicateBytes-e[1].estimatedDuplicateBytes)))}var y=Object.freeze({__proto__:null,computeScriptDuplication:function(e){const t=new Map;for(const r of e.scripts){if(!r.content||!r.sourceMap)continue;const e=i.ModelHandlers.Scripts.getScriptGeneratedSizes(r);if(!e)continue;if("errorMessage"in e){console.error(e.errorMessage);continue}const a=[];t.set(r,a);const s=r.sourceMap.sourceURLs();for(let t=0;t<s.length;t++){if((n=s[t]).includes("webpack/bootstrap")||n.includes("(webpack)/buildin")||n.includes("external "))continue;const r=e.files[s[t]];a.push({source:I(s[t]),resourceSize:r})}}var n;const r=new Map;for(const[e,n]of t)for(const t of n){let n=r.get(t.source);n||(n={estimatedDuplicateBytes:0,duplicates:[]},r.set(t.source,n)),n.duplicates.push({script:e,attributedSize:t.resourceSize})}const a=function(e){const t=new Map;for(const[n,r]of e){if(!n.includes("node_modules")){t.set(n,r);continue}const e="node_modules/"+C(n),i=t.get(e)??{duplicates:[],estimatedDuplicateBytes:0};t.set(e,i);for(const{script:e,attributedSize:t}of r.duplicates){let n=i.duplicates.find((t=>t.script===e));n||(n={script:e,attributedSize:0},i.duplicates.push(n)),n.attributedSize+=t}}return t}(r);return k(r),k(a),{duplication:E(r),duplicationGroupedByNodeModules:E(a)}},getNodeModuleName:C,normalizeDuplication:k,normalizeSource:I});const w=new Map;function b(e,n){let r=w.get(n);r||(r=new Map,w.set(n,r));const i=r.get(e);if(i)return i;let a=null;if(t.Events.isProfileCall(e))a=function(e,n){const r=n.Renderer.entryToNode.size>0?n.Renderer.entryToNode:n.Samples.entryToNode,i={callFrames:[]};let a=i,s=e,o=r.get(e);const l=w.get(n)||new Map;w.set(n,l);for(;o;){if(!t.Events.isProfileCall(o.entry)){o=o.parent;continue}s=o.entry;const e=l.get(o.entry);if(e){a.callFrames.push(...e.callFrames.filter((e=>!N(e)))),a.parent=e.parent,a.description=a.description||e.description;break}N(s.callFrame)||a.callFrames.push(s.callFrame);const i=n.AsyncJSCalls.asyncCallToScheduler.get(s),c=i&&r.get(i.scheduler);c?(a.parent={callFrames:[]},a=a.parent,a.description=i.taskName,o=c):o=o.parent}return i}(e,n);else if(t.Extensions.isSyntheticExtensionEntry(e))a=function(e,t){return F(e.rawSourceEvent,t)}(e,n);else if(t.Events.isUserTiming(e))a=F(e,n);else if(t.Events.isLayout(e)||t.Events.isUpdateLayoutTree(e)){const t=n.Renderer.entryToNode.get(e),r=t?.parent?.entry;r&&(a=b(r,n))}return a&&r.set(e,a),a}function P(e){const t=e.args?.data;return t&&t.rnStackTrace?t.rnStackTrace:null}function F(e,n){let r=e;if(t.Events.isPerformanceMeasureBegin(e)){if(void 0===e.args.traceId)return null;r=n.UserTimings.measureTraceByTraceId.get(e.args.traceId)}if(!r)return null;let i=n.Renderer.entryToNode.get(r);for(;i&&!t.Events.isProfileCall(i.entry);)i=i.parent;return i&&t.Events.isProfileCall(i.entry)?b(i.entry,n):null}function N({columnNumber:e,lineNumber:t,url:n,scriptId:r}){return-1===t&&-1===e&&""===n&&"0"===r}var R=Object.freeze({__proto__:null,clearCacheForTrace:function(e){w.delete(e)},extractStackTraceForReactNative:P,get:b,getForReactNative:function(e,n){let r=w.get(n);r||(r=new Map,w.set(n,r));const i=r.get(e);if(i)return i;let a=null;return t.Events.isUserTiming(e)&&t.Events.isPerformanceMeasureBegin(e)?a=P(e):t.Extensions.isSyntheticExtensionEntry(e)?a=P(e.rawSourceEvent):t.Events.isConsoleTimeStamp(e)&&(a=P(e)),a&&r.set(e,a),a},stackTraceForEventInTrace:w});let D=class{};class _ extends D{visibleTypes;constructor(e){super(),this.visibleTypes=new Set(e)}accept(e){return!!t.Extensions.isSyntheticExtensionEntry(e)||this.visibleTypes.has(_.eventType(e))}static eventType(e){return e.cat.includes("blink.console")?"ConsoleTime":e.cat.includes("blink.user_timing")?"UserTiming":e.name}}class z extends D{#e;constructor(e){super(),this.#e=new Set(e)}accept(e){return!this.#e.has(e.name)}}var x=Object.freeze({__proto__:null,ExclusiveNameFilter:z,InvisibleEventsFilter:class extends D{#t;constructor(e){super(),this.#t=new Set(e)}accept(e){return!this.#t.has(_.eventType(e))}},TraceFilter:D,VisibleEventsFilter:_});function G(e,n){const r=e.ts,i=n.ts;if(r<i)return-1;if(r>i)return 1;const a=r+(e.dur??0),s=i+(n.dur??0);return a>s?-1:a<s?1:t.Events.isProfileCall(e)&&!t.Events.isProfileCall(n)?-1:t.Events.isProfileCall(n)&&!t.Events.isProfileCall(e)?1:0}function J(e,n,r,i,a,s){return{cat:"",name:"ProfileCall",nodeId:e.id,args:{},ph:"X",pid:a,tid:s,ts:i,dur:t.Timing.Micro(0),callFrame:e.callFrame,sampleIndex:r,profileId:n}}new Map;function L(e){if(!e.args)return null;if("beginData"in e.args){return e.args.beginData.sampleTraceId??null}return e.args?.sampleTraceId??e.args?.data?.sampleTraceId??null}new Set(["AbortPostTaskCallback","Animation","AsyncTask","v8.deserializeOnBackground","BeginFrame","BeginMainThreadFrame","v8.produceModuleCache","v8.produceCache","CancelAnimationFrame","CancelIdleCallback","v8.compile","V8.CompileCode","V8.CompileModule","Commit","CompositeLayers","ComputeIntersections","ConsoleTime","TimeStamp","CppGC.IncrementalSweep","DoDecrypt","DoDecryptReply","DoDigest","DoDigestReply","DoEncrypt","DoEncryptReply","DoSign","DoSignReply","DoVerify","DoVerifyReply","Decode Image","DrawFrame","EmbedderCallback","v8.evaluateModule","EvaluateScript","EventDispatch","EventTiming","V8.FinalizeDeserialization","FireAnimationFrame","FireIdleCallback","FrameStartedLoading","FunctionCall","GCEvent","BlinkGC.AtomicPhase","GPUTask","HandlePostMessage","HitTest","InvalidateLayout","JSSample","Layerize","Layout","LayoutShift","MajorGC","MarkDOMContent","firstPaint","firstContentfulPaint","largestContentfulPaint::Candidate","MarkLoad","MinorGC","V8.OptimizeCode","Paint","PaintImage","PaintSetup","ParseAuthorStyleSheet","ParseHTML","PrePaint","ProfileCall","Program","RasterTask","RequestAnimationFrame","RequestIdleCallback","RequestMainThreadFrame","ResourceFinish","ResourceReceivedData","ResourceReceiveResponse","ResourceSendRequest","ResourceWillSendRequest","RunMicrotasks","RunPostTaskCallback","RunTask","SchedulePostMessage","SchedulePostTaskCallback","ScheduleStyleRecalculation","ScrollLayer","CpuProfiler::StartProfiling","v8.parseOnBackground","v8.parseOnBackgroundParsing","v8.parseOnBackgroundWaiting","SyntheticLayoutShift","SyntheticLayoutShiftCluster","TimerFire","TimerInstall","TimerRemove","UpdateLayer","UpdateLayerTree","UpdateLayoutTree","UserTiming","V8Console::runTask","v8.wasm.cachedModule","v8.wasm.compiledModule","v8.wasm.moduleCacheHit","v8.wasm.moduleCacheInvalid","v8.wasm.streamFromResponseCallback","WebSocketCreate","WebSocketDestroy","WebSocketReceive","WebSocketReceiveHandshakeResponse","WebSocketSend","WebSocketSendHandshakeRequest","XHRLoad","XHRReadyStateChange"]);const B=e=>t.Timing.Micro(1e3*e);class A{#n=[];#r=[];#i;#a;#s=[];#o=!1;#l;#c=new Map;#d;#u;jsSampleEvents=[];constructor(e,n,r,i,a){this.#l=e,this.#a=i,this.#i=r,this.#d=a||t.Configuration.defaults(),this.#u=n}buildProfileCalls(e){const n=function(e,t){const n=[];let r=0,i=0;for(;r<e.length&&i<t.length;){const a=e[r],s=t[i],o=G(a,s);o<=0&&(n.push(a),r++),1===o&&(n.push(s),i++)}for(;r<e.length;)n.push(e[r++]);for(;i<t.length;)n.push(t[i++]);return n}(e,this.callsFromProfileSamples()),r=[];for(let e=0;e<n.length;e++){const i=n[e];if("I"===i.ph&&!L(i))continue;if(0===r.length){if(t.Events.isProfileCall(i)){this.#h(i);continue}r.push(i),this.#p(i);continue}const a=r.at(-1);if(void 0===a)continue;i.ts>=a.ts+(a.dur||0)?(this.#m(a),r.pop(),e--):t.Events.isProfileCall(i)?this.#h(i,a):(this.#p(i),r.push(i))}for(;r.length;){const e=r.pop();e&&this.#m(e)}return this.jsSampleEvents.sort(G),this.#n}#p(e){"RunMicrotasks"!==e.name&&"RunTask"!==e.name||(this.#s=[],this.#f(0,e.ts),this.#o=!1),this.#o&&(this.#f(this.#s.pop()||0,e.ts),this.#o=!1),this.#g(e),this.#s.push(this.#r.length)}#h(e,n){if(n&&t.Events.isJSInvocationEvent(n)||this.#o)this.#g(e);else if(t.Events.isProfileCall(e)&&0===this.#r.length){this.#o=!0;const t=this.#r.length;this.#g(e),this.#s.push(t)}}#m(e){const n=t.Timing.Micro(e.ts+(e.dur??0));this.#f(this.#s.pop()||0,n)}callsFromProfileSamples(){const e=this.#l.samples,n=this.#l.timestamps;if(!e)return[];const r=[];let i;for(let a=0;a<e.length;a++){const e=this.#l.nodeByIndex(a),s=B(t.Timing.Milli(n[a]));if(!e)continue;const o=J(e,this.#u,a,s,this.#i,this.#a);if(r.push(o),this.#d.debugMode){const e=this.#l.traceIds?.[a];this.jsSampleEvents.push(this.#v(o,s,e))}e.id===this.#l.gcNode?.id&&i?this.#c.set(o,i):i=e}return r}#T(e,t){let n=this.#l.nodeById(e.nodeId);const r=n?.id===this.#l.gcNode?.id;if(r&&(n=this.#c.get(e)||null),!n)return[];const i=new Array(n.depth+1+Number(r));let a=i.length-1;for(r&&(i[a--]=e);n;)i[a--]=J(n,e.profileId,e.sampleIndex,t??e.ts,this.#i,this.#a),n=n.parent;return i}#S(e,t){const n=this.#l.traceIds?.[e],r=n&&this.#l.nodeById(n),i=r&&J(r,this.#u,-1,t,this.#i,this.#a);return i?(this.#d.debugMode&&this.jsSampleEvents.push(this.#v(i,t,e)),this.#T(i)):null}#g(e){let n=this.#r;t.Events.isProfileCall(e)&&(n=this.#T(e));const r=L(e),i=r&&this.#S(r,e.ts);i&&(n=i),A.filterStackFrames(n,this.#d);const a=e.ts+(e.dur||0),s=Math.min(n.length,this.#r.length);let o;for(o=this.#s.at(-1)||0;o<s;++o){const e=n[o].callFrame,r=this.#r[o].callFrame;if(!A.framesAreEqual(e,r))break;this.#r[o].dur=t.Timing.Micro(Math.max(this.#r[o].dur||0,a-this.#r[o].ts))}for(this.#f(o,e.ts);o<n.length;++o){const e=n[o];e.nodeId!==this.#l.programNode?.id&&e.nodeId!==this.#l.root?.id&&e.nodeId!==this.#l.idleNode?.id&&e.nodeId!==this.#l.gcNode?.id&&(this.#r.push(e),this.#n.push(e))}}#f(e,n){if(this.#s.length){const t=this.#s.at(-1);t&&e<t&&(console.error(`Child stack is shallower (${e}) than the parent stack (${t}) at ${n}`),e=t)}this.#r.length<e&&(console.error(`Trying to truncate higher than the current stack size at ${n}`),e=this.#r.length);for(let e=0;e<this.#r.length;++e)this.#r[e].dur=t.Timing.Micro(Math.max(n-this.#r[e].ts,0));this.#r.length=e}#v(e,n,r){return{name:"JSSample",cat:"devtools.timeline",args:{data:{traceId:r,stackTrace:this.#T(e).map((e=>e.callFrame))}},ph:"I",ts:n,dur:t.Timing.Micro(0),pid:this.#i,tid:this.#a}}static framesAreEqual(e,t){return e.scriptId===t.scriptId&&e.functionName===t.functionName&&e.lineNumber===t.lineNumber}static showNativeName(e,t){return t&&Boolean(A.nativeGroup(e))}static nativeGroup(e){return e.startsWith("Parse")?"Parse":e.startsWith("Compile")||e.startsWith("Recompile")?"Compile":null}static isNativeRuntimeFrame(e){return"native V8Runtime"===e.url}static filterStackFrames(e,t){if(t.showAllEvents)return;let n=null,r=0;for(let i=0;i<e.length;++i){const a=e[i].callFrame,s=A.isNativeRuntimeFrame(a);if(s&&!A.showNativeName(a.functionName,t.includeRuntimeCallStats))continue;const o=s?A.nativeGroup(a.functionName):null;n&&n===o||(n=o,e[r++]=e[i])}e.length=r}static createFakeTraceFromCpuProfile(e,n){const r=[],i=`Thread ${n}`;return a("TracingStartedInPage",{data:{sessionId:"1"}},0,0,"M"),a("thread_name",{name:i},0,0,"M","__metadata"),e?(a("JSRoot",{},e.startTime,e.endTime-e.startTime,"X","toplevel"),a("CpuProfile",{data:{cpuProfile:e}},e.endTime,0,"X"),{traceEvents:r,metadata:{dataOrigin:"CPUProfile"}}):{traceEvents:r,metadata:{}};function a(e,i,a,s,o,l){const c={cat:l||"disabled-by-default-devtools.timeline",name:e,ph:o||"X",pid:t.Events.ProcessID(1),tid:n,ts:t.Timing.Micro(a),args:i};return s&&(c.dur=t.Timing.Micro(s)),r.push(c),c}}}class O{totalTime;selfTime;transferSize;id;event;events;parent;groupId;isGroupNodeInternal;depth;constructor(e,t){this.totalTime=0,this.selfTime=0,this.transferSize=0,this.id=e,this.event=t,this.events=[t],this.groupId="",this.isGroupNodeInternal=!1,this.depth=0}isGroupNode(){return this.isGroupNodeInternal}hasChildren(){throw new Error("Not implemented")}setHasChildren(e){throw new Error("Not implemented")}children(){throw new Error("Not implemented")}searchTree(e,t){t=t||[],this.event&&e(this.event)&&t.push(this);for(const n of this.children().values())n.searchTree(e,t);return t}}class U extends O{root;hasChildrenInternal;childrenInternal;parent;constructor(e,t,n){super(e,t),this.root=n?.root??null,this.hasChildrenInternal=!1,this.childrenInternal=null,this.parent=n}hasChildren(){return this.hasChildrenInternal}setHasChildren(e){this.hasChildrenInternal=e}children(){return this.childrenInternal||this.buildChildren()}buildChildren(){const e=[];for(let t=this;t.parent&&!t.isGroupNode();t=t.parent)e.push(t);e.reverse();const n=new Map,i=this,a=this.root;if(!a)return this.childrenInternal=n,this.childrenInternal;const s=a.startTime,o=a.endTime,l=a.doNotAggregate||a.includeInstantEvents?function(t){++u,h===e.length&&u<=e.length+2&&m(t,0);--u}:void 0,c=a.doNotAggregate?void 0:H,d=a.getEventGroupIdCallback();let u=0,h=0,p=null;function m(r,a){if(u===e.length+2){if(!p)return;return p.setHasChildren(!0),void(p.selfTime-=a)}let s,o="";c?(s=c(r),o=d?d(r):"",o&&(s+="/"+o)):s=Symbol("uniqueId");let l=n.get(s);l?l.events.push(r):(l=new U(s,r,i),l.groupId=o,n.set(s,l)),l.selfTime+=a,l.totalTime+=a,t.Events.isReceivedDataEvent(r)&&(l.transferSize+=r.args.data.encodedDataLength),p=l}return r.Trace.forEachEvent(a.events,{onStartEvent:function(t){const{startTime:n,endTime:i}=r.Timing.eventTimingsMilliSeconds(t);if(++u,u>e.length+2)return;if(!function(t){const{endTime:n}=r.Timing.eventTimingsMilliSeconds(t);if(h===e.length)return!0;if(h!==u-1)return!1;if(!n)return!1;if(!c)return t===e[h].event&&++h,!1;let i=c(t);const a=d?d(t):"";a&&(i+="/"+a);i===e[h].id&&++h;return!1}(t))return;const a=(void 0!==i?Math.min(i,o):o)-Math.max(s,n);a<0&&console.error("Negative event duration");m(t,a)},onEndEvent:function(){--u,h>u&&(h=u)},onInstantEvent:l,startTime:r.Timing.milliToMicro(s),endTime:r.Timing.milliToMicro(o),eventFilter:a.filter,ignoreAsyncEvents:!1}),this.childrenInternal=n,n}getRoot(){return this.root}}class j extends O{childrenInternal;textFilter;filter;startTime;endTime;totalTime;eventGroupIdCallback;calculateTransferSize;forceGroupIdCallback;constructor(e,{textFilter:t,filters:n,startTime:r,endTime:i,eventGroupIdCallback:a,calculateTransferSize:s,forceGroupIdCallback:o}){super("",e[0]),this.childrenInternal=null,this.events=e,this.textFilter=t,this.filter=e=>n.every((t=>t.accept(e))),this.startTime=r,this.endTime=i,this.eventGroupIdCallback=a,this.totalTime=i-r,this.calculateTransferSize=s,this.forceGroupIdCallback=o}hasChildren(){return!0}filterChildren(e){for(const[t,n]of e)n.event&&n.depth<=1&&!this.textFilter.accept(n.event)&&e.delete(t);return e}children(){return this.childrenInternal||(this.childrenInternal=this.filterChildren(this.grouppedTopNodes())),this.childrenInternal}ungrouppedTopNodes(){const e=this,n=this.startTime,i=this.endTime,a=new Map,s=[i-n],o=[],l=new Map,c=this.eventGroupIdCallback,d=this.forceGroupIdCallback;r.Trace.forEachEvent(this.events,{onStartEvent:function(e){const{startTime:t,endTime:a}=r.Timing.eventTimingsMilliSeconds(e),u=(void 0!==a?Math.min(a,i):i)-Math.max(t,n);s[s.length-1]-=u,s.push(u);let h=H(e);d&&c&&(h=`${h}-${c(e)}`);const p=!l.has(h);p&&l.set(h,u);o.push(p)},onEndEvent:function(t){let n=H(t);d&&c&&(n=`${n}-${c(t)}`);let r=a.get(n);r?r.events.push(t):(r=new $(e,n,t,!1,e),a.set(n,r));r.selfTime+=s.pop()||0,o.pop()&&(r.totalTime+=l.get(n)||0,l.delete(n));o.length&&r.setHasChildren(!0)},onInstantEvent:this.calculateTransferSize?n=>{if(t.Events.isReceivedDataEvent(n)){let t=H(n);this.forceGroupIdCallback&&this.eventGroupIdCallback&&(t=`${t}-${this.eventGroupIdCallback(n)}`);let r=a.get(t);r?r.events.push(n):(r=new $(e,t,n,!1,e),a.set(t,r)),"ResourceReceivedData"===n.name?r.transferSize+=n.args.data.encodedDataLength:n.args.data.encodedDataLength>0&&(r.transferSize=n.args.data.encodedDataLength)}}:void 0,startTime:r.Timing.milliToMicro(this.startTime),endTime:r.Timing.milliToMicro(this.endTime),eventFilter:this.filter,ignoreAsyncEvents:!1}),this.selfTime=s.pop()||0;for(const e of a)e[1].selfTime<=0&&(!this.calculateTransferSize||e[1].transferSize<=0)&&a.delete(e[0]);return a}grouppedTopNodes(){const e=this.ungrouppedTopNodes();if(!this.eventGroupIdCallback)return e;const t=new Map;for(const n of e.values()){const e=this.eventGroupIdCallback(n.event);let r=t.get(e);r?r.events.push(...n.events):(r=new W(e,this,n.events),t.set(e,r)),r.addChild(n,n.selfTime,n.selfTime,n.transferSize)}return t}}class W extends O{childrenInternal;isGroupNodeInternal;events;constructor(e,t,n){super(e,n[0]),this.events=n,this.childrenInternal=new Map,this.parent=t,this.isGroupNodeInternal=!0}addChild(e,t,n,r){this.childrenInternal.set(e.id,e),this.selfTime+=t,this.totalTime+=n,this.transferSize+=r,e.parent=this}hasChildren(){return!0}children(){return this.childrenInternal}}class $ extends O{parent;root;depth;cachedChildren;hasChildrenInternal;constructor(e,t,n,r,i){super(t,n),this.parent=i,this.root=e,this.depth=(i.depth||0)+1,this.cachedChildren=null,this.hasChildrenInternal=r}hasChildren(){return this.hasChildrenInternal}setHasChildren(e){this.hasChildrenInternal=e}children(){if(this.cachedChildren)return this.cachedChildren;const e=[0],t=[],n=[],i=new Map,a=this.root.startTime,s=this.root.endTime;let o=a;const l=this;return r.Trace.forEachEvent(this.root.events,{onStartEvent:function(i){const{startTime:o,endTime:l}=r.Timing.eventTimingsMilliSeconds(i),c=(void 0!==l?Math.min(l,s):s)-Math.max(o,a);c<0&&console.assert(!1,"Negative duration of an event");e[e.length-1]-=c,e.push(c);const d=H(i);t.push(d),n.push(i)},onEndEvent:function(a){const{startTime:c,endTime:d}=r.Timing.eventTimingsMilliSeconds(a),u=e.pop(),h=t.pop();let p;for(n.pop(),p=l;p.depth>1;p=p.parent)if(p.id!==t[t.length+1-p.depth])return;if(p.id!==h||t.length<l.depth)return;const m=t[t.length-l.depth];if(p=i.get(m),p)p.events.push(a);else{const e=n[n.length-l.depth],t=n.length>l.depth;p=new $(l.root,m,e,t,l),i.set(m,p)}const f=void 0!==d?Math.min(d,s):s,g=f-Math.max(c,o);p.selfTime+=u||0,p.totalTime+=g,o=f},startTime:r.Timing.milliToMicro(a),endTime:r.Timing.milliToMicro(s),eventFilter:this.root.filter,ignoreAsyncEvents:!1}),this.cachedChildren=this.root.filterChildren(i),this.cachedChildren}searchTree(e,t){return t=t||[],this.event&&e(this.event)&&t.push(this),t}}function H(e){if(t.Events.isProfileCall(e)){return`f:${A.isNativeRuntimeFrame(e.callFrame)?A.nativeGroup(e.callFrame.functionName):e.callFrame.functionName}@${e.callFrame.scriptId||e.callFrame.url||""}`}return t.Events.isConsoleTimeStamp(e)&&e.args.data?`${e.name}:${e.args.data.name}`:t.Events.isSyntheticNetworkRequest(e)||t.Events.isReceivedDataEvent(e)?`req:${e.args.data.requestId}`:e.name}var q=Object.freeze({__proto__:null,BottomUpNode:$,BottomUpRootNode:j,GroupNode:W,Node:O,TopDownNode:U,TopDownRootNode:class extends U{filter;startTime;endTime;eventGroupIdCallback;doNotAggregate;includeInstantEvents;totalTime;selfTime;constructor(e,{filters:t,startTime:n,endTime:r,doNotAggregate:i,eventGroupIdCallback:a,includeInstantEvents:s}){super("",e[0],null),this.event=e[0],this.root=this,this.events=e,this.filter=e=>t.every((t=>t.accept(e))),this.startTime=n,this.endTime=r,this.eventGroupIdCallback=a,this.doNotAggregate=i,this.includeInstantEvents=s,this.totalTime=r-n,this.selfTime=this.totalTime}children(){return this.childrenInternal||this.grouppedTopNodes()}grouppedTopNodes(){const e=super.children();for(const t of e.values())this.selfTime-=t.totalTime;if(!this.eventGroupIdCallback)return e;const t=new Map;for(const n of e.values()){const e=this.eventGroupIdCallback(n.event);let r=t.get(e);r?r.events.push(...n.events):(r=new W(e,this,n.events),t.set(e,r)),r.addChild(n,n.selfTime,n.totalTime,n.transferSize)}return this.childrenInternal=t,t}getEventGroupIdCallback(){return this.eventGroupIdCallback}},eventStackFrame:function(e){if(t.Events.isProfileCall(e))return e.callFrame;const n=e.args?.data?.stackTrace?.[0];return n?{...n,scriptId:String(n.scriptId)}:null},generateEventID:H});var V=Object.freeze({__proto__:null,summarizeThirdParties:function(e,n){const i=function(e,t,n){const i=t.Renderer.entityMappings,a=e=>{const t=i?.entityByEvent.get(e);return t?.name??""},s=r.Trace.VISIBLE_TRACE_EVENT_TYPES.values().toArray(),o=new _(s.concat(["SyntheticNetworkRequest"])),l=r.Timing.microToMilli(n.min),c=r.Timing.microToMilli(n.max),d=new j(e,{textFilter:new z([]),filters:[o],startTime:l,endTime:c,eventGroupIdCallback:a,calculateTransferSize:!0,forceGroupIdCallback:!0});return d}(function(e){const t=e.Renderer.processes.values().find((e=>{const t=e.url??"";return e.isOnMainFrame&&!t.startsWith("about:")&&!t.startsWith("chrome:")}))?.threads.values().find((e=>"CrRendererMain"===e.name));return t?t.entries:[]}(e).sort(r.Trace.eventTimeComparator),e,n);return function(e,n){const r=new Map,i=[],a=[...e.children().values()].flat();for(const e of a){if(""===e.id)continue;const a=n.Renderer.entityMappings.entityByEvent.get(e.event);if(!a)continue;const s={transferSize:e.transferSize,mainThreadTime:t.Timing.Milli(e.selfTime),relatedEvents:n.Renderer.entityMappings.eventsByEntity.get(a)??[],entity:a};r.set(a,s),i.push(s)}return i}(i,e)}});export{m as FetchNodes,g as FilmStrip,T as MainThreadActivity,S as Metadata,y as ScriptDuplication,R as StackTraceForEvent,V as ThirdParties,x as TraceFilter,q as TraceTree};