import*as i18n from"../i18n/i18n.js";import*as SDK from"../sdk/sdk.js";import{RecordType,TimelineModelImpl}from"./TimelineModel.js";const UIStrings={threadS:"Thread {PH1}"},str_=i18n.i18n.registerUIStrings("timeline_model/TimelineJSProfile.ts",UIStrings),i18nString=i18n.i18n.getLocalizedString.bind(void 0,str_);export class TimelineJSProfileProcessor{static generateTracingEventsFromCpuProfile(e,t){const n=e.idleNode,i=e.programNode||null,r=e.gcNode,o=e.samples||[],a=e.timestamps,s=[],l=new Map;l.set(i,[]);for(let c=0;c<o.length;++c){let i=e.nodeByIndex(c);if(!i){console.error(`Node with unknown id ${o[c]} at index ${c}`);continue}if(i===r||i===n)continue;let d=l.get(i);if(!d){d=new Array(i.depth+1),l.set(i,d);for(let e=0;i.parent;i=i.parent)d[e++]=i}const m=new SDK.TracingModel.Event(SDK.TracingModel.DevToolsTimelineEventCategory,RecordType.JSSample,SDK.TracingModel.Phase.Instant,a[c],t);m.args.data={stackTrace:d},s.push(m)}return s}static generateJSFrameEvents(e,t){const n=[],i=[],r=[];let o=0,a=!1;const{showAllEvents:s,showRuntimeCallStats:l,showNativeFunctions:c}=t;function d(e,t){if(r.length){const n=r[r.length-1];e<n&&(console.error(`Child stack is shallower (${e}) than the parent stack (${n}) at ${t}`),e=n)}i.length<e&&(console.error(`Trying to truncate higher than the current stack size at ${t}`),e=i.length);for(let n=0;n<i.length;++n)i[n].setEndTime(t);i.length=e}function m(e){const t=e.name===RecordType.JSSample?e.args.data.stackTrace.slice().reverse():i.map((e=>e.args.data));!function(e){if(s)return;let t=null,n=0;for(let r=0;r<e.length;++r){const o=e[r],a=o.url,s=a&&a.startsWith("native ");if(!c&&s)continue;const d=TimelineJSProfileProcessor.isNativeRuntimeFrame(o);if(d&&(i=o.functionName,!l||!Boolean(TimelineJSProfileProcessor.nativeGroup(i))))continue;const m=d?TimelineJSProfileProcessor.nativeGroup(o.functionName):null;t&&t===m||(t=m,e[n++]=o)}var i;e.length=n}(t);const o=e.endTime||e.startTime,a=Math.min(t.length,i.length);let m;for(m=r[r.length-1]||0;m<a;++m){const e=t[m],n=i[m].args.data;if(p=n,(u=e).scriptId!==p.scriptId||u.functionName!==p.functionName||u.lineNumber!==p.lineNumber)break;i[m].setEndTime(Math.max(i[m].endTime,o))}var u,p;for(d(m,e.startTime);m<t.length;++m){const r=t[m],a=new SDK.TracingModel.Event(SDK.TracingModel.DevToolsTimelineEventCategory,RecordType.JSFrame,SDK.TracingModel.Phase.Complete,e.startTime,e.thread);a.ordinal=e.ordinal,a.addArgs({data:r}),a.setEndTime(o),i.push(a),n.push(a)}}const u=e.find(SDK.TracingModel.TracingModel.isTopLevelEvent),p=u?u.startTime:0;return TimelineModelImpl.forEachEvent(e,(function(e){a&&(d(r.pop(),e.startTime),a=!1),e.ordinal=++o,m(e),r.push(i.length)}),(function(e){d(r.pop(),e.endTime)}),(function(e,t){if(e.ordinal=++o,t&&function(e){switch(e.name){case RecordType.RunMicrotasks:case RecordType.FunctionCall:case RecordType.EvaluateScript:case RecordType.EvaluateModule:case RecordType.EventDispatch:case RecordType.V8Execute:return!0}return!1}(t)||a)m(e);else if(e.name===RecordType.JSSample&&0===i.length){a=!0;const t=i.length;m(e),r.push(t)}}),p),n}static isNativeRuntimeFrame(e){return"native V8Runtime"===e.url}static nativeGroup(e){return e.startsWith("Parse")?TimelineJSProfileProcessor.NativeGroups.Parse:e.startsWith("Compile")||e.startsWith("Recompile")?TimelineJSProfileProcessor.NativeGroups.Compile:null}static buildTraceProfileFromCpuProfile(e,t,n,i){const r=[];if(n&&T("TracingStartedInPage",{data:{sessionId:"1"}},0,0,"M"),i||(i=i18nString(UIStrings.threadS,{PH1:t})),T(SDK.TracingModel.MetadataEvent.ThreadName,{name:i},0,0,"M","__metadata"),!e)return r;const o=new Map,a=e.nodes;for(let g=0;g<a.length;++g)o.set(a[g].id,a[g]);let s=null,l=null,c=e.startTime,d=0;const m=e.samples,u=e.timeDeltas;for(let g=0;g<m.length;++g){d=c,c+=u[g];const e=o.get(m[g]).callFrame.functionName;"(idle)"!==e?(s||(s=T("MessageLoop::RunTask",{},d,0,"X","toplevel")),"(program)"===e?l&&(l.dur=d-l.ts,l=null):l||(l=T("FunctionCall",{data:{sessionId:"1"}},d))):p()}return p(),T("CpuProfile",{data:{cpuProfile:e}},e.endTime,0,"I"),r;function p(){s&&(s.dur=d-s.ts),l&&(l.dur=d-l.ts),s=null,l=null}function T(e,n,i,o,a,s){const l={cat:s||"disabled-by-default-devtools.timeline",name:e,ph:a||"X",pid:1,tid:t,ts:i,args:n};return o&&(l.dur=o),r.push(l),l}}}!function(e){let t;!function(e){e.Compile="Compile",e.Parse="Parse"}(t=e.NativeGroups||(e.NativeGroups={}))}(TimelineJSProfileProcessor||(TimelineJSProfileProcessor={}));