@react-native/debugger-frontend
Version:
Debugger frontend for React Native based on Chrome DevTools
2 lines (1 loc) • 31.9 kB
JavaScript
import*as e from"../../../core/root/root.js";import*as t from"../../../models/trace/trace.js";import*as n from"../../../core/common/common.js";import*as r from"../../../core/i18n/i18n.js";import*as i from"../../../ui/legacy/theme_support/theme_support.js";import*as a from"../../../core/sdk/sdk.js";import*as s from"../../../models/bindings/bindings.js";import*as o from"../../../models/source_map_scopes/source_map_scopes.js";import*as l from"../../../models/workspace/workspace.js";import"../../../ui/components/markdown_view/markdown_view.js";import*as c from"../../../core/platform/platform.js";import*as d from"../../../models/crux-manager/crux-manager.js";import*as p from"../../../third_party/marked/marked.js";import*as u from"../../../ui/lit/lit.js";import*as g from"../../mobile_throttling/mobile_throttling.js";const m={loading:"Loading",experience:"Experience",scripting:"Scripting",rendering:"Rendering",painting:"Painting",gpu:"GPU",async:"Async",system:"System",idle:"Idle",task:"Task",consoleTaskRun:"Run console task",other:"Other",animation:"Animation",event:"Event",requestMainThreadFrame:"Request main thread frame",frameStart:"Frame start",onMessage:"On message",schedulePostMessage:"Schedule postMessage",messaging:"Messaging",frameStartMainThread:"Frame start (main thread)",drawFrame:"Draw frame",profilingOverhead:"Profiling overhead",hitTest:"Hit test",scheduleStyleRecalculation:"Schedule style recalculation",recalculateStyle:"Recalculate style",invalidateLayout:"Invalidate Layout",layerize:"Layerize",layout:"Layout",paintSetup:"Paint setup",paintImage:"Paint image",prePaint:"Pre-paint",updateLayer:"Update layer",updateLayerTree:"Update layer tree",paint:"Paint",rasterizePaint:"Rasterize paint",scroll:"Scroll",commit:"Commit",compositeLayers:"Composite layers",computeIntersections:"Compute intersections",parseHtml:"Parse HTML",parseStylesheet:"Parse stylesheet",installTimer:"Install timer",removeTimer:"Remove timer",timerFired:"Timer fired",xhrReadyStateChange:"`XHR` `readyState` change",xhrLoad:"`XHR` load",compileScript:"Compile script",cacheScript:"Cache script code",compileCode:"Compile code",optimizeCode:"Optimize code",evaluateScript:"Evaluate script",compileModule:"Compile module",cacheModule:"Cache module code",evaluateModule:"Evaluate module",streamingCompileTask:"Streaming compile task",waitingForNetwork:"Waiting for network",parseAndCompile:"Parse and compile",deserializeCodeCache:"Deserialize code cache",streamingWasmResponse:"Streaming Wasm response",compiledWasmModule:"Compiled Wasm module",cachedWasmModule:"Cached Wasm module",wasmModuleCacheHit:"Wasm module cache hit",wasmModuleCacheInvalid:"Wasm module cache invalid",frameStartedLoading:"Frame started loading",onloadEvent:"Onload event",domcontentloadedEvent:"DOMContentLoaded event",firstPaint:"First Paint",firstContentfulPaint:"First Contentful Paint",largestContentfulPaint:"Largest Contentful Paint",timestamp:"Timestamp",consoleTime:"Console time",userTiming:"User timing",willSendRequest:"Will send request",sendRequest:"Send request",receiveResponse:"Receive response",finishLoading:"Finish loading",receiveData:"Receive data",runMicrotasks:"Run microtasks",functionCall:"Function call",gcEvent:"GC event",majorGc:"Major GC",minorGc:"Minor GC",requestAnimationFrame:"Request animation frame",cancelAnimationFrame:"Cancel animation frame",animationFrameFired:"Animation frame fired",requestIdleCallback:"Request idle callback",cancelIdleCallback:"Cancel idle callback",fireIdleCallback:"Fire idle callback",createWebsocket:"Create WebSocket",sendWebsocketHandshake:"Send WebSocket handshake",receiveWebsocketHandshake:"Receive WebSocket handshake",wsMessageReceived:"Receive WebSocket message",wsMessageSent:"Send WebSocket message",destroyWebsocket:"Destroy WebSocket",embedderCallback:"Embedder callback",imageDecode:"Image decode",domGc:"DOM GC",cppGc:"CPP GC",encrypt:"Encrypt",encryptReply:"Encrypt reply",decrypt:"Decrypt",decryptReply:"Decrypt reply",digest:"Digest",digestReply:"Digest reply",sign:"Sign",signReply:"Sign reply",verify:"Verify",verifyReply:"Verify reply",asyncTask:"Async task",layoutShift:"Layout shift",layoutShiftCluster:"Layout shift cluster",eventTiming:"Event timing",jsFrame:"JS frame",rasterizing:"Rasterizing",drawing:"Drawing",schedulePostTaskCallback:"Schedule postTask",runPostTaskCallback:"Fire postTask",abortPostTaskCallback:"Cancel postTask"};var h;let y;!function(e){e.DRAWING="drawing",e.RASTERIZING="rasterizing",e.LAYOUT="layout",e.LOADING="loading",e.EXPERIENCE="experience",e.SCRIPTING="scripting",e.MESSAGING="messaging",e.RENDERING="rendering",e.PAINTING="painting",e.GPU="gpu",e.ASYNC="async",e.OTHER="other",e.IDLE="idle"}(h||(h={}));const f=r.i18n.registerUIStrings("panels/timeline/utils/EntryStyles.ts",m),v=r.i18n.getLocalizedString.bind(void 0,f);class w{title;category;hidden;constructor(e,t,n=!1){this.title=e,this.category=t,this.hidden=n}}class T{name;title;visible;childColor;colorInternal;#e;constructor(e,t,n,r,i){this.name=e,this.title=t,this.visible=n,this.childColor=r,this.colorInternal=i,this.hidden=!1}get hidden(){return Boolean(this.#e)}get color(){return this.getComputedColorValue()}getCSSValue(){return`var(${this.colorInternal})`}getComputedColorValue(){return i.ThemeSupport.instance().getComputedValue(this.colorInternal)}set hidden(e){this.#e=e}}let C,S;function E(e){return k()[e]}function M(){return C||(C={loading:new T(h.LOADING,v(m.loading),!0,"--app-color-loading-children","--app-color-loading"),experience:new T(h.EXPERIENCE,v(m.experience),!1,"--app-color-rendering-children","--app-color-rendering"),messaging:new T(h.MESSAGING,v(m.messaging),!0,"--app-color-messaging-children","--app-color-messaging"),scripting:new T(h.SCRIPTING,v(m.scripting),!0,"--app-color-scripting-children","--app-color-scripting"),rendering:new T(h.RENDERING,v(m.rendering),!0,"--app-color-rendering-children","--app-color-rendering"),painting:new T(h.PAINTING,v(m.painting),!0,"--app-color-painting-children","--app-color-painting"),gpu:new T(h.GPU,v(m.gpu),!1,"--app-color-painting-children","--app-color-painting"),async:new T(h.ASYNC,v(m.async),!1,"--app-color-async-children","--app-color-async"),other:new T(h.OTHER,v(m.system),!1,"--app-color-system-children","--app-color-system"),idle:new T(h.IDLE,v(m.idle),!1,"--app-color-idle-children","--app-color-idle"),layout:new T(h.LAYOUT,v(m.layout),!1,"--app-color-loading-children","--app-color-loading"),rasterizing:new T(h.RASTERIZING,v(m.rasterizing),!1,"--app-color-children","--app-color-scripting"),drawing:new T(h.DRAWING,v(m.drawing),!1,"--app-color-rendering-children","--app-color-rendering")},C)}function k(){if(S)return S;const e=M();S={RunTask:new w(v(m.task),e.other),ProfileCall:new w(v(m.jsFrame),e.scripting),JSSample:new w("JSSample",e.scripting),Program:new w(v(m.other),e.other),"CpuProfiler::StartProfiling":new w(v(m.profilingOverhead),e.other),Animation:new w(v(m.animation),e.rendering),EventDispatch:new w(v(m.event),e.scripting),RequestMainThreadFrame:new w(v(m.requestMainThreadFrame),e.rendering,!0),BeginFrame:new w(v(m.frameStart),e.rendering,!0),BeginMainThreadFrame:new w(v(m.frameStartMainThread),e.rendering,!0),DrawFrame:new w(v(m.drawFrame),e.rendering,!0),HitTest:new w(v(m.hitTest),e.rendering),ScheduleStyleRecalculation:new w(v(m.scheduleStyleRecalculation),e.rendering),UpdateLayoutTree:new w(v(m.recalculateStyle),e.rendering),InvalidateLayout:new w(v(m.invalidateLayout),e.rendering,!0),Layerize:new w(v(m.layerize),e.rendering),Layout:new w(v(m.layout),e.rendering),PaintSetup:new w(v(m.paintSetup),e.painting),PaintImage:new w(v(m.paintImage),e.painting,!0),UpdateLayer:new w(v(m.updateLayer),e.painting,!0),UpdateLayerTree:new w(v(m.updateLayerTree),e.rendering),Paint:new w(v(m.paint),e.painting),PrePaint:new w(v(m.prePaint),e.rendering),RasterTask:new w(v(m.rasterizePaint),e.painting),ScrollLayer:new w(v(m.scroll),e.rendering),Commit:new w(v(m.commit),e.painting),CompositeLayers:new w(v(m.compositeLayers),e.painting),ComputeIntersections:new w(v(m.computeIntersections),e.rendering),ParseHTML:new w(v(m.parseHtml),e.loading),ParseAuthorStyleSheet:new w(v(m.parseStylesheet),e.loading),TimerInstall:new w(v(m.installTimer),e.scripting),TimerRemove:new w(v(m.removeTimer),e.scripting),TimerFire:new w(v(m.timerFired),e.scripting),XHRReadyStateChange:new w(v(m.xhrReadyStateChange),e.scripting),XHRLoad:new w(v(m.xhrLoad),e.scripting),"v8.compile":new w(v(m.compileScript),e.scripting),"v8.produceCache":new w(v(m.cacheScript),e.scripting),"V8.CompileCode":new w(v(m.compileCode),e.scripting),"V8.OptimizeCode":new w(v(m.optimizeCode),e.scripting),EvaluateScript:new w(v(m.evaluateScript),e.scripting),"V8.CompileModule":new w(v(m.compileModule),e.scripting),"v8.produceModuleCache":new w(v(m.cacheModule),e.scripting),"v8.evaluateModule":new w(v(m.evaluateModule),e.scripting),"v8.parseOnBackground":new w(v(m.streamingCompileTask),e.other),"v8.parseOnBackgroundWaiting":new w(v(m.waitingForNetwork),e.idle),"v8.parseOnBackgroundParsing":new w(v(m.parseAndCompile),e.scripting),"v8.deserializeOnBackground":new w(v(m.deserializeCodeCache),e.scripting),"V8.FinalizeDeserialization":new w(v(m.profilingOverhead),e.other),"v8.wasm.streamFromResponseCallback":new w(v(m.streamingWasmResponse),e.scripting),"v8.wasm.compiledModule":new w(v(m.compiledWasmModule),e.scripting),"v8.wasm.cachedModule":new w(v(m.cachedWasmModule),e.scripting),"v8.wasm.moduleCacheHit":new w(v(m.wasmModuleCacheHit),e.scripting),"v8.wasm.moduleCacheInvalid":new w(v(m.wasmModuleCacheInvalid),e.scripting),FrameStartedLoading:new w(v(m.frameStartedLoading),e.loading,!0),MarkLoad:new w(v(m.onloadEvent),e.scripting,!0),MarkDOMContent:new w(v(m.domcontentloadedEvent),e.scripting,!0),firstPaint:new w(v(m.firstPaint),e.painting,!0),firstContentfulPaint:new w(v(m.firstContentfulPaint),e.rendering,!0),"largestContentfulPaint::Candidate":new w(v(m.largestContentfulPaint),e.rendering,!0),TimeStamp:new w(v(m.timestamp),e.scripting),ConsoleTime:new w(v(m.consoleTime),e.scripting),UserTiming:new w(v(m.userTiming),e.scripting),ResourceWillSendRequest:new w(v(m.willSendRequest),e.loading),ResourceSendRequest:new w(v(m.sendRequest),e.loading),ResourceReceiveResponse:new w(v(m.receiveResponse),e.loading),ResourceFinish:new w(v(m.finishLoading),e.loading),ResourceReceivedData:new w(v(m.receiveData),e.loading),RunMicrotasks:new w(v(m.runMicrotasks),e.scripting),FunctionCall:new w(v(m.functionCall),e.scripting),GCEvent:new w(v(m.gcEvent),e.scripting),MajorGC:new w(v(m.majorGc),e.scripting),MinorGC:new w(v(m.minorGc),e.scripting),"CppGC.IncrementalSweep":new w(v(m.cppGc),e.scripting),RequestAnimationFrame:new w(v(m.requestAnimationFrame),e.scripting),CancelAnimationFrame:new w(v(m.cancelAnimationFrame),e.scripting),FireAnimationFrame:new w(v(m.animationFrameFired),e.scripting),RequestIdleCallback:new w(v(m.requestIdleCallback),e.scripting),CancelIdleCallback:new w(v(m.cancelIdleCallback),e.scripting),FireIdleCallback:new w(v(m.fireIdleCallback),e.scripting),WebSocketCreate:new w(v(m.createWebsocket),e.scripting),WebSocketSendHandshakeRequest:new w(v(m.sendWebsocketHandshake),e.scripting),WebSocketReceiveHandshakeResponse:new w(v(m.receiveWebsocketHandshake),e.scripting),WebSocketDestroy:new w(v(m.destroyWebsocket),e.scripting),WebSocketSend:new w(v(m.wsMessageSent),e.scripting),WebSocketReceive:new w(v(m.wsMessageReceived),e.scripting),EmbedderCallback:new w(v(m.embedderCallback),e.scripting),"Decode Image":new w(v(m.imageDecode),e.painting),GPUTask:new w(v(m.gpu),e.gpu),"BlinkGC.AtomicPhase":new w(v(m.domGc),e.scripting),DoEncrypt:new w(v(m.encrypt),e.scripting),DoEncryptReply:new w(v(m.encryptReply),e.scripting),DoDecrypt:new w(v(m.decrypt),e.scripting),DoDecryptReply:new w(v(m.decryptReply),e.scripting),DoDigest:new w(v(m.digest),e.scripting),DoDigestReply:new w(v(m.digestReply),e.scripting),DoSign:new w(v(m.sign),e.scripting),DoSignReply:new w(v(m.signReply),e.scripting),DoVerify:new w(v(m.verify),e.scripting),DoVerifyReply:new w(v(m.verifyReply),e.scripting),AsyncTask:new w(v(m.asyncTask),e.async),LayoutShift:new w(v(m.layoutShift),e.experience,!0),SyntheticLayoutShift:new w(v(m.layoutShift),e.experience),SyntheticLayoutShiftCluster:new w(v(m.layoutShiftCluster),e.experience),EventTiming:new w(v(m.eventTiming),e.experience),HandlePostMessage:new w(v(m.onMessage),e.messaging),SchedulePostMessage:new w(v(m.schedulePostMessage),e.messaging),SchedulePostTaskCallback:new w(v(m.schedulePostTaskCallback),e.scripting),RunPostTaskCallback:new w(v(m.runPostTaskCallback),e.scripting),AbortPostTaskCallback:new w(v(m.abortPostTaskCallback),e.scripting),"V8Console::runTask":new w(v(m.consoleTaskRun),e.scripting)};const n=Object.keys(S).every((e=>t.Helpers.Trace.VISIBLE_TRACE_EVENT_TYPES.has(e))),r=Object.keys(S),i=Array.from(t.Helpers.Trace.VISIBLE_TRACE_EVENT_TYPES).every((e=>r.includes(e)));if(!n||!i)throw new Error("eventStylesMap and VISIBLE_TRACE_EVENT_TYPES are out of sync!");return S}function R(){const e=k(),t=[];for(const n in e){const r=n;e[r]?.hidden||t.push(n)}return t}var I=Object.freeze({__proto__:null,get EventCategory(){return h},TimelineCategory:T,TimelineRecordStyle:w,getCategoryStyles:M,getEventStyle:E,getTimelineMainEventCategories:function(){return y||(y=[h.IDLE,h.LOADING,h.PAINTING,h.RENDERING,h.SCRIPTING,h.OTHER],y)},markerDetailsForEvent:function(e){let n="",r="var(--color-text-primary)";return t.Types.Events.isFirstContentfulPaint(e)&&(r="var(--sys-color-green-bright)",n="FCP"),t.Types.Events.isLargestContentfulPaintCandidate(e)&&(r="var(--sys-color-green)",n="LCP"),t.Types.Events.isNavigationStart(e)&&(r="var(--color-text-primary)",n="Nav"),t.Types.Events.isMarkDOMContent(e)&&(r="var(--color-text-disabled)",n="DCL"),t.Types.Events.isMarkLoad(e)&&(r="var(--color-text-disabled)",n="L"),{color:r,title:n}},maybeInitSylesMap:k,setCategories:function(e){C=e},setEventStylesMap:function(e){S=e},setTimelineMainEventCategories:function(e){y=e},stringIsEventCategory:function(e){return Object.values(h).includes(e)},visibleTypes:R});const b={anonymous:"(anonymous)",eventDispatchS:"Event: {PH1}",frame:"Frame",wsConnectionOpened:"WebSocket opened",wsConnectionOpenedWithUrl:"WebSocket opened: {PH1}",wsConnectionClosed:"WebSocket closed",layoutShift:"Layout shift"},P=r.i18n.registerUIStrings("panels/timeline/utils/EntryName.ts",b),F=r.i18n.getLocalizedString.bind(void 0,P);function L(e,i){if(t.Types.Events.isProfileCall(e)){if(i){const n=t.Handlers.ModelHandlers.Samples.getProfileCallFunctionName(i.Samples,e);if(n)return n}return e.callFrame.functionName||F(b.anonymous)}if(t.Types.Events.isLegacyTimelineFrame(e))return r.i18n.lockedString(b.frame);if(t.Types.Events.isDispatch(e))return F(b.eventDispatchS,{PH1:e.args.data.type});if(t.Types.Events.isSyntheticNetworkRequest(e)){const t=new n.ParsedURL.ParsedURL(e.args.data.url);return t.isValid?`${t.displayName} (${t.host})`:e.args.data.url||"Network request"}if(t.Types.Events.isWebSocketCreate(e))return e.args.data.url?F(b.wsConnectionOpenedWithUrl,{PH1:e.args.data.url}):F(b.wsConnectionOpened);if(t.Types.Events.isWebSocketDestroy(e))return F(b.wsConnectionClosed);if(t.Types.Events.isSyntheticInteraction(e))return function(e){const n=t.Handlers.ModelHandlers.UserInteractions.categoryOfInteraction(e);if("OTHER"===n)return"Other";if("KEYBOARD"===n)return"Keyboard";if("POINTER"===n)return"Pointer";return e.type}(e);if(t.Types.Events.isSyntheticLayoutShift(e))return F(b.layoutShift);if(t.Types.Events.isSyntheticAnimation(e)&&e.args.data.beginEvent.args.data.displayName)return e.args.data.beginEvent.args.data.displayName;const a=E(e.name)?.title;return a||e.name}var N=Object.freeze({__proto__:null,nameForEntry:L});class D extends Event{static eventName="sourcemappingsupdated";constructor(){super(D.eventName,{composed:!0,bubbles:!0})}}const A=new Map;class O extends EventTarget{executionContextNamesByOrigin=new Map;#t;#n=null;#r=!1;#i=new Set;constructor(e,t){super(),this.#t=e,this.#n=t??null}static clearResolvedNodeNames(){A.clear()}static keyForCodeLocation(e){return`${e.url}$$$${e.scriptId}$$$${e.functionName}$$$${e.lineNumber}$$$${e.columnNumber}`}static resolvedCodeLocationForCallFrame(e){const t=this.keyForCodeLocation(e);return A.get(t)??null}static resolvedCodeLocationForEntry(e){let n=null;if(t.Types.Events.isProfileCall(e))n=e.callFrame;else{const r=t.Helpers.Trace.getZeroIndexedStackTraceForEvent(e);if(null===r||r.length<1)return null;n=r[0]}return O.resolvedCodeLocationForCallFrame(n)}static resolvedURLForEntry(e,n){const r=O.resolvedCodeLocationForEntry(n)?.devtoolsLocation?.uiSourceCode.url();if(r)return r;const i=t.Handlers.Helpers.getNonResolvedURL(n,e);return i?l.Workspace.WorkspaceImpl.instance().uiSourceCodeForURL(i)?.url()??i:null}static storeResolvedCodeDataForCallFrame(e,t){const n=this.keyForCodeLocation(e);A.set(n,t)}async install(){for(const e of this.#t.Samples.profilesInProcess.values())for(const[t,n]of e){const e=n.parsedProfile.nodes();if(!e||0===e.length)continue;const r=this.#a(t),i=r?.model(a.DebuggerModel.DebuggerModel);if(i)for(const t of e){const e=i.scriptForId(String(t.callFrame.scriptId));(!e||e.sourceMapURL)&&this.#i.add(i)}}for(const e of this.#i)e.sourceMapManager().addEventListener(a.SourceMapManager.Events.SourceMapAttached,this.#s,this);this.#o(),await this.#l()}uninstall(){for(const e of this.#i)e.sourceMapManager().removeEventListener(a.SourceMapManager.Events.SourceMapAttached,this.#s,this);this.#i.clear()}async#l(){let e=!1;for(const[,t]of this.#t.Samples.profilesInProcess)for(const[n,r]of t){const t=r.parsedProfile.nodes()??[],i=this.#a(n);if(i)for(const n of t){const t=await o.NamesResolver.resolveProfileFrameFunctionName(n.callFrame,i);e||=Boolean(t),n.setFunctionName(t);const r=i.model(a.DebuggerModel.DebuggerModel),l=r?.scriptForId(n.scriptId)||null,c=r&&new a.DebuggerModel.Location(r,n.callFrame.scriptId,n.callFrame.lineNumber,n.callFrame.columnNumber),d=c&&await s.DebuggerWorkspaceBinding.DebuggerWorkspaceBinding.instance().rawLocationToUILocation(c);e||=Boolean(d),d?.uiSourceCode.url()&&this.#n&&this.#n.updateSourceMapEntities(n.callFrame,d.uiSourceCode.url()),O.storeResolvedCodeDataForCallFrame(n.callFrame,{name:t,devtoolsLocation:d,script:l})}}e&&this.dispatchEvent(new D)}#s(){this.#r||(this.#r=!0,setTimeout((async()=>{this.#r=!1,await this.#l()}),500))}#a(e){const t=this.#t.Workers.workerIdByThread.get(e);return t?a.TargetManager.TargetManager.instance().targetById(t):a.TargetManager.TargetManager.instance().primaryPageTarget()}#o(){for(const e of a.TargetManager.TargetManager.instance().models(a.RuntimeModel.RuntimeModel))for(const t of e.executionContexts())this.executionContextNamesByOrigin.set(t.origin,t.name);this.#n?.updateExtensionEntitiesWithName(this.executionContextNamesByOrigin)}}var _=Object.freeze({__proto__:null,SourceMappingsUpdated:D,SourceMapsResolver:O,resolvedCodeLocationDataNames:A});function H(e,t){for(const n of e){if(t?.(n))break;H(n.children().values(),t)}}class x{selectedNode;rootNode;parsedTrace;constructor(e,t,n){this.selectedNode=e,this.rootNode=t,this.parsedTrace=n}static fromTimeOnThread({thread:e,parsedTrace:n,bounds:r}){const i=n.Renderer.processes.get(e.pid)?.threads.get(e.tid)?.entries;if(!i)return null;const a=i.filter((e=>t.Helpers.Timing.eventIsInBounds(e,r))),s=new t.Extras.TraceFilter.VisibleEventsFilter(R()),o=t.Types.Timing.Micro(.005*r.range),l=new B(o),c=new W,d=new t.Extras.TraceTree.TopDownRootNode(a,{filters:[l,c,s],startTime:t.Helpers.Timing.microToMilli(r.min),endTime:t.Helpers.Timing.microToMilli(r.max),doNotAggregate:!0,includeInstantEvents:!0});return new x(null,d,n)}static fromEvent(n,r){const i=t.Handlers.Threads.threadsInTrace(r).find((e=>e.pid===n.pid&&e.tid===n.tid));if(!i)return null;if("MAIN_THREAD"!==i.type&&"CPU_PROFILE"!==i.type)return null;if(!r.Renderer.entryToNode.has(n)&&!r.Samples.entryToNode.has(n))return null;const a=e.Runtime.experiments.isEnabled("timeline-show-all-events"),{startTime:s,endTime:o}=t.Helpers.Timing.eventTimingsMilliSeconds(n),l=t.Helpers.Timing.traceWindowFromMicroSeconds(t.Helpers.Timing.milliToMicro(s),t.Helpers.Timing.milliToMicro(o));let c=r.Renderer.processes.get(n.pid)?.threads.get(n.tid)?.entries;if(c||(c=r.Samples.profilesInProcess.get(n.pid)?.get(n.tid)?.profileCalls),!c)return console.warn(`AICallTree: could not find thread for selected entry: ${n}`),null;const d=c.filter((e=>t.Helpers.Timing.eventIsInBounds(e,l))),p=[new U(n),new W(n)];a||p.push(new t.Extras.TraceFilter.VisibleEventsFilter(R()));const u=new t.Extras.TraceTree.TopDownRootNode(d,{filters:p,startTime:s,endTime:o,includeInstantEvents:!0});let g=null;if(H([u].values(),(e=>{if(e.event===n)return g=e,!0})),null===g)return console.warn(`Selected event ${n} not found within its own tree.`),null;return new x(g,u,r)}serialize(){const e=new Map,t=[];let n="";H(this.rootNode.children().values(),(r=>{n+=x.stringifyNode(r,this.parsedTrace,this.selectedNode,e,t)}));let r="";return t.length&&(r+="\n# All URL #s:\n\n"+t.map(((e,t)=>` * ${t}: ${e}`)).join("\n")),r+="\n\n# Call tree:"+n,r}static stringifyNode(e,t,n,r,i){const a=e.event;if(!a)throw new Error("Event required");const s=O.resolvedURLForEntry(t,a),o=s?-1===i.indexOf(s)?i.push(s)-1:i.indexOf(s):-1,l=Array.from(e.children().values()),c=e=>(r.has(e)||r.set(e,r.size+1),`${r.get(e)} – ${L(e.event,t)}`),d=e=>Math.round(10*e)/10,p=[`\n\nNode: ${c(e)}`,n===e&&"Selected: true",e.totalTime&&`dur: ${d(e.totalTime)}`,e.selfTime&&`self: ${d(e.selfTime)}`,-1!==o&&`URL #: ${o}`];return l.length&&(p.push("Children:"),p.push(...l.map((e=>` * ${c(e)}`)))),p.filter(Boolean).join("\n")}logDebug(){const e=this.serialize();console.log("🎆",e),e.length>45e3&&console.warn("Output will likely not fit in the context window. Expect an AIDA error.")}}class W extends t.Extras.TraceFilter.TraceFilter{#c=null;constructor(e){super(),this.#c=e??null}accept(e){return!(!this.#c||e!==this.#c)||"V8.CompileCode"!==e.name}}class U extends t.Extras.TraceFilter.TraceFilter{#d;#c;constructor(e){super(),this.#d=t.Types.Timing.Micro(.005*(e.dur??1)),this.#c=e}accept(e){return e===this.#c||!!e.dur&&e.dur>=this.#d}}class B extends t.Extras.TraceFilter.TraceFilter{#d;constructor(e){super(),this.#d=e}accept(e){return!!e.dur&&e.dur>=this.#d}}var $=Object.freeze({__proto__:null,AICallTree:x,ExcludeCompileCodeFilter:W,MinDurationFilter:B,SelectedEventDurationFilter:U});var z=Object.freeze({__proto__:null,EntityMapper:class{#p;#t;#u;#g;#m=[];#h=new Set;constructor(t){this.#t=t,this.#u=this.#t.Renderer.entityMappings,this.#p=e.Runtime.experiments.isEnabled("react-native-specific-ui"),this.#g=this.#y(),this.#m=this.#f()}#y(){if(this.#p)return null;const e=Array.from(this.#t.Meta.navigationsByNavigationId.values()).sort(((e,t)=>e.ts-t.ts))[0],n=e?.args.data?.documentLoaderURL??this.#t.Meta.mainFrameURL;return n?t.Handlers.Helpers.getEntityForUrl(n,this.#u.createdEntityCache)??null:null}#f(){return Array.from(this.#u.eventsByEntity.entries()).flatMap((([e,t])=>e!==this.#g?t:[]))}entityForEvent(e){return this.#p?null:this.#u.entityByEvent.get(e)??null}eventsForEntity(e){return this.#u.eventsByEntity.get(e)??[]}firstPartyEntity(){return this.#g}thirdPartyEvents(){return this.#m}mappings(){return this.#u}updateSourceMapEntities(e,n){if(this.#h.has(e))return;const r=e.url,i=t.Handlers.Helpers.getEntityForUrl(r,this.#u.createdEntityCache),a=t.Handlers.Helpers.getEntityForUrl(n,this.#u.createdEntityCache);if(a===i||!i||!a)return;const s=(i&&this.#u.eventsByEntity.get(i))??[],o=[],l=[];s?.forEach((n=>{const r=t.Helpers.Trace.getZeroIndexedStackTraceForEvent(n),i=r?.at(0);i&&t.Helpers.Trace.isMatchingCallFrame(i,e)?o.push(n):l.push(n)})),this.#u.eventsByEntity.set(i,l),this.#u.eventsByEntity.set(a,o),o.forEach((e=>{this.#u.entityByEvent.set(e,a)})),this.#h.add(e)}updateExtensionEntitiesWithName(e){const t=Array.from(this.#u.eventsByEntity.keys());for(const[n,r]of e){const e=t.find((e=>e.domains[0]===n));e&&(e.name=e.company=r)}}}});const{html:G}=u;function j(e){let t="";for(const[n,r]of e.searchParams)t&&(t+="&"),t+=r?`${n}=${c.StringUtilities.trimEndWithMaxLength(r,8)}`:n;return t&&(t="?"+t),t}var q=Object.freeze({__proto__:null,createUrlLabels:function(e){const t=[],n=e.every((e=>"https:"===e.protocol));for(const[r,i]of e.entries()){const a=e[r-1];let s=a&&i.host===a.host&&i.protocol===a.protocol,o=n;0===r&&n&&(s=!0,o=!0);const l=j(i);o?s?t.push(`${i.pathname}${l}`):t.push(`${i.host}${i.pathname}${l}`):t.push(`${i.protocol}//${i.host}${i.pathname}${l}`)}return t.map((e=>e.length>1&&e.endsWith("/")?e.substring(0,e.length-1):e))},formatOriginWithEntity:function(e,t,n){const r=e.origin.replace("https://","");if(!t)return r;let i;return i=t.isUnrecognized?`${r}`:n?`${r} (${t.name})`:`${r} - ${t.name}`,i=c.StringUtilities.trimEndWithMaxLength(i,60),i},getThrottlingRecommendations:function(){let e=a.CPUThrottlingManager.CalibratedMidTierMobileThrottlingOption;0===e.rate()&&(e=a.CPUThrottlingManager.MidTierThrottlingOption);let t=null;const n=d.CrUXManager.instance().getSelectedFieldMetricData("round_trip_time");if(n?.percentiles){const e=Number(n.percentiles.p75);t=g.ThrottlingPresets.ThrottlingPresets.getRecommendedNetworkPreset(e)}return{cpuOption:e,networkConditions:t}},md:function(e){const t=p.Marked.lexer(e);return G`<devtools-markdown-view .data=${{tokens:t}}></devtools-markdown-view>`},shortenUrl:function(e,t=20){const n="/"===e.pathname?[e.host]:e.pathname.split("/");let r=n.at(-1)??"";if(r.length>t)return c.StringUtilities.trimMiddle(r,t);let i=n.length-1;for(;--i>=0;)r.length+n[i].length<=t&&(r=`${n[i]}/${r}`);return r}});const V={skipContentScripts:"Content script",skip3rdPartyScripts:"Marked with ignoreList in source map",skipAnonymousScripts:"Anonymous script",unknown:"Unknown"},Y=r.i18n.registerUIStrings("panels/timeline/utils/IgnoreList.ts",V),X=r.i18n.getLocalizedString.bind(void 0,Y);function K(e){const t=e.callFrame.url,n=O.resolvedCodeLocationForEntry(e),r=n?.script,i=n?.devtoolsLocation?.uiSourceCode,a=i?.url(),s=i?.isKnownThirdParty(),o=r?.isContentScript();return{url:a||t,ignoreListOptions:{isContentScript:o,isKnownThirdParty:s}}}var J=Object.freeze({__proto__:null,getIgnoredReasonString:function(e){if(!t.Types.Events.isProfileCall(e))return console.warn("Ignore list feature should only support ProfileCall."),"";const{url:n,ignoreListOptions:r}=K(e),i=s.IgnoreListManager.IgnoreListManager.instance();if(r.isContentScript&&i.skipContentScripts)return X(V.skipContentScripts);if(r.isKnownThirdParty&&i.automaticallyIgnoreListKnownThirdPartyScripts)return X(V.skip3rdPartyScripts);if(!n)return i.skipAnonymousScripts?X(V.skipAnonymousScripts):"";const a=i.getFirstMatchedRegex(n);return a?a.source:X(V.unknown)},isIgnoreListedEntry:function(e){if(!t.Types.Events.isProfileCall(e))return!1;const{url:n,ignoreListOptions:r}=K(e);return function(e,t){return s.IgnoreListManager.IgnoreListManager.instance().isUserIgnoreListedURL(e,t)}(n,r)}});const Z=new WeakMap,Q=new EventTarget;function ee(e){return new Promise((t=>{const n=new Image;n.addEventListener("load",(()=>t(n))),n.addEventListener("error",(()=>t(null))),n.src=e}))}const te=Z,ne=ee;var re=Object.freeze({__proto__:null,cacheForTesting:te,emitter:Q,getOrQueue:function(e){return Z.has(e)?Z.get(e)??null:(ee(t.Handlers.ModelHandlers.Screenshots.screenshotImageDataUri(e)).then((t=>{Z.set(e,t),Q.dispatchEvent(new CustomEvent("screenshot-loaded",{detail:{screenshot:e,image:t}}))})).catch((()=>{})),null)},loadImageForTesting:ne,preload:function(e){const n=e.map((e=>{if(Z.has(e))return;return ee(t.Handlers.ModelHandlers.Screenshots.screenshotImageDataUri(e)).then((t=>{Z.set(e,t)}))}));return Promise.all(n)}});function ie(e,n){const r=e.navigationId?n.Meta.navigationsByNavigationId.get(e.navigationId):void 0,i=r?.ts??n.Meta.traceBounds.min;let a=function(e){if(t.Insights.Models.LCPPhases.isLCPPhases(e)&&e.lcpEvent)return e.lcpEvent.ts;return null}(e);if(!a&&(a=n.Meta.traceBounds.max,r)){const e=function(e,t){for(let n=0;n<t.Meta.mainFrameNavigations.length;n++){const r=t.Meta.mainFrameNavigations[n];if(r.args.data?.navigationId===e.args.data?.navigationId)return t.Meta.mainFrameNavigations.at(n+1)??null}return null}(r,n);e&&(a=e.ts)}return t.Helpers.Timing.traceWindowFromMicroSeconds(i,a)}var ae=Object.freeze({__proto__:null,AIQueries:class{static networkRequests(e,t){const n=ie(e,t),r=[];for(const e of t.NetworkRequests.byTime){if(e.ts>n.max)break;e.args.data.url.startsWith("data:")||e.ts>=n.min&&e.ts+e.dur<=n.max&&r.push(e)}return r}static networkRequest(e,t){return e.NetworkRequests.byTime.find((e=>e.args.data.url===t))??null}static mainThreadActivity(e,n){let r=null,i=null;if(e.navigationId){const t=n.Meta.navigationsByNavigationId.get(e.navigationId);t?.args.data?.isOutermostMainFrame&&(r=t.pid,i=t.tid)}const a=t.Handlers.Threads.threadsInTrace(n).find((e=>r&&i?e.pid===r&&e.tid===i:"MAIN_THREAD"===e.type));if(!a)return null;const s=ie(e,n);return x.fromTimeOnThread({thread:{pid:a.pid,tid:a.tid},parsedTrace:n,bounds:s})}},ActiveInsight:class{#v;#t;constructor(e,t){this.#v=e,this.#t=t}get insight(){return this.#v}get parsedTrace(){return this.#t}title(){return this.#v.title}}});async function se(e,t,n){const r=new URL(t);r.hash=await async function(e){let t=(new TextEncoder).encode(e);const n=new CompressionStream("gzip"),r=n.writable.getWriter();r.write(t),r.close();const i=await new Response(n.readable).arrayBuffer();t=new Uint8Array(i);let a="";for(let e=0;e<t.length;e+=5e3)a+=String.fromCharCode(...t.subarray(e,e+5e3));return btoa(a)}(JSON.stringify(e)),r.searchParams.set("gzip","1"),window.open(r.toString(),n)}function oe(e,t,n){function r(e){return{name:e,resourceBytes:0}}const i=r(t);function a(e,n){let a=i;i.resourceBytes+=n.resourceBytes;const s=e.replace(t,"").split(/\/+/);s.forEach(((e,t)=>{if(0===e.length)return;const i=t===s.length-1;let o=a.children?.find((t=>t.name===e));o||(o=r(e),a.children=a.children||[],a.children.push(o)),a=o,a.resourceBytes+=n.resourceBytes,i&&void 0!==n.duplicatedNormalizedModuleName&&(a.duplicatedNormalizedModuleName=n.duplicatedNormalizedModuleName)}))}for(const[e,t]of Object.entries(n))a(e,t);if(function e(t){for(;t.children&&1===t.children.length;){const e=t.children[0];t.name+="/"+e.name,e.duplicatedNormalizedModuleName&&(t.duplicatedNormalizedModuleName=e.duplicatedNormalizedModuleName),t.children=e.children}if(t.children)for(const n of t.children)e(n)}(i),!i.name)return{...i,name:e,children:i.children};const s={...i};return s.name=e,s.children=[i],s}var le=Object.freeze({__proto__:null,createTreemapData:function(e,n){const r=[],i=new Map;for(const a of e.scripts){if(!a.url)continue;const e=a.url,s=t.Handlers.ModelHandlers.Scripts.getScriptGeneratedSizes(a);let o;if(a.sourceMap&&s&&!("errorMessage"in s)){const e={};for(const[r,i]of Object.entries(s.files)){const a={resourceBytes:i},s=t.Extras.ScriptDuplication.normalizeSource(r);n.has(s)&&(a.duplicatedNormalizedModuleName=s),e[r]=a}if(s.unmappedBytes){const t={resourceBytes:s.unmappedBytes};e["(unmapped)"]=t}o=oe(a.url,a.url,e)}else o={name:e,resourceBytes:a.content?.length??0};if(a.inline){let t=i.get(a.frame);t||(t={name:e,resourceBytes:0,children:[]},i.set(a.frame,t),r.push(t)),t.resourceBytes+=o.resourceBytes,o.name=a.content?"(inline) "+a.content.trimStart().substring(0,15)+"…":"(inline)",t.children?.push(o)}else r.push(o)}return r},makeScriptNode:oe,openTreemap:function(e,t,n){se({lhr:{mainDocumentUrl:t,audits:{"script-treemap-data":{details:{type:"treemap-data",nodes:e}}},configSettings:{locale:r.DevToolsLocale.DevToolsLocale.instance().locale}},initialView:"duplicate-modules"},"https://googlechrome.github.io/lighthouse/treemap/",`treemap-${n}`)}});export{$ as AICallTree,z as EntityMapper,N as EntryName,I as EntryStyles,q as Helpers,J as IgnoreList,re as ImageCache,ae as InsightAIContext,_ as SourceMapsResolver,le as Treemap};