import{Settings,UIString,Throttler,Progress,ObjectWrapper,ResourceType,Color,ParsedURL,StringOutputStream,Console}from'../common/common.js';import{InspectorFrontendHost,Platform,userMetrics,UserMetrics}from'../host/host.js';import{BinaryResourceViewFactory,ResourceSourceFrame,JSONView,PreviewFactory}from'../source_frame/source_frame.js';import{ContentProvider,StaticContentProvider,TextUtils}from'../text_utils/text_utils.js';import{Widget,EmptyWidget,Toolbar,ListWidget,UIUtils,ARIAUtils,SettingsUI,Icon,TreeOutline,XLink,ContextMenu,View,Utils,SplitWidget,TabbedPane,PopoverHelper,Dialog,GlassPane,FilterBar,FilterSuggestionBuilder,DropTarget,ViewManager,ProgressIndicator,Panel}from'../ui/ui.js';import{NetworkManager,SDKModel,NetworkRequest,HARLog,CookieModel,CookieParser,RelatedIssue,RemoteObject,NetworkLog,ResourceTreeModel,Resource,FilmStripModel,TracingManager,TracingModel}from'../sdk/sdk.js';import{SortableDataGrid,DataGrid,ViewportDataGrid}from'../data_grid/data_grid.js';import{StringUtilities}from'../platform/platform.js';import{ThrottlingManager}from'../mobile_throttling/mobile_throttling.js';import{ResourceUtils,FileUtils,TempFile}from'../bindings/bindings.js';import{Linkifier,JSPresentationUtils}from'../components/components.js';import{NetworkPriorities,TimelineGrid,TimelineOverviewPane,FilmStripView}from'../perf_ui/perf_ui.js';import{Workspace,UISourceCode}from'../workspace/workspace.js';import{CookiesTable}from'../cookie_table/cookie_table.js';import{ObjectPropertiesSection}from'../object_ui/object_ui.js';import{HARFormat,HARImporter}from'../har_importer/har_importer.js';import{SearchView}from'../search/search.js';class BinaryResourceView extends Widget.VBox{constructor(base64content,contentUrl,resourceType){super();this.registerRequiredCSS('network/binaryResourceView.css');this._empty=!base64content.length;if(this._empty){new EmptyWidget.EmptyWidget('No data present in selected item').show(this.element);return;}
this._binaryResourceViewFactory=new BinaryResourceViewFactory.BinaryResourceViewFactory(base64content,contentUrl,resourceType);this._toolbar=new Toolbar.Toolbar('binary-view-toolbar',this.element);this._binaryViewObjects=[new BinaryViewObject('base64',ls`Base64`,ls`Copied as Base64`,this._binaryResourceViewFactory.createBase64View.bind(this._binaryResourceViewFactory),this._binaryResourceViewFactory.base64.bind(this._binaryResourceViewFactory)),new BinaryViewObject('hex',ls`Hex Viewer`,ls`Copied as Hex`,this._binaryResourceViewFactory.createHexView.bind(this._binaryResourceViewFactory),this._binaryResourceViewFactory.hex.bind(this._binaryResourceViewFactory)),new BinaryViewObject('utf8',ls`UTF-8`,ls`Copied as UTF-8`,this._binaryResourceViewFactory.createUtf8View.bind(this._binaryResourceViewFactory),this._binaryResourceViewFactory.utf8.bind(this._binaryResourceViewFactory)),];this._binaryViewTypeSetting=Settings.Settings.instance().createSetting('binaryViewType','hex');this._binaryViewTypeCombobox=new Toolbar.ToolbarComboBox(this._binaryViewTypeChanged.bind(this),ls`Binary view type`);for(const viewObject of this._binaryViewObjects){this._binaryViewTypeCombobox.addOption(this._binaryViewTypeCombobox.createOption(viewObject.label,viewObject.type));}
this._toolbar.appendToolbarItem(this._binaryViewTypeCombobox);const copyButton=new Toolbar.ToolbarButton(ls`Copy to clipboard`,'largeicon-copy');copyButton.addEventListener(Toolbar.ToolbarButton.Events.Click,event=>{this._copySelectedViewToClipboard();},this);this._toolbar.appendToolbarItem(copyButton);this._copiedText=new Toolbar.ToolbarText();this._copiedText.element.classList.add('binary-view-copied-text');this._toolbar.element.appendChild(this._copiedText.element);this._addFadeoutSettimeoutId=null;this._lastView=null;this._updateView();}
_getCurrentViewObject(){const filter=obj=>obj.type===this._binaryViewTypeSetting.get();const binaryViewObject=this._binaryViewObjects.find(filter);console.assert(binaryViewObject,`No binary view found for binary view type found in setting 'binaryViewType': ${
            this._binaryViewTypeSetting.get()}`);return binaryViewObject||null;}
async _copySelectedViewToClipboard(){const viewObject=this._getCurrentViewObject();InspectorFrontendHost.InspectorFrontendHostInstance.copyText((await viewObject.content()).content);this._copiedText.setText(viewObject.copiedMessage);this._copiedText.element.classList.remove('fadeout');function addFadeoutClass(){this._copiedText.element.classList.add('fadeout');}
if(this._addFadeoutSettimeoutId){clearTimeout(this._addFadeoutSettimeoutId);this._addFadeoutSettimeoutId=null;}
this._addFadeoutSettimeoutId=setTimeout(addFadeoutClass.bind(this),2000);}
wasShown(){if(!this._empty){this._updateView();}}
_updateView(){const newViewObject=this._getCurrentViewObject();if(!newViewObject){return;}
const newView=newViewObject.getView();if(newView===this._lastView){return;}
if(this._lastView){this._lastView.detach();}
this._lastView=newView;newView.show(this.element,this._toolbar.element);this._binaryViewTypeCombobox.selectElement().value=this._binaryViewTypeSetting.get();}
_binaryViewTypeChanged(){const newViewType=this._binaryViewTypeCombobox.selectedOption().value;if(this._binaryViewTypeSetting.get()===newViewType){return;}
this._binaryViewTypeSetting.set(newViewType);this._updateView();}
addCopyToContextMenu(contextMenu,submenuItemText){if(this._empty){return;}
const copyMenu=contextMenu.clipboardSection().appendSubMenuItem(submenuItemText);const footerSection=copyMenu.footerSection();footerSection.appendItem(ls`Copy as Base64`,async()=>{const content=await this._binaryResourceViewFactory.base64();InspectorFrontendHost.InspectorFrontendHostInstance.copyText(content.content);});footerSection.appendItem(ls`Copy as Hex`,async()=>{const content=await this._binaryResourceViewFactory.hex();InspectorFrontendHost.InspectorFrontendHostInstance.copyText(content.content);});footerSection.appendItem(ls`Copy as UTF-8`,async()=>{const content=await this._binaryResourceViewFactory.utf8();InspectorFrontendHost.InspectorFrontendHostInstance.copyText(content.content);});}}
class BinaryViewObject{constructor(type,label,copiedMessage,createViewFn,deferredContent){this.type=type;this.label=label;this.copiedMessage=copiedMessage;this.content=deferredContent;this._createViewFn=createViewFn;this._view=null;}
getView(){if(!this._view){this._view=this._createViewFn();}
return this._view;}}
var BinaryResourceView$1=Object.freeze({__proto__:null,BinaryResourceView:BinaryResourceView,BinaryViewObject:BinaryViewObject});let _instance=null;class BlockedURLsPane extends Widget.VBox{constructor(){super(true);this.registerRequiredCSS('network/blockedURLsPane.css');_instance=this;this._manager=self.SDK.multitargetNetworkManager;this._manager.addEventListener(NetworkManager.MultitargetNetworkManager.Events.BlockedPatternsChanged,this._update,this);this._toolbar=new Toolbar.Toolbar('',this.contentElement);this._enabledCheckbox=new Toolbar.ToolbarCheckbox(UIString.UIString('Enable request blocking'),undefined,this._toggleEnabled.bind(this));this._toolbar.appendToolbarItem(this._enabledCheckbox);this._toolbar.appendSeparator();const addButton=new Toolbar.ToolbarButton(UIString.UIString('Add pattern'),'largeicon-add');addButton.addEventListener(Toolbar.ToolbarButton.Events.Click,this._addButtonClicked,this);this._toolbar.appendToolbarItem(addButton);const clearButton=new Toolbar.ToolbarButton(UIString.UIString('Remove all patterns'),'largeicon-clear');clearButton.addEventListener(Toolbar.ToolbarButton.Events.Click,this._removeAll,this);this._toolbar.appendToolbarItem(clearButton);this._list=new ListWidget.ListWidget(this);this._list.element.classList.add('blocked-urls');this._list.registerRequiredCSS('network/blockedURLsPane.css');this._list.setEmptyPlaceholder(this._createEmptyPlaceholder());this._list.show(this.contentElement);this._editor=null;this._blockedCountForUrl=new Map();SDKModel.TargetManager.instance().addModelListener(NetworkManager.NetworkManager,NetworkManager.Events.RequestFinished,this._onRequestFinished,this);this._updateThrottler=new Throttler.Throttler(200);this._update();}
_createEmptyPlaceholder(){const element=this.contentElement.createChild('div','no-blocked-urls');const addButton=UIUtils.createTextButton(ls`Add pattern`,this._addButtonClicked.bind(this),'add-button');ARIAUtils.setAccessibleName(addButton,ls`Add request blocking pattern`);element.appendChild(UIUtils.formatLocalized('Requests are not blocked. %s',[addButton]));return element;}
static reset(){if(_instance){_instance.reset();}}
_addButtonClicked(){this._manager.setBlockingEnabled(true);this._list.addNewItem(0,{url:'',enabled:true});}
renderItem(pattern,editable){const count=this._blockedRequestsCount(pattern.url);const element=createElementWithClass('div','blocked-url');const checkbox=element.createChild('input','blocked-url-checkbox');checkbox.type='checkbox';checkbox.checked=pattern.enabled;checkbox.disabled=!this._manager.blockingEnabled();element.createChild('div','blocked-url-label').textContent=pattern.url;element.createChild('div','blocked-url-count').textContent=UIString.UIString('%d blocked',count);element.addEventListener('click',event=>this._togglePattern(pattern,event),false);checkbox.addEventListener('click',event=>this._togglePattern(pattern,event),false);return element;}
_togglePattern(pattern,event){event.consume(true);const patterns=this._manager.blockedPatterns();patterns.splice(patterns.indexOf(pattern),1,{enabled:!pattern.enabled,url:pattern.url});this._manager.setBlockedPatterns(patterns);}
_toggleEnabled(){this._manager.setBlockingEnabled(!this._manager.blockingEnabled());this._update();}
removeItemRequested(pattern,index){const patterns=this._manager.blockedPatterns();patterns.splice(index,1);this._manager.setBlockedPatterns(patterns);}
beginEdit(pattern){this._editor=this._createEditor();this._editor.control('url').value=pattern.url;return this._editor;}
commitEdit(item,editor,isNew){const url=editor.control('url').value;const patterns=this._manager.blockedPatterns();if(isNew){patterns.push({enabled:true,url:url});}else{patterns.splice(patterns.indexOf(item),1,{enabled:true,url:url});}
this._manager.setBlockedPatterns(patterns);}
_createEditor(){if(this._editor){return this._editor;}
const editor=new ListWidget.Editor();const content=editor.contentElement();const titles=content.createChild('div','blocked-url-edit-row');titles.createChild('div').textContent=UIString.UIString('Text pattern to block matching requests; use * for wildcard');const fields=content.createChild('div','blocked-url-edit-row');const validator=(item,index,input)=>{let valid=true;let errorMessage;if(!input.value){errorMessage=ls`Pattern input cannot be empty.`;valid=false;}else if(this._manager.blockedPatterns().find(pattern=>pattern.url===input.value)){errorMessage=ls`Pattern already exists.`;valid=false;}
return{valid,errorMessage};};const urlInput=editor.createInput('url','text','',validator);fields.createChild('div','blocked-url-edit-value').appendChild(urlInput);return editor;}
_removeAll(){this._manager.setBlockedPatterns([]);}
_update(){const enabled=this._manager.blockingEnabled();this._list.element.classList.toggle('blocking-disabled',!enabled&&!!this._manager.blockedPatterns().length);this._enabledCheckbox.setChecked(enabled);this._list.clear();for(const pattern of this._manager.blockedPatterns()){this._list.appendItem(pattern,true);}
return Promise.resolve();}
_blockedRequestsCount(url){if(!url){return 0;}
let result=0;for(const blockedUrl of this._blockedCountForUrl.keys()){if(this._matches(url,blockedUrl)){result+=this._blockedCountForUrl.get(blockedUrl);}}
return result;}
_matches(pattern,url){let pos=0;const parts=pattern.split('*');for(let index=0;index<parts.length;index++){const part=parts[index];if(!part.length){continue;}
pos=url.indexOf(part,pos);if(pos===-1){return false;}
pos+=part.length;}
return true;}
reset(){this._blockedCountForUrl.clear();this._updateThrottler.schedule(this._update.bind(this));}
_onRequestFinished(event){const request=(event.data);if(request.wasBlocked()){const count=this._blockedCountForUrl.get(request.url())||0;this._blockedCountForUrl.set(request.url(),count+1);this._updateThrottler.schedule(this._update.bind(this));}}}
var BlockedURLsPane$1=Object.freeze({__proto__:null,get _instance(){return _instance;},BlockedURLsPane:BlockedURLsPane});class EventSourceMessagesView extends Widget.VBox{constructor(request){super();this.registerRequiredCSS('network/eventSourceMessagesView.css');this.element.classList.add('event-source-messages-view');this._request=request;const columns=([{id:'id',title:UIString.UIString('Id'),sortable:true,weight:8},{id:'type',title:UIString.UIString('Type'),sortable:true,weight:8},{id:'data',title:UIString.UIString('Data'),sortable:false,weight:88},{id:'time',title:UIString.UIString('Time'),sortable:true,weight:8}]);this._dataGrid=new SortableDataGrid.SortableDataGrid({displayName:ls`Event Source`,columns});this._dataGrid.setStriped(true);this._dataGrid.setStickToBottom(true);this._dataGrid.markColumnAsSortedBy('time',DataGrid.Order.Ascending);this._sortItems();this._dataGrid.addEventListener(DataGrid.Events.SortingChanged,this._sortItems,this);this._dataGrid.setName('EventSourceMessagesView');this._dataGrid.asWidget().show(this.element);}
wasShown(){this._dataGrid.rootNode().removeChildren();const messages=this._request.eventSourceMessages();for(let i=0;i<messages.length;++i){this._dataGrid.insertChild(new EventSourceMessageNode(messages[i]));}
this._request.addEventListener(NetworkRequest.Events.EventSourceMessageAdded,this._messageAdded,this);}
willHide(){this._request.removeEventListener(NetworkRequest.Events.EventSourceMessageAdded,this._messageAdded,this);}
_messageAdded(event){const message=(event.data);this._dataGrid.insertChild(new EventSourceMessageNode(message));}
_sortItems(){const sortColumnId=this._dataGrid.sortColumnId();if(!sortColumnId){return;}
const comparator=Comparators[sortColumnId];if(!comparator){return;}
this._dataGrid.sortNodes(comparator,!this._dataGrid.isSortOrderAscending());}}
class EventSourceMessageNode extends SortableDataGrid.SortableDataGridNode{constructor(message){const time=new Date(message.time*1000);const timeText=('0'+time.getHours()).substr(-2)+':'+('0'+time.getMinutes()).substr(-2)+':'+
('0'+time.getSeconds()).substr(-2)+'.'+('00'+time.getMilliseconds()).substr(-3);const timeNode=createElement('div');timeNode.createTextChild(timeText);timeNode.title=time.toLocaleString();super({id:message.eventId,type:message.eventName,data:message.data,time:timeNode});this._message=message;}}
function EventSourceMessageNodeComparator(field,a,b){const aValue=a._message[field];const bValue=b._message[field];return aValue<bValue?-1:aValue>bValue?1:0;}
const Comparators={'id':EventSourceMessageNodeComparator.bind(null,'eventId'),'type':EventSourceMessageNodeComparator.bind(null,'eventName'),'time':EventSourceMessageNodeComparator.bind(null,'time')};var EventSourceMessagesView$1=Object.freeze({__proto__:null,EventSourceMessagesView:EventSourceMessagesView,EventSourceMessageNode:EventSourceMessageNode,EventSourceMessageNodeComparator:EventSourceMessageNodeComparator,Comparators:Comparators});class HARWriter{static async write(stream,requests,progress){const compositeProgress=new Progress.CompositeProgress(progress);const content=await HARWriter._harStringForRequests(requests,compositeProgress);if(progress.isCanceled()){return Promise.resolve();}
return HARWriter._writeToStream(stream,compositeProgress,content);}
static async _harStringForRequests(requests,compositeProgress){const progress=compositeProgress.createSubProgress();progress.setTitle(UIString.UIString('Collecting content…'));progress.setTotalWork(requests.length);const harLog=await HARLog.HARLog.build(requests);const promises=[];for(let i=0;i<requests.length;i++){const promise=requests[i].contentData();promises.push(promise.then(contentLoaded.bind(null,harLog.entries[i])));}
await Promise.all(promises);progress.done();if(progress.isCanceled()){return'';}
return JSON.stringify({log:harLog},null,_jsonIndent);function isValidCharacter(code_point){return code_point<0xD800||(code_point>=0xE000&&code_point<0xFDD0)||(code_point>0xFDEF&&code_point<=0x10FFFF&&(code_point&0xFFFE)!==0xFFFE);}
function needsEncoding(content){for(let i=0;i<content.length;i++){if(!isValidCharacter(content.charCodeAt(i))){return true;}}
return false;}
function contentLoaded(entry,contentData){progress.worked();let encoded=contentData.encoded;if(contentData.content!==null){let content=contentData.content;if(content&&!encoded&&needsEncoding(content)){content=StringUtilities.toBase64(content);encoded=true;}
entry.response.content.text=content;}
if(encoded){entry.response.content.encoding='base64';}}}
static async _writeToStream(stream,compositeProgress,fileContent){const progress=compositeProgress.createSubProgress();progress.setTitle(UIString.UIString('Writing file…'));progress.setTotalWork(fileContent.length);for(let i=0;i<fileContent.length&&!progress.isCanceled();i+=_chunkSize){const chunk=fileContent.substr(i,_chunkSize);await stream.write(chunk);progress.worked(chunk.length);}
progress.done();}}
const _jsonIndent=2;const _chunkSize=100000;var HARWriter$1=Object.freeze({__proto__:null,HARWriter:HARWriter,_jsonIndent:_jsonIndent,_chunkSize:_chunkSize});class NetworkConfigView extends Widget.VBox{constructor(){super(true);this.registerRequiredCSS('network/networkConfigView.css');this.contentElement.classList.add('network-config');this._createCacheSection();this.contentElement.createChild('div').classList.add('panel-section-separator');this._createNetworkThrottlingSection();this.contentElement.createChild('div').classList.add('panel-section-separator');this._createUserAgentSection();}
static createUserAgentSelectAndInput(title){const userAgentSetting=Settings.Settings.instance().createSetting('customUserAgent','');const userAgentSelectElement=createElement('select');ARIAUtils.setAccessibleName(userAgentSelectElement,title);const customOverride={title:UIString.UIString('Custom...'),value:'custom'};userAgentSelectElement.appendChild(new Option(customOverride.title,customOverride.value));for(const userAgentDescriptor of userAgentGroups){const groupElement=userAgentSelectElement.createChild('optgroup');groupElement.label=userAgentDescriptor.title;for(const userAgentVersion of userAgentDescriptor.values){const userAgentValue=NetworkManager.MultitargetNetworkManager.patchUserAgentWithChromeVersion(userAgentVersion.value);groupElement.appendChild(new Option(userAgentVersion.title,userAgentValue));}}
userAgentSelectElement.selectedIndex=0;const otherUserAgentElement=UIUtils.createInput('','text');otherUserAgentElement.value=userAgentSetting.get();otherUserAgentElement.title=userAgentSetting.get();otherUserAgentElement.placeholder=UIString.UIString('Enter a custom user agent');otherUserAgentElement.required=true;ARIAUtils.setAccessibleName(otherUserAgentElement,otherUserAgentElement.placeholder);const errorElement=createElementWithClass('div','network-config-input-validation-error');ARIAUtils.markAsAlert(errorElement);if(!otherUserAgentElement.value){errorElement.textContent=ls`Custom user agent field is required`;}
settingChanged();userAgentSelectElement.addEventListener('change',userAgentSelected,false);otherUserAgentElement.addEventListener('input',applyOtherUserAgent,false);function userAgentSelected(){const value=userAgentSelectElement.options[userAgentSelectElement.selectedIndex].value;if(value!==customOverride.value){userAgentSetting.set(value);otherUserAgentElement.value=value;otherUserAgentElement.title=value;}else{otherUserAgentElement.select();}
errorElement.textContent='';}
function settingChanged(){const value=userAgentSetting.get();const options=userAgentSelectElement.options;let selectionRestored=false;for(let i=0;i<options.length;++i){if(options[i].value===value){userAgentSelectElement.selectedIndex=i;selectionRestored=true;break;}}
if(!selectionRestored){userAgentSelectElement.selectedIndex=0;}}
function applyOtherUserAgent(){if(userAgentSetting.get()!==otherUserAgentElement.value){if(!otherUserAgentElement.value){errorElement.textContent=ls`Custom user agent field is required`;}else{errorElement.textContent='';}
userAgentSetting.set(otherUserAgentElement.value);otherUserAgentElement.title=otherUserAgentElement.value;settingChanged();}}
return{select:userAgentSelectElement,input:otherUserAgentElement,error:errorElement};}
_createSection(title,className){const section=this.contentElement.createChild('section','network-config-group');if(className){section.classList.add(className);}
section.createChild('div','network-config-title').textContent=title;return section.createChild('div','network-config-fields');}
_createCacheSection(){const section=this._createSection(UIString.UIString('Caching'),'network-config-disable-cache');section.appendChild(SettingsUI.createSettingCheckbox(UIString.UIString('Disable cache'),Settings.Settings.instance().moduleSetting('cacheDisabled'),true));}
_createNetworkThrottlingSection(){const title=ls`Network throttling`;const section=this._createSection(title,'network-config-throttling');const networkThrottlingSelect=(section.createChild('select','chrome-select'));ThrottlingManager.throttlingManager().decorateSelectWithNetworkThrottling(networkThrottlingSelect);ARIAUtils.setAccessibleName(networkThrottlingSelect,title);}
_createUserAgentSection(){const title=ls`User agent`;const section=this._createSection(title,'network-config-ua');const checkboxLabel=UIUtils.CheckboxLabel.create(UIString.UIString('Select automatically'),true);section.appendChild(checkboxLabel);const autoCheckbox=checkboxLabel.checkboxElement;const customUserAgentSetting=Settings.Settings.instance().createSetting('customUserAgent','');customUserAgentSetting.addChangeListener(()=>{if(autoCheckbox.checked){return;}
self.SDK.multitargetNetworkManager.setCustomUserAgentOverride(customUserAgentSetting.get());});const customUserAgentSelectBox=section.createChild('div','network-config-ua-custom');autoCheckbox.addEventListener('change',userAgentSelectBoxChanged);const customSelectAndInput=NetworkConfigView.createUserAgentSelectAndInput(title);customSelectAndInput.select.classList.add('chrome-select');customUserAgentSelectBox.appendChild(customSelectAndInput.select);customUserAgentSelectBox.appendChild(customSelectAndInput.input);customUserAgentSelectBox.appendChild(customSelectAndInput.error);userAgentSelectBoxChanged();function userAgentSelectBoxChanged(){const useCustomUA=!autoCheckbox.checked;customUserAgentSelectBox.classList.toggle('checked',useCustomUA);customSelectAndInput.select.disabled=!useCustomUA;customSelectAndInput.input.disabled=!useCustomUA;customSelectAndInput.error.hidden=!useCustomUA;const customUA=useCustomUA?customUserAgentSetting.get():'';self.SDK.multitargetNetworkManager.setCustomUserAgentOverride(customUA);}}}
const userAgentGroups=[{title:ls`Android`,values:[{title:ls`Android (4.0.2) Browser \u2014 Galaxy Nexus`,value:'Mozilla/5.0 (Linux; U; Android 4.0.2; en-us; Galaxy Nexus Build/ICL53F) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30'},{title:ls`Android (2.3) Browser \u2014 Nexus S`,value:'Mozilla/5.0 (Linux; U; Android 2.3.6; en-us; Nexus S Build/GRK39F) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1'}]},{title:ls`BlackBerry`,values:[{title:ls`BlackBerry \u2014 BB10`,value:'Mozilla/5.0 (BB10; Touch) AppleWebKit/537.1+ (KHTML, like Gecko) Version/10.0.0.1337 Mobile Safari/537.1+'},{title:ls`BlackBerry \u2014 PlayBook 2.1`,value:'Mozilla/5.0 (PlayBook; U; RIM Tablet OS 2.1.0; en-US) AppleWebKit/536.2+ (KHTML, like Gecko) Version/7.2.1.0 Safari/536.2+'},{title:ls`BlackBerry \u2014 9900`,value:'Mozilla/5.0 (BlackBerry; U; BlackBerry 9900; en-US) AppleWebKit/534.11+ (KHTML, like Gecko) Version/7.0.0.187 Mobile Safari/534.11+'}]},{title:ls`Chrome`,values:[{title:ls`Chrome \u2014 Android Mobile`,value:'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Mobile Safari/537.36'},{title:ls`Chrome \u2014 Android Mobile (high-end)`,value:'Mozilla/5.0 (Linux; Android 10; Pixel 4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Mobile Safari/537.36'},{title:ls`Chrome \u2014 Android Tablet`,value:'Mozilla/5.0 (Linux; Android 4.3; Nexus 7 Build/JSS15Q) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36'},{title:ls`Chrome \u2014 iPhone`,value:'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/%s Mobile/15E148 Safari/604.1'},{title:ls`Chrome \u2014 iPad`,value:'Mozilla/5.0 (iPad; CPU OS 13_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/%s Mobile/15E148 Safari/604.1'},{title:ls`Chrome \u2014 Chrome OS`,value:'Mozilla/5.0 (X11; CrOS x86_64 10066.0.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36'},{title:ls`Chrome \u2014 Mac`,value:'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36'},{title:ls`Chrome \u2014 Windows`,value:'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36'}]},{title:ls`Firefox`,values:[{title:ls`Firefox \u2014 Android Mobile`,value:'Mozilla/5.0 (Android 4.4; Mobile; rv:70.0) Gecko/70.0 Firefox/70.0'},{title:ls`Firefox \u2014 Android Tablet`,value:'Mozilla/5.0 (Android 4.4; Tablet; rv:70.0) Gecko/70.0 Firefox/70.0'},{title:ls`Firefox \u2014 iPhone`,value:'Mozilla/5.0 (iPhone; CPU iPhone OS 8_3 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) FxiOS/1.0 Mobile/12F69 Safari/600.1.4'},{title:ls`Firefox \u2014 iPad`,value:'Mozilla/5.0 (iPad; CPU iPhone OS 8_3 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) FxiOS/1.0 Mobile/12F69 Safari/600.1.4'},{title:ls`Firefox \u2014 Mac`,value:'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:70.0) Gecko/20100101 Firefox/70.0'},{title:ls`Firefox \u2014 Windows`,value:'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:70.0) Gecko/20100101 Firefox/70.0'}]},{title:ls`Googlebot`,values:[{title:ls`Googlebot`,value:'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'},{title:ls`Googlebot Desktop`,value:'Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; Googlebot/2.1; +http://www.google.com/bot.html) Chrome/%s Safari/537.36'},{title:ls`Googlebot Smartphone`,value:'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'}]},{title:ls`Internet Explorer`,values:[{title:ls`Internet Explorer 11`,value:'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko'},{title:ls`Internet Explorer 10`,value:'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)'},{title:ls`Internet Explorer 9`,value:'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)'},{title:ls`Internet Explorer 8`,value:'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)'},{title:ls`Internet Explorer 7`,value:'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)'}]},{title:ls`Microsoft Edge`,values:[{title:ls`Microsoft Edge (Chromium) \u2014 Windows`,value:'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36 Edg/%s'},{title:ls`Microsoft Edge (Chromium) \u2014 Mac`,value:'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Chrome/%s Safari/604.1 Edg/%s'},{title:ls`Microsoft Edge \u2014 iPhone`,value:'Mozilla/5.0 (iPhone; CPU iPhone OS 12_3_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1.1 EdgiOS/44.5.0.10 Mobile/15E148 Safari/604.1'},{title:ls`Microsoft Edge \u2014 iPad`,value:'Mozilla/5.0 (iPad; CPU OS 12_3_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 EdgiOS/44.5.2 Mobile/15E148 Safari/605.1.15'},{title:ls`Microsoft Edge \u2014 Android Mobile`,value:'Mozilla/5.0 (Linux; Android 8.1.0; Pixel Build/OPM4.171019.021.D1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.109 Mobile Safari/537.36 EdgA/42.0.0.2057'},{title:ls`Microsoft Edge \u2014 Android Tablet`,value:'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 7 Build/MOB30X) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.109 Safari/537.36 EdgA/42.0.0.2057'},{title:ls`Microsoft Edge (EdgeHTML) \u2014 Windows`,value:'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.18362'},{title:ls`Microsoft Edge (EdgeHTML) \u2014 XBox`,value:'Mozilla/5.0 (Windows NT 10.0; Win64; x64; Xbox; Xbox One) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.18362'}]},{title:ls`Opera`,values:[{title:ls`Opera \u2014 Mac`,value:'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36 OPR/65.0.3467.48'},{title:ls`Opera \u2014 Windows`,value:'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36 OPR/65.0.3467.48'},{title:ls`Opera (Presto) \u2014 Mac`,value:'Opera/9.80 (Macintosh; Intel Mac OS X 10.9.1) Presto/2.12.388 Version/12.16'},{title:ls`Opera (Presto) \u2014 Windows`,value:'Opera/9.80 (Windows NT 6.1) Presto/2.12.388 Version/12.16'},{title:ls`Opera Mobile \u2014 Android Mobile`,value:'Opera/12.02 (Android 4.1; Linux; Opera Mobi/ADR-1111101157; U; en-US) Presto/2.9.201 Version/12.02'},{title:ls`Opera Mini \u2014 iOS`,value:'Opera/9.80 (iPhone; Opera Mini/8.0.0/34.2336; U; en) Presto/2.8.119 Version/11.10'}]},{title:ls`Safari`,values:[{title:ls`Safari \u2014 iPad iOS 13.2`,value:'Mozilla/5.0 (iPad; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1'},{title:ls`Safari \u2014 iPhone iOS 13.2`,value:'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1'},{title:ls`Safari \u2014 Mac`,value:'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Safari/605.1.15'}]},{title:ls`UC Browser`,values:[{title:ls`UC Browser \u2014 Android Mobile`,value:'Mozilla/5.0 (Linux; U; Android 8.1.0; en-US; Nexus 6P Build/OPM7.181205.001) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.108 UCBrowser/12.11.1.1197 Mobile Safari/537.36'},{title:ls`UC Browser \u2014 iOS`,value:'Mozilla/5.0 (iPhone; CPU iPhone OS 12_1 like Mac OS X; zh-CN) AppleWebKit/537.51.1 (KHTML, like Gecko) Mobile/16B92 UCBrowser/12.1.7.1109 Mobile AliApp(TUnionSDK/0.1.20.3)'},{title:ls`UC Browser \u2014 Windows Phone`,value:'Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA; Lumia 920) UCBrowser/10.1.0.563 Mobile'}]}];var NetworkConfigView$1=Object.freeze({__proto__:null,NetworkConfigView:NetworkConfigView,userAgentGroups:userAgentGroups});class NetworkTimeBoundary{constructor(minimum,maximum){this.minimum=minimum;this.maximum=maximum;}
equals(other){return(this.minimum===other.minimum)&&(this.maximum===other.maximum);}}
class NetworkTimeCalculator extends ObjectWrapper.ObjectWrapper{constructor(startAtZero){super();this.startAtZero=startAtZero;this._minimumBoundary=-1;this._maximumBoundary=-1;this._boundryChangedEventThrottler=new Throttler.Throttler(0);this._window=null;}
setWindow(window){this._window=window;this._boundaryChanged();}
setInitialUserFriendlyBoundaries(){this._minimumBoundary=0;this._maximumBoundary=1;}
computePosition(time){return(time-this.minimumBoundary())/this.boundarySpan()*this._workingArea;}
formatValue(value,precision){return Number.secondsToString(value,!!precision);}
minimumBoundary(){return this._window?this._window.minimum:this._minimumBoundary;}
zeroTime(){return this._minimumBoundary;}
maximumBoundary(){return this._window?this._window.maximum:this._maximumBoundary;}
boundary(){return new NetworkTimeBoundary(this.minimumBoundary(),this.maximumBoundary());}
boundarySpan(){return this.maximumBoundary()-this.minimumBoundary();}
reset(){this._minimumBoundary=-1;this._maximumBoundary=-1;this._boundaryChanged();}
_value(item){return 0;}
setDisplayWidth(clientWidth){this._workingArea=clientWidth;}
computeBarGraphPercentages(request){let start;let middle;let end;if(request.startTime!==-1){start=((request.startTime-this.minimumBoundary())/this.boundarySpan())*100;}else{start=0;}
if(request.responseReceivedTime!==-1){middle=((request.responseReceivedTime-this.minimumBoundary())/this.boundarySpan())*100;}else{middle=(this.startAtZero?start:100);}
if(request.endTime!==-1){end=((request.endTime-this.minimumBoundary())/this.boundarySpan())*100;}else{end=(this.startAtZero?middle:100);}
if(this.startAtZero){end-=start;middle-=start;start=0;}
return{start:start,middle:middle,end:end};}
computePercentageFromEventTime(eventTime){if(eventTime!==-1&&!this.startAtZero){return((eventTime-this.minimumBoundary())/this.boundarySpan())*100;}
return 0;}
percentageToTime(percentage){return percentage*this.boundarySpan()/100+this.minimumBoundary();}
_boundaryChanged(){this._boundryChangedEventThrottler.schedule(dispatchEvent.bind(this));function dispatchEvent(){this.dispatchEventToListeners(Events.BoundariesChanged);return Promise.resolve();}}
updateBoundariesForEventTime(eventTime){if(eventTime===-1||this.startAtZero){return;}
if(this._maximumBoundary===undefined||eventTime>this._maximumBoundary){this._maximumBoundary=eventTime;this._boundaryChanged();}}
computeBarGraphLabels(request){let rightLabel='';if(request.responseReceivedTime!==-1&&request.endTime!==-1){rightLabel=Number.secondsToString(request.endTime-request.responseReceivedTime);}
const hasLatency=request.latency>0;const leftLabel=hasLatency?Number.secondsToString(request.latency):rightLabel;if(request.timing){return{left:leftLabel,right:rightLabel};}
let tooltip;if(hasLatency&&rightLabel){const total=Number.secondsToString(request.duration);tooltip=_latencyDownloadTotalFormat.format(leftLabel,rightLabel,total);}else if(hasLatency){tooltip=_latencyFormat.format(leftLabel);}else if(rightLabel){tooltip=_downloadFormat.format(rightLabel);}
if(request.fetchedViaServiceWorker){tooltip=_fromServiceWorkerFormat.format(tooltip);}else if(request.cached()){tooltip=_fromCacheFormat.format(tooltip);}
return{left:leftLabel,right:rightLabel,tooltip:tooltip};}
updateBoundaries(request){const lowerBound=this._lowerBound(request);const upperBound=this._upperBound(request);let changed=false;if(lowerBound!==-1||this.startAtZero){changed=this._extendBoundariesToIncludeTimestamp(this.startAtZero?0:lowerBound);}
if(upperBound!==-1){changed=this._extendBoundariesToIncludeTimestamp(upperBound)||changed;}
if(changed){this._boundaryChanged();}}
_extendBoundariesToIncludeTimestamp(timestamp){const previousMinimumBoundary=this._minimumBoundary;const previousMaximumBoundary=this._maximumBoundary;const minOffset=_minimumSpread;if(this._minimumBoundary===-1||this._maximumBoundary===-1){this._minimumBoundary=timestamp;this._maximumBoundary=timestamp+minOffset;}else{this._minimumBoundary=Math.min(timestamp,this._minimumBoundary);this._maximumBoundary=Math.max(timestamp,this._minimumBoundary+minOffset,this._maximumBoundary);}
return previousMinimumBoundary!==this._minimumBoundary||previousMaximumBoundary!==this._maximumBoundary;}
_lowerBound(request){return 0;}
_upperBound(request){return 0;}}
const _minimumSpread=0.1;const Events={BoundariesChanged:Symbol('BoundariesChanged')};const _latencyDownloadTotalFormat=new UIString.UIStringFormat('%s latency, %s download (%s total)');const _latencyFormat=new UIString.UIStringFormat('%s latency');const _downloadFormat=new UIString.UIStringFormat('%s download');const _fromServiceWorkerFormat=new UIString.UIStringFormat('%s (from ServiceWorker)');const _fromCacheFormat=new UIString.UIStringFormat('%s (from cache)');class NetworkTransferTimeCalculator extends NetworkTimeCalculator{constructor(){super(false);}
formatValue(value,precision){return Number.secondsToString(value-this.zeroTime(),!!precision);}
_lowerBound(request){return request.issueTime();}
_upperBound(request){return request.endTime;}}
class NetworkTransferDurationCalculator extends NetworkTimeCalculator{constructor(){super(true);}
formatValue(value,precision){return Number.secondsToString(value,!!precision);}
_upperBound(request){return request.duration;}}
var NetworkTimeCalculator$1=Object.freeze({__proto__:null,NetworkTimeBoundary:NetworkTimeBoundary,NetworkTimeCalculator:NetworkTimeCalculator,_minimumSpread:_minimumSpread,Events:Events,_latencyDownloadTotalFormat:_latencyDownloadTotalFormat,_latencyFormat:_latencyFormat,_downloadFormat:_downloadFormat,_fromServiceWorkerFormat:_fromServiceWorkerFormat,_fromCacheFormat:_fromCacheFormat,NetworkTransferTimeCalculator:NetworkTransferTimeCalculator,NetworkTransferDurationCalculator:NetworkTransferDurationCalculator});class RequestCookiesView extends Widget.Widget{constructor(request){super();this.registerRequiredCSS('network/requestCookiesView.css');this.element.classList.add('request-cookies-view');this._request=request;this._detailedRequestCookies=null;this._showFilteredOutCookiesSetting=Settings.Settings.instance().createSetting('show-filtered-out-request-cookies',false);this._emptyWidget=new EmptyWidget.EmptyWidget(UIString.UIString('This request has no cookies.'));this._emptyWidget.show(this.element);this._requestCookiesTitle=this.element.createChild('div');const titleText=this._requestCookiesTitle.createChild('span','request-cookies-title');titleText.textContent=ls`Request Cookies`;titleText.title=ls`Cookies that were sent to the server in the 'cookie' header of the request`;const requestCookiesCheckbox=SettingsUI.createSettingCheckbox(ls`show filtered out request cookies`,this._showFilteredOutCookiesSetting,true);requestCookiesCheckbox.checkboxElement.addEventListener('change',()=>{this._refreshRequestCookiesView();});this._requestCookiesTitle.appendChild(requestCookiesCheckbox);this._requestCookiesEmpty=this.element.createChild('div','cookies-panel-item');this._requestCookiesEmpty.textContent=ls`No request cookies were sent.`;this._requestCookiesTable=new CookiesTable.CookiesTable(true);this._requestCookiesTable.contentElement.classList.add('cookie-table','cookies-panel-item');this._requestCookiesTable.show(this.element);this._responseCookiesTitle=this.element.createChild('div','request-cookies-title');this._responseCookiesTitle.textContent=ls`Response Cookies`;this._responseCookiesTitle.title=ls`Cookies that were received from the server in the 'set-cookie' header of the response`;this._responseCookiesTable=new CookiesTable.CookiesTable(true);this._responseCookiesTable.contentElement.classList.add('cookie-table','cookies-panel-item');this._responseCookiesTable.show(this.element);this._malformedResponseCookiesTitle=this.element.createChild('div','request-cookies-title');this._malformedResponseCookiesTitle.textContent=ls`Malformed Response Cookies`;this._malformedResponseCookiesTitle.title=ls`Cookies that were received from the server in the 'set-cookie' header of the response but were malformed`;this._malformedResponseCookiesList=this.element.createChild('div');}
_getRequestCookies(){let requestCookies=[];const requestCookieToBlockedReasons=new Map();if(this._request.requestCookies.length){requestCookies=this._request.requestCookies.slice();if(this._detailedRequestCookies){requestCookies=requestCookies.map(cookie=>{for(const detailedCookie of(this._detailedRequestCookies||[])){if(detailedCookie.name()===cookie.name()&&detailedCookie.value()===cookie.value()){return detailedCookie;}}
return cookie;});}else{const networkManager=NetworkManager.NetworkManager.forRequest(this._request);if(networkManager){const cookieModel=networkManager.target().model(CookieModel.CookieModel);if(cookieModel){cookieModel.getCookies([this._request.url()]).then(cookies=>{this._detailedRequestCookies=cookies;this._refreshRequestCookiesView();});}}}}
if(this._showFilteredOutCookiesSetting.get()){for(const blockedCookie of this._request.blockedRequestCookies()){requestCookieToBlockedReasons.set(blockedCookie.cookie,blockedCookie.blockedReasons.map(blockedReason=>{return{attribute:NetworkRequest.cookieBlockedReasonToAttribute(blockedReason),uiString:NetworkRequest.cookieBlockedReasonToUiString(blockedReason)};}));requestCookies.push(blockedCookie.cookie);}}
return{requestCookies,requestCookieToBlockedReasons};}
_getResponseCookies(){let responseCookies=[];const responseCookieToBlockedReasons=new Map();const malformedResponseCookies=[];if(this._request.responseCookies.length){const blockedCookieLines=this._request.blockedResponseCookies().map(blockedCookie=>blockedCookie.cookieLine);responseCookies=this._request.responseCookies.filter(cookie=>{const index=blockedCookieLines.indexOf(cookie.getCookieLine());if(index!==-1){blockedCookieLines[index]=null;return false;}
return true;});for(const blockedCookie of this._request.blockedResponseCookies()){const parsedCookies=CookieParser.CookieParser.parseSetCookie(blockedCookie.cookieLine);if(!parsedCookies.length||blockedCookie.blockedReasons.includes(Protocol.Network.SetCookieBlockedReason.SyntaxError)){malformedResponseCookies.push(blockedCookie);continue;}
const cookie=blockedCookie.cookie||parsedCookies[0];if(cookie){responseCookieToBlockedReasons.set(cookie,blockedCookie.blockedReasons.map(blockedReason=>{return{attribute:NetworkRequest.setCookieBlockedReasonToAttribute(blockedReason),uiString:NetworkRequest.setCookieBlockedReasonToUiString(blockedReason)};}));responseCookies.push(cookie);}}}
return{responseCookies,responseCookieToBlockedReasons,malformedResponseCookies};}
_refreshRequestCookiesView(){if(!this.isShowing()){return;}
const gotCookies=this._request.requestCookies.length||this._request.responseCookies.length;if(gotCookies){this._emptyWidget.hideWidget();}else{this._emptyWidget.showWidget();}
const{requestCookies,requestCookieToBlockedReasons}=this._getRequestCookies();const{responseCookies,responseCookieToBlockedReasons,malformedResponseCookies}=this._getResponseCookies();if(requestCookies.length){this._requestCookiesTitle.classList.remove('hidden');this._requestCookiesEmpty.classList.add('hidden');this._requestCookiesTable.showWidget();this._requestCookiesTable.setCookies(requestCookies,requestCookieToBlockedReasons);}else if(this._request.blockedRequestCookies().length){this._requestCookiesTitle.classList.remove('hidden');this._requestCookiesEmpty.classList.remove('hidden');this._requestCookiesTable.hideWidget();}else{this._requestCookiesTitle.classList.add('hidden');this._requestCookiesEmpty.classList.add('hidden');this._requestCookiesTable.hideWidget();}
if(responseCookies.length){this._responseCookiesTitle.classList.remove('hidden');this._responseCookiesTable.showWidget();this._responseCookiesTable.setCookies(responseCookies,responseCookieToBlockedReasons);}else{this._responseCookiesTitle.classList.add('hidden');this._responseCookiesTable.hideWidget();}
if(malformedResponseCookies.length){this._malformedResponseCookiesTitle.classList.remove('hidden');this._malformedResponseCookiesList.classList.remove('hidden');this._malformedResponseCookiesList.removeChildren();for(const malformedCookie of malformedResponseCookies){const listItem=this._malformedResponseCookiesList.createChild('span','cookie-line source-code');const icon=Icon.Icon.create('smallicon-error','cookie-warning-icon');listItem.appendChild(icon);listItem.createTextChild(malformedCookie.cookieLine);listItem.title=NetworkRequest.setCookieBlockedReasonToUiString(Protocol.Network.SetCookieBlockedReason.SyntaxError);}}else{this._malformedResponseCookiesTitle.classList.add('hidden');this._malformedResponseCookiesList.classList.add('hidden');}}
wasShown(){this._request.addEventListener(NetworkRequest.Events.RequestHeadersChanged,this._refreshRequestCookiesView,this);this._request.addEventListener(NetworkRequest.Events.ResponseHeadersChanged,this._refreshRequestCookiesView,this);this._refreshRequestCookiesView();}
willHide(){this._request.removeEventListener(NetworkRequest.Events.RequestHeadersChanged,this._refreshRequestCookiesView,this);this._request.removeEventListener(NetworkRequest.Events.ResponseHeadersChanged,this._refreshRequestCookiesView,this);}}
var RequestCookiesView$1=Object.freeze({__proto__:null,RequestCookiesView:RequestCookiesView});class RequestHeadersView extends Widget.VBox{constructor(request){super();this.registerRequiredCSS('network/requestHeadersView.css');this.element.classList.add('request-headers-view');this._request=request;this._decodeRequestParameters=true;this._showRequestHeadersText=false;this._showResponseHeadersText=false;const contentType=request.requestContentType();if(contentType){this._decodeRequestParameters=!!contentType.match(/^application\/x-www-form-urlencoded\s*(;.*)?$/i);}
this._highlightedElement=null;const root=new TreeOutline.TreeOutlineInShadow();root.registerRequiredCSS('object_ui/objectValue.css');root.registerRequiredCSS('object_ui/objectPropertiesSection.css');root.registerRequiredCSS('network/requestHeadersTree.css');root.element.classList.add('request-headers-tree');root.makeDense();this.element.appendChild(root.element);const generalCategory=new Category(root,'general',UIString.UIString('General'));generalCategory.hidden=false;this._root=generalCategory;this._urlItem=generalCategory.createLeaf();this._requestMethodItem=generalCategory.createLeaf();this._statusCodeItem=generalCategory.createLeaf();this._remoteAddressItem=generalCategory.createLeaf();this._remoteAddressItem.hidden=true;this._referrerPolicyItem=generalCategory.createLeaf();this._referrerPolicyItem.hidden=true;this._responseHeadersCategory=new Category(root,'responseHeaders','');this._requestHeadersCategory=new Category(root,'requestHeaders','');this._queryStringCategory=new Category(root,'queryString','');this._formDataCategory=new Category(root,'formData','');this._requestPayloadCategory=new Category(root,'requestPayload',UIString.UIString('Request Payload'));}
wasShown(){this._clearHighlight();this._request.addEventListener(NetworkRequest.Events.RemoteAddressChanged,this._refreshRemoteAddress,this);this._request.addEventListener(NetworkRequest.Events.RequestHeadersChanged,this._refreshRequestHeaders,this);this._request.addEventListener(NetworkRequest.Events.ResponseHeadersChanged,this._refreshResponseHeaders,this);this._request.addEventListener(NetworkRequest.Events.FinishedLoading,this._refreshHTTPInformation,this);this._refreshURL();this._refreshQueryString();this._refreshRequestHeaders();this._refreshResponseHeaders();this._refreshHTTPInformation();this._refreshRemoteAddress();this._refreshReferrerPolicy();this._root.select(true,false);}
willHide(){this._request.removeEventListener(NetworkRequest.Events.RemoteAddressChanged,this._refreshRemoteAddress,this);this._request.removeEventListener(NetworkRequest.Events.RequestHeadersChanged,this._refreshRequestHeaders,this);this._request.removeEventListener(NetworkRequest.Events.ResponseHeadersChanged,this._refreshResponseHeaders,this);this._request.removeEventListener(NetworkRequest.Events.FinishedLoading,this._refreshHTTPInformation,this);}
_formatHeader(name,value){const fragment=createDocumentFragment();fragment.createChild('div','header-name').textContent=name+': ';fragment.createChild('span','header-separator');fragment.createChild('div','header-value source-code').textContent=value;return fragment;}
_formatHeaderObject(header){const fragment=createDocumentFragment();if(header.headerNotSet){fragment.createChild('div','header-badge header-badge-text').textContent='not-set';}
const colon=header.value?': ':'';fragment.createChild('div','header-name').textContent=header.name+colon;fragment.createChild('span','header-separator');if(header.value){if(header.headerValueIncorrect){fragment.createChild('div','header-value source-code header-warning').textContent=header.value;}else{fragment.createChild('div','header-value source-code').textContent=header.value;}}
if(header.details){const detailsNode=fragment.createChild('div','header-details');const callToAction=detailsNode.createChild('div','call-to-action');const callToActionBody=callToAction.createChild('div','call-to-action-body');callToActionBody.createChild('div','explanation').textContent=header.details.explanation;for(const example of header.details.examples){const exampleNode=callToActionBody.createChild('div','example');exampleNode.createChild('code').textContent=example.codeSnippet;if(example.comment){exampleNode.createChild('span','comment').textContent=example.comment;}}
if(Root.Runtime.experiments.isEnabled('issuesPane')&&RelatedIssue.hasIssueOfCategory(this._request,RelatedIssue.IssueCategory.CrossOriginEmbedderPolicy)){const link=createElementWithClass('div','devtools-link');link.onclick=()=>{RelatedIssue.reveal(this._request,RelatedIssue.IssueCategory.CrossOriginEmbedderPolicy);};const text=createElementWithClass('span','devtools-link');text.textContent='Learn more in the issues panel';link.appendChild(text);link.prepend(Icon.Icon.create('largeicon-breaking-change','icon'));callToActionBody.appendChild(link);}else if(header.details.link){const link=XLink.XLink.create(header.details.link.url,ls`Learn more`,'link');link.prepend(Icon.Icon.create('largeicon-link','link-icon'));callToActionBody.appendChild(link);}}
return fragment;}
_formatParameter(value,className,decodeParameters){let errorDecoding=false;if(decodeParameters){value=value.replace(/\+/g,' ');if(value.indexOf('%')>=0){try{value=decodeURIComponent(value);}catch(e){errorDecoding=true;}}}
const div=createElementWithClass('div',className);if(value===''){div.classList.add('empty-value');}
if(errorDecoding){div.createChild('span','header-decode-error').textContent=UIString.UIString('(unable to decode value)');}else{div.textContent=value;}
return div;}
_refreshURL(){this._urlItem.title=this._formatHeader(UIString.UIString('Request URL'),this._request.url());}
_refreshQueryString(){const queryString=this._request.queryString();const queryParameters=this._request.queryParameters;this._queryStringCategory.hidden=!queryParameters;if(queryParameters){this._refreshParams(UIString.UIString('Query String Parameters'),queryParameters,queryString,this._queryStringCategory);}}
async _refreshFormData(){const formData=await this._request.requestFormData();if(!formData){this._formDataCategory.hidden=true;this._requestPayloadCategory.hidden=true;return;}
const formParameters=await this._request.formParameters();if(formParameters){this._formDataCategory.hidden=false;this._requestPayloadCategory.hidden=true;this._refreshParams(UIString.UIString('Form Data'),formParameters,formData,this._formDataCategory);}else{this._requestPayloadCategory.hidden=false;this._formDataCategory.hidden=true;try{const json=JSON.parse(formData);this._refreshRequestJSONPayload(json,formData);}catch(e){this._populateTreeElementWithSourceText(this._requestPayloadCategory,formData);}}}
_populateTreeElementWithSourceText(treeElement,sourceText){const max_len=3000;const text=(sourceText||'').trim();const trim=text.length>max_len;const sourceTextElement=createElementWithClass('span','header-value source-code');sourceTextElement.textContent=trim?text.substr(0,max_len):text;const sourceTreeElement=new TreeOutline.TreeElement(sourceTextElement);treeElement.removeChildren();treeElement.appendChild(sourceTreeElement);if(!trim){return;}
const showMoreButton=createElementWithClass('button','request-headers-show-more-button');showMoreButton.textContent=UIString.UIString('Show more');function showMore(){showMoreButton.remove();sourceTextElement.textContent=text;sourceTreeElement.listItemElement.removeEventListener('contextmenu',onContextMenuShowMore);}
showMoreButton.addEventListener('click',showMore);function onContextMenuShowMore(event){const contextMenu=new ContextMenu.ContextMenu(event);const section=contextMenu.newSection();section.appendItem(ls`Show more`,showMore);contextMenu.show();}
sourceTreeElement.listItemElement.addEventListener('contextmenu',onContextMenuShowMore);sourceTextElement.appendChild(showMoreButton);}
_refreshParams(title,params,sourceText,paramsTreeElement){paramsTreeElement.removeChildren();paramsTreeElement.listItemElement.removeChildren();paramsTreeElement.listItemElement.createChild('div','selection fill');paramsTreeElement.listItemElement.createTextChild(title);const headerCount=createElementWithClass('span','header-count');headerCount.textContent=UIString.UIString('\xA0(%d)',params.length);paramsTreeElement.listItemElement.appendChild(headerCount);const shouldViewSource=paramsTreeElement[_viewSourceSymbol];if(shouldViewSource){this._appendParamsSource(title,params,sourceText,paramsTreeElement);}else{this._appendParamsParsed(title,params,sourceText,paramsTreeElement);}}
_appendParamsSource(title,params,sourceText,paramsTreeElement){this._populateTreeElementWithSourceText(paramsTreeElement,sourceText);const listItemElement=paramsTreeElement.listItemElement;const viewParsed=function(event){listItemElement.removeEventListener('contextmenu',viewParsedContextMenu);paramsTreeElement[_viewSourceSymbol]=false;this._refreshParams(title,params,sourceText,paramsTreeElement);event.consume();};const viewParsedContextMenu=function(event){if(!paramsTreeElement.expanded){return;}
const contextMenu=new ContextMenu.ContextMenu(event);contextMenu.newSection().appendItem(ls`View parsed`,viewParsed.bind(this,event));contextMenu.show();}.bind(this);const viewParsedButton=this._createViewSourceToggle(true,viewParsed.bind(this));listItemElement.appendChild(viewParsedButton);listItemElement.addEventListener('contextmenu',viewParsedContextMenu);}
_appendParamsParsed(title,params,sourceText,paramsTreeElement){for(let i=0;i<params.length;++i){const paramNameValue=createDocumentFragment();if(params[i].name!==''){const name=this._formatParameter(params[i].name+': ','header-name',this._decodeRequestParameters);const value=this._formatParameter(params[i].value,'header-value source-code',this._decodeRequestParameters);paramNameValue.appendChild(name);paramNameValue.createChild('span','header-separator');paramNameValue.appendChild(value);}else{paramNameValue.appendChild(this._formatParameter(UIString.UIString('(empty)'),'empty-request-header',this._decodeRequestParameters));}
const paramTreeElement=new TreeOutline.TreeElement(paramNameValue);paramsTreeElement.appendChild(paramTreeElement);}
const listItemElement=paramsTreeElement.listItemElement;const viewSource=function(event){listItemElement.removeEventListener('contextmenu',viewSourceContextMenu);paramsTreeElement[_viewSourceSymbol]=true;this._refreshParams(title,params,sourceText,paramsTreeElement);event.consume();};const toggleURLDecoding=function(event){listItemElement.removeEventListener('contextmenu',viewSourceContextMenu);this._toggleURLDecoding(event);};const viewSourceContextMenu=function(event){if(!paramsTreeElement.expanded){return;}
const contextMenu=new ContextMenu.ContextMenu(event);const section=contextMenu.newSection();section.appendItem(ls`View source`,viewSource.bind(this,event));const viewURLEncodedText=this._decodeRequestParameters?ls`View URL encoded`:ls`View decoded`;section.appendItem(viewURLEncodedText,toggleURLDecoding.bind(this,event));contextMenu.show();}.bind(this);const viewSourceButton=this._createViewSourceToggle(false,viewSource.bind(this));listItemElement.appendChild(viewSourceButton);const toggleTitle=this._decodeRequestParameters?ls`view URL encoded`:ls`view decoded`;const toggleButton=this._createToggleButton(toggleTitle);toggleButton.addEventListener('click',toggleURLDecoding.bind(this),false);listItemElement.appendChild(toggleButton);listItemElement.addEventListener('contextmenu',viewSourceContextMenu);}
_refreshRequestJSONPayload(parsedObject,sourceText){const rootListItem=this._requestPayloadCategory;rootListItem.removeChildren();const rootListItemElement=rootListItem.listItemElement;rootListItemElement.removeChildren();rootListItemElement.createChild('div','selection fill');rootListItemElement.createTextChild(this._requestPayloadCategory.title);const shouldViewSource=rootListItem[_viewSourceSymbol];if(shouldViewSource){this._appendJSONPayloadSource(rootListItem,parsedObject,sourceText);}else{this._appendJSONPayloadParsed(rootListItem,parsedObject,sourceText);}}
_appendJSONPayloadSource(rootListItem,parsedObject,sourceText){const rootListItemElement=rootListItem.listItemElement;this._populateTreeElementWithSourceText(rootListItem,sourceText);const viewParsed=function(event){rootListItemElement.removeEventListener('contextmenu',viewParsedContextMenu);rootListItem[_viewSourceSymbol]=false;this._refreshRequestJSONPayload(parsedObject,sourceText);event.consume();};const viewParsedButton=this._createViewSourceToggle(true,viewParsed.bind(this));rootListItemElement.appendChild(viewParsedButton);const viewParsedContextMenu=function(event){if(!rootListItem.expanded){return;}
const contextMenu=new ContextMenu.ContextMenu(event);contextMenu.newSection().appendItem(ls`View parsed`,viewParsed.bind(this,event));contextMenu.show();}.bind(this);rootListItemElement.addEventListener('contextmenu',viewParsedContextMenu);}
_appendJSONPayloadParsed(rootListItem,parsedObject,sourceText){const object=(RemoteObject.RemoteObject.fromLocalObject(parsedObject));const section=new ObjectPropertiesSection.RootElement(object);section.title=object.description;section.expand();section.editable=false;rootListItem.childrenListElement.classList.add('source-code','object-properties-section');rootListItem.appendChild(section);const rootListItemElement=rootListItem.listItemElement;const viewSource=function(event){rootListItemElement.removeEventListener('contextmenu',viewSourceContextMenu);rootListItem[_viewSourceSymbol]=true;this._refreshRequestJSONPayload(parsedObject,sourceText);event.consume();};const viewSourceContextMenu=function(event){if(!rootListItem.expanded){return;}
const contextMenu=new ContextMenu.ContextMenu(event);contextMenu.newSection().appendItem(ls`View source`,viewSource.bind(this,event));contextMenu.show();}.bind(this);const viewSourceButton=this._createViewSourceToggle(false,viewSource.bind(this));rootListItemElement.appendChild(viewSourceButton);rootListItemElement.addEventListener('contextmenu',viewSourceContextMenu);}
_createViewSourceToggle(viewSource,handler){const viewSourceToggleTitle=viewSource?UIString.UIString('view parsed'):UIString.UIString('view source');const viewSourceToggleButton=this._createToggleButton(viewSourceToggleTitle);viewSourceToggleButton.addEventListener('click',handler,false);return viewSourceToggleButton;}
_toggleURLDecoding(event){this._decodeRequestParameters=!this._decodeRequestParameters;this._refreshQueryString();this._refreshFormData();event.consume();}
_refreshRequestHeaders(){const treeElement=this._requestHeadersCategory;const headers=this._request.requestHeaders().slice();headers.sort(function(a,b){return a.name.toLowerCase().compareTo(b.name.toLowerCase());});const headersText=this._request.requestHeadersText();if(this._showRequestHeadersText&&headersText){this._refreshHeadersText(UIString.UIString('Request Headers'),headers.length,headersText,treeElement);}else{this._refreshHeaders(UIString.UIString('Request Headers'),headers,treeElement,headersText===undefined);}
if(headersText){const toggleButton=this._createHeadersToggleButton(this._showRequestHeadersText);toggleButton.addEventListener('click',this._toggleRequestHeadersText.bind(this),false);treeElement.listItemElement.appendChild(toggleButton);}
this._refreshFormData();}
_refreshResponseHeaders(){const treeElement=this._responseHeadersCategory;const headers=this._request.sortedResponseHeaders.slice();const headersText=this._request.responseHeadersText;if(this._showResponseHeadersText){this._refreshHeadersText(UIString.UIString('Response Headers'),headers.length,headersText,treeElement);}else{const headersWithIssues=[];if(this._request.wasBlocked()){const headerWithIssues=BlockedReasonDetails.get(this._request.blockedReason());if(headerWithIssues){headersWithIssues.push(headerWithIssues);}}
this._refreshHeaders(UIString.UIString('Response Headers'),mergeHeadersWithIssues(headers,headersWithIssues),treeElement,false,this._request.blockedResponseCookies());}
if(headersText){const toggleButton=this._createHeadersToggleButton(this._showResponseHeadersText);toggleButton.addEventListener('click',this._toggleResponseHeadersText.bind(this),false);treeElement.listItemElement.appendChild(toggleButton);}
function mergeHeadersWithIssues(headers,headersWithIssues){let i=0,j=0;const result=[];while(i<headers.length||j<headersWithIssues.length){if(i<headers.length&&(j>=headersWithIssues.length||headers[i].name<headersWithIssues[j].name)){result.push({...headers[i++],headerNotSet:false});}else if(j<headersWithIssues.length&&(i>=headers.length||headers[i].name>headersWithIssues[j].name)){result.push({...headersWithIssues[j++],headerNotSet:true});}else if(i<headers.length&&j<headersWithIssues.length&&headers[i].name===headersWithIssues[j].name){result.push({...headersWithIssues[j++],...headers[i++],headerNotSet:false});}}
return result;}}
_refreshHTTPInformation(){const requestMethodElement=this._requestMethodItem;requestMethodElement.hidden=!this._request.statusCode;const statusCodeElement=this._statusCodeItem;statusCodeElement.hidden=!this._request.statusCode;if(this._request.statusCode){const statusCodeFragment=createDocumentFragment();statusCodeFragment.createChild('div','header-name').textContent=ls`Status Code`+': ';statusCodeFragment.createChild('span','header-separator');const statusCodeImage=statusCodeFragment.createChild('span','resource-status-image','dt-icon-label');statusCodeImage.title=this._request.statusCode+' '+this._request.statusText;if(this._request.statusCode<300||this._request.statusCode===304){statusCodeImage.type='smallicon-green-ball';}else if(this._request.statusCode<400){statusCodeImage.type='smallicon-orange-ball';}else{statusCodeImage.type='smallicon-red-ball';}
requestMethodElement.title=this._formatHeader(ls`Request Method`,this._request.requestMethod);const statusTextElement=statusCodeFragment.createChild('div','header-value source-code');let statusText=this._request.statusCode+' '+this._request.statusText;if(this._request.cachedInMemory()){statusText+=' '+ls`(from memory cache)`;statusTextElement.classList.add('status-from-cache');}else if(this._request.fetchedViaServiceWorker){statusText+=' '+ls`(from ServiceWorker)`;statusTextElement.classList.add('status-from-cache');}else if(this._request.redirectSource()&&this._request.redirectSource().signedExchangeInfo()&&!this._request.redirectSource().signedExchangeInfo().errors){statusText+=' '+ls`(from signed-exchange)`;statusTextElement.classList.add('status-from-cache');}else if(this._request.fromPrefetchCache()){statusText+=' '+ls`(from prefetch cache)`;statusTextElement.classList.add('status-from-cache');}else if(this._request.cached()){statusText+=' '+ls`(from disk cache)`;statusTextElement.classList.add('status-from-cache');}
statusTextElement.textContent=statusText;statusCodeElement.title=statusCodeFragment;}}
_refreshHeadersTitle(title,headersTreeElement,headersLength){headersTreeElement.listItemElement.removeChildren();headersTreeElement.listItemElement.createChild('div','selection fill');headersTreeElement.listItemElement.createTextChild(title);const headerCount=UIString.UIString('\xA0(%d)',headersLength);headersTreeElement.listItemElement.createChild('span','header-count').textContent=headerCount;}
_refreshHeaders(title,headers,headersTreeElement,provisionalHeaders,blockedResponseCookies){headersTreeElement.removeChildren();const length=headers.length;this._refreshHeadersTitle(title,headersTreeElement,length);if(provisionalHeaders){let cautionText;let cautionTitle='';if(this._request.cachedInMemory()||this._request.cached()){cautionText=ls`Provisional headers are shown. Disable cache to see full headers.`;cautionTitle=ls`Only provisional headers are available because this request was not sent over the network and instead was served from a local cache, which doesn't store the original request headers. Disable cache to see full request headers.`;}else{cautionText=ls`Provisional headers are shown`;}
const cautionElement=createElement('div');cautionElement.title=cautionTitle;cautionElement.createChild('span','','dt-icon-label').type='smallicon-warning';cautionElement.createChild('div','caution').textContent=cautionText;const cautionTreeElement=new TreeOutline.TreeElement(cautionElement);headersTreeElement.appendChild(cautionTreeElement);}
const blockedCookieLineToReasons=new Map();if(blockedResponseCookies){blockedResponseCookies.forEach(blockedCookie=>{blockedCookieLineToReasons.set(blockedCookie.cookieLine,blockedCookie.blockedReasons);});}
headersTreeElement.hidden=!length&&!provisionalHeaders;for(let i=0;i<length;++i){const headerTreeElement=new TreeOutline.TreeElement(this._formatHeaderObject(headers[i]));headerTreeElement[_headerNameSymbol]=headers[i].name;if(headers[i].name.toLowerCase()==='set-cookie'){const matchingBlockedReasons=blockedCookieLineToReasons.get(headers[i].value);if(matchingBlockedReasons){const icon=Icon.Icon.create('smallicon-warning','');headerTreeElement.listItemElement.appendChild(icon);let titleText='';for(const blockedReason of matchingBlockedReasons){if(titleText){titleText+='\n';}
titleText+=NetworkRequest.setCookieBlockedReasonToUiString(blockedReason);}
icon.title=titleText;}}
headersTreeElement.appendChild(headerTreeElement);}}
_refreshHeadersText(title,count,headersText,headersTreeElement){this._populateTreeElementWithSourceText(headersTreeElement,headersText);this._refreshHeadersTitle(title,headersTreeElement,count);}
_refreshRemoteAddress(){const remoteAddress=this._request.remoteAddress();const treeElement=this._remoteAddressItem;treeElement.hidden=!remoteAddress;if(remoteAddress){treeElement.title=this._formatHeader(UIString.UIString('Remote Address'),remoteAddress);}}
_refreshReferrerPolicy(){const referrerPolicy=this._request.referrerPolicy();const treeElement=this._referrerPolicyItem;treeElement.hidden=!referrerPolicy;if(referrerPolicy){treeElement.title=this._formatHeader(UIString.UIString('Referrer Policy'),referrerPolicy);}}
_toggleRequestHeadersText(event){this._showRequestHeadersText=!this._showRequestHeadersText;this._refreshRequestHeaders();event.consume();}
_toggleResponseHeadersText(event){this._showResponseHeadersText=!this._showResponseHeadersText;this._refreshResponseHeaders();event.consume();}
_createToggleButton(title){const button=createElementWithClass('span','header-toggle');button.textContent=title;return button;}
_createHeadersToggleButton(isHeadersTextShown){const toggleTitle=isHeadersTextShown?UIString.UIString('view parsed'):UIString.UIString('view source');return this._createToggleButton(toggleTitle);}
_clearHighlight(){if(this._highlightedElement){this._highlightedElement.listItemElement.classList.remove('header-highlight');}
this._highlightedElement=null;}
_revealAndHighlight(category,name){this._clearHighlight();for(const element of category.children()){if(element[_headerNameSymbol]!==name){continue;}
this._highlightedElement=element;element.reveal();element.listItemElement.classList.add('header-highlight');return;}}
revealRequestHeader(header){this._revealAndHighlight(this._requestHeadersCategory,header);}
revealResponseHeader(header){this._revealAndHighlight(this._responseHeadersCategory,header);}}
const _headerNameSymbol=Symbol('HeaderName');const _viewSourceSymbol=Symbol('ViewSource');class Category extends TreeOutline.TreeElement{constructor(root,name,title){super(title||'',true);this.toggleOnClick=true;this.hidden=true;this._expandedSetting=Settings.Settings.instance().createSetting('request-info-'+name+'-category-expanded',true);this.expanded=this._expandedSetting.get();root.appendChild(this);}
createLeaf(){const leaf=new TreeOutline.TreeElement();this.appendChild(leaf);return leaf;}
onexpand(){this._expandedSetting.set(true);}
oncollapse(){this._expandedSetting.set(false);}}
const BlockedReasonDetails=new Map([[Protocol.Network.BlockedReason.CoepFrameResourceNeedsCoepHeader,{name:'cross-origin-embedder-policy',value:null,details:{explanation:ls`To embed this frame in your document, the response needs to enable the cross-origin embedder policy by specifying the following response header:`,examples:[{codeSnippet:'Cross-Origin-Embedder-Policy: require-corp'}],link:{url:'https://web.dev/coop-coep/'}}}],[Protocol.Network.BlockedReason.CorpNotSameOriginAfterDefaultedToSameOriginByCoep,{name:'cross-origin-resource-policy',value:null,details:{explanation:ls`To use this resource from a different origin, the server needs to specify a cross-origin resource policy in the response headers:`,examples:[{codeSnippet:'Cross-Origin-Resource-Policy: same-site',comment:ls`Choose this option if the resource and the document are served from the same site.`},{codeSnippet:'Cross-Origin-Resource-Policy: cross-origin',comment:ls`Only choose this option if an arbitrary website including this resource does not impose a security risk.`},],link:{url:'https://web.dev/coop-coep/'}}}],[Protocol.Network.BlockedReason.CoopSandboxedIframeCannotNavigateToCoopPage,{name:'cross-origin-opener-policy',value:null,headerValueIncorrect:false,details:{explanation:ls`This document was blocked from loading in an iframe with a sandbox attribute because this document specified a cross-origin opener policy.`,examples:[],link:{url:'https://web.dev/coop-coep/'}}}],[Protocol.Network.BlockedReason.CorpNotSameSite,{name:'cross-origin-resource-policy',value:null,headerValueIncorrect:true,details:{explanation:ls`To use this resource from a different site, the server may relax the cross-origin resource policy response header:`,examples:[{codeSnippet:'Cross-Origin-Resource-Policy: cross-origin',comment:ls`Only choose this option if an arbitrary website including this resource does not impose a security risk.`},]}}],[Protocol.Network.BlockedReason.CorpNotSameOrigin,{name:'cross-origin-resource-policy',value:null,headerValueIncorrect:true,details:{explanation:ls`To use this resource from a different origin, the server may relax the cross-origin resource policy response header:`,examples:[{codeSnippet:'Cross-Origin-Resource-Policy: same-site',comment:ls`Choose this option if the resource and the document are served from the same site.`},{codeSnippet:'Cross-Origin-Resource-Policy: cross-origin',comment:ls`Only choose this option if an arbitrary website including this resource does not impose a security risk.`},]}}],]);var RequestHeadersView$1=Object.freeze({__proto__:null,RequestHeadersView:RequestHeadersView,_headerNameSymbol:_headerNameSymbol,_viewSourceSymbol:_viewSourceSymbol,Category:Category});class RequestInitiatorView extends Widget.VBox{constructor(request){super();this.registerRequiredCSS('network/requestInitiatorView.css');this.element.classList.add('request-initiator-view');this._linkifier=new Linkifier.Linkifier();this._request=request;this._emptyWidget=new EmptyWidget.EmptyWidget(UIString.UIString('This request has no initiator data.'));this._emptyWidget.show(this.element);this._hasShown=false;}
static createStackTracePreview(request,linkifier,focusableLink,callback){const initiator=request.initiator();if(!initiator||!initiator.stack){return null;}
const networkManager=NetworkManager.NetworkManager.forRequest(request);const target=networkManager?networkManager.target():null;const stackTrace=JSPresentationUtils.buildStackTracePreviewContents(target,linkifier,{stackTrace:initiator.stack,contentUpdated:callback,tabStops:focusableLink});return stackTrace;}
_appendExpandableSection(sectionContent,title,expanded){const section=createElementWithClass('div','request-initiator-view-section');const icon=Icon.Icon.create('smallicon-triangle-right');const clickableElement=section.createChild('div','request-initiator-view-section-title');clickableElement.appendChild(icon);clickableElement.createTextChild(title);clickableElement.tabIndex=0;sectionContent.classList.add('hidden','request-initiator-view-section-content');section.appendChild(sectionContent);const expand=expanded=>{icon.setIconType(expanded?'smallicon-triangle-down':'smallicon-triangle-right');sectionContent.classList.toggle('hidden',!expanded);};self.onInvokeElement(clickableElement,event=>{expand(sectionContent.classList.contains('hidden'));event.consume();});expand(expanded);this.element.appendChild(section);}
_buildRequestChainTree(initiatorGraph){const root=new TreeOutline.TreeOutlineInShadow();const initiators=initiatorGraph.initiators;let parent=root;for(const request of Array.from(initiators).reverse()){const treeElement=new TreeOutline.TreeElement(request.url());parent.appendChild(treeElement);if(parent!==root){parent.expand();}
parent=treeElement;}
parent.select();parent.titleElement.style.fontWeight='bold';const initiated=initiatorGraph.initiated;this._depthFirstSearchTreeBuilder(initiated,(parent),this._request);return root;}
_depthFirstSearchTreeBuilder(initiated,parentElement,parentRequest){const visited=new Set();visited.add(this._request);for(const request of initiated.keys()){if(initiated.get(request)===parentRequest){const treeElement=new TreeOutline.TreeElement(request.url());parentElement.appendChild(treeElement);parentElement.expand();if(!visited.has(request)){visited.add(request);this._depthFirstSearchTreeBuilder(initiated,treeElement,request);}}}}
wasShown(){if(this._hasShown){return;}
let initiatorDataPresent=false;const stackTracePreview=RequestInitiatorView.createStackTracePreview(this._request,this._linkifier,true);if(stackTracePreview){initiatorDataPresent=true;this._appendExpandableSection(stackTracePreview.element,ls`Request call stack`,true);}
const initiatorGraph=self.SDK.networkLog.initiatorGraphForRequest(this._request);if(initiatorGraph.initiators.size>1||initiatorGraph.initiated.size>1){initiatorDataPresent=true;this._appendExpandableSection(this._buildRequestChainTree(initiatorGraph).element,ls`Request initiator chain`,true);}
if(initiatorDataPresent){this._emptyWidget.hideWidget();}
this._hasShown=true;}}
var RequestInitiatorView$1=Object.freeze({__proto__:null,RequestInitiatorView:RequestInitiatorView});class RequestHTMLView extends Widget.VBox{constructor(dataURL){super(true);this.registerRequiredCSS('network/requestHTMLView.css');this._dataURL=encodeURI(dataURL).replace(/#/g,'%23');this.contentElement.classList.add('html','request-view');}
wasShown(){this._createIFrame();}
willHide(){this.contentElement.removeChildren();}
_createIFrame(){this.contentElement.removeChildren();const iframe=createElement('iframe');iframe.className='html-preview-frame';iframe.setAttribute('sandbox','');iframe.setAttribute('src',this._dataURL);iframe.setAttribute('tabIndex',-1);ARIAUtils.markAsPresentation(iframe);this.contentElement.appendChild(iframe);}}
var RequestHTMLView$1=Object.freeze({__proto__:null,RequestHTMLView:RequestHTMLView});class RequestResponseView extends Widget.VBox{constructor(request){super();this.element.classList.add('request-view');this.request=request;this._contentViewPromise=null;}
static _hasTextContent(request,contentData){const mimeType=request.mimeType||'';let resourceType=ResourceType.ResourceType.fromMimeType(mimeType);if(resourceType===ResourceType.resourceTypes.Other){resourceType=request.contentType();}
if(resourceType===ResourceType.resourceTypes.Image){return mimeType.startsWith('image/svg');}
if(resourceType.isTextType()){return true;}
if(contentData.error){return false;}
if(resourceType===ResourceType.resourceTypes.Other){return!!contentData.content&&!contentData.encoded;}
return false;}
static async sourceViewForRequest(request){let sourceView=request[_sourceViewSymbol];if(sourceView!==undefined){return sourceView;}
const contentData=await request.contentData();if(!RequestResponseView._hasTextContent(request,contentData)){request[_sourceViewSymbol]=null;return null;}
const highlighterType=request.resourceType().canonicalMimeType()||request.mimeType;sourceView=ResourceSourceFrame.ResourceSourceFrame.createSearchableView(request,highlighterType);request[_sourceViewSymbol]=sourceView;return sourceView;}
wasShown(){this._doShowPreview();}
_doShowPreview(){if(!this._contentViewPromise){this._contentViewPromise=this.showPreview();}
return this._contentViewPromise;}
async showPreview(){const responseView=await this.createPreview();responseView.show(this.element);return responseView;}
async createPreview(){const contentData=await this.request.contentData();const sourceView=await RequestResponseView.sourceViewForRequest(this.request);if((!contentData.content||!sourceView)&&!contentData.error){return new EmptyWidget.EmptyWidget(UIString.UIString('This request has no response data available.'));}
if(contentData.content&&sourceView){return sourceView;}
return new EmptyWidget.EmptyWidget(UIString.UIString('Failed to load response data'));}
async revealLine(line){const view=await this._doShowPreview();if(view instanceof ResourceSourceFrame.SearchableContainer){view.revealPosition(line);}}}
const _sourceViewSymbol=Symbol('RequestResponseSourceView');var RequestResponseView$1=Object.freeze({__proto__:null,RequestResponseView:RequestResponseView,_sourceViewSymbol:_sourceViewSymbol});class SignedExchangeInfoView extends Widget.VBox{constructor(request){super();const signedExchangeInfo=request.signedExchangeInfo();console.assert(signedExchangeInfo);this.registerRequiredCSS('network/signedExchangeInfoView.css');this.element.classList.add('signed-exchange-info-view');const root=new TreeOutline.TreeOutlineInShadow();root.registerRequiredCSS('network/signedExchangeInfoTree.css');root.element.classList.add('signed-exchange-info-tree');root.setFocusable(false);root.makeDense();root.expandTreeElementsWhenArrowing=true;this.element.appendChild(root.element);const errorFieldSetMap=new Map();if(signedExchangeInfo.errors&&signedExchangeInfo.errors.length){const errorMessagesCategory=new Category$1(root,UIString.UIString('Errors'));for(const error of signedExchangeInfo.errors){const fragment=createDocumentFragment();fragment.appendChild(Icon.Icon.create('smallicon-error','prompt-icon'));fragment.createChild('div','error-log').textContent=error.message;errorMessagesCategory.createLeaf(fragment);if(error.errorField){let errorFieldSet=errorFieldSetMap.get(error.signatureIndex);if(!errorFieldSet){errorFieldSet=new Set();errorFieldSetMap.set(error.signatureIndex,errorFieldSet);}
errorFieldSet.add(error.errorField);}}}
const titleElement=createDocumentFragment();titleElement.createChild('div','header-name').textContent=UIString.UIString('Signed HTTP exchange');const learnMoreNode=XLink.XLink.create('https://github.com/WICG/webpackage',UIString.UIString('Learn\xa0more'),'header-toggle');titleElement.appendChild(learnMoreNode);const headerCategory=new Category$1(root,titleElement);if(signedExchangeInfo.header){const header=signedExchangeInfo.header;const redirectDestination=request.redirectDestination();const requestURLElement=this._formatHeader(UIString.UIString('Request URL'),header.requestUrl);if(redirectDestination){const viewRequestLink=Linkifier.Linkifier.linkifyRevealable(redirectDestination,'View request');viewRequestLink.classList.add('header-toggle');requestURLElement.appendChild(viewRequestLink);}
headerCategory.createLeaf(requestURLElement);headerCategory.createLeaf(this._formatHeader(UIString.UIString('Response code'),header.responseCode+''));headerCategory.createLeaf(this._formatHeader(UIString.UIString('Header integrity hash'),header.headerIntegrity));this._responseHeadersItem=headerCategory.createLeaf(this._formatHeader(UIString.UIString('Response headers'),''));const responseHeaders=header.responseHeaders;for(const name in responseHeaders){const headerTreeElement=new TreeOutline.TreeElement(this._formatHeader(name,responseHeaders[name]));headerTreeElement.selectable=false;this._responseHeadersItem.appendChild(headerTreeElement);}
this._responseHeadersItem.expand();for(let i=0;i<header.signatures.length;++i){const errorFieldSet=errorFieldSetMap.get(i)||new Set();const signature=header.signatures[i];const signatureCategory=new Category$1(root,UIString.UIString('Signature'));signatureCategory.createLeaf(this._formatHeader(UIString.UIString('Label'),signature.label));signatureCategory.createLeaf(this._formatHeaderForHexData(UIString.UIString('Signature'),signature.signature,errorFieldSet.has(Protocol.Network.SignedExchangeErrorField.SignatureSig)));if(signature.certUrl){const certURLElement=this._formatHeader(UIString.UIString('Certificate URL'),signature.certUrl,errorFieldSet.has(Protocol.Network.SignedExchangeErrorField.SignatureCertUrl));if(signature.certificates){const viewCertLink=certURLElement.createChild('span','devtools-link header-toggle');viewCertLink.textContent=UIString.UIString('View certificate');viewCertLink.addEventListener('click',InspectorFrontendHost.InspectorFrontendHostInstance.showCertificateViewer.bind(null,signature.certificates),false);}
signatureCategory.createLeaf(certURLElement);}
signatureCategory.createLeaf(this._formatHeader(UIString.UIString('Integrity'),signature.integrity,errorFieldSet.has(Protocol.Network.SignedExchangeErrorField.SignatureIntegrity)));if(signature.certSha256){signatureCategory.createLeaf(this._formatHeaderForHexData(UIString.UIString('Certificate SHA256'),signature.certSha256,errorFieldSet.has(Protocol.Network.SignedExchangeErrorField.SignatureCertSha256)));}
signatureCategory.createLeaf(this._formatHeader(UIString.UIString('Validity URL'),signature.validityUrl,errorFieldSet.has(Protocol.Network.SignedExchangeErrorField.SignatureValidityUrl)));signatureCategory.createLeaf().title=this._formatHeader(UIString.UIString('Date'),new Date(1000*signature.date).toUTCString(),errorFieldSet.has(Protocol.Network.SignedExchangeErrorField.SignatureTimestamps));signatureCategory.createLeaf().title=this._formatHeader(UIString.UIString('Expires'),new Date(1000*signature.expires).toUTCString(),errorFieldSet.has(Protocol.Network.SignedExchangeErrorField.SignatureTimestamps));}}
if(signedExchangeInfo.securityDetails){const securityDetails=signedExchangeInfo.securityDetails;const securityCategory=new Category$1(root,UIString.UIString('Certificate'));securityCategory.createLeaf(this._formatHeader(UIString.UIString('Subject'),securityDetails.subjectName));securityCategory.createLeaf(this._formatHeader(UIString.UIString('Valid from'),new Date(1000*securityDetails.validFrom).toUTCString()));securityCategory.createLeaf(this._formatHeader(UIString.UIString('Valid until'),new Date(1000*securityDetails.validTo).toUTCString()));securityCategory.createLeaf(this._formatHeader(UIString.UIString('Issuer'),securityDetails.issuer));}}
_formatHeader(name,value,highlighted){const fragment=createDocumentFragment();const nameElement=fragment.createChild('div','header-name');nameElement.textContent=name+': ';fragment.createChild('span','header-separator');const valueElement=fragment.createChild('div','header-value source-code');valueElement.textContent=value;if(highlighted){nameElement.classList.add('error-field');valueElement.classList.add('error-field');}
return fragment;}
_formatHeaderForHexData(name,value,highlighted){const fragment=createDocumentFragment();const nameElement=fragment.createChild('div','header-name');nameElement.textContent=name+': ';fragment.createChild('span','header-separator');const valueElement=fragment.createChild('div','header-value source-code hex-data');valueElement.textContent=value.replace(/(.{2})/g,'$1 ');if(highlighted){nameElement.classList.add('error-field');valueElement.classList.add('error-field');}
return fragment;}}
class Category$1 extends TreeOutline.TreeElement{constructor(root,title){super(title,true);this.selectable=false;this.toggleOnClick=true;this.expanded=true;root.appendChild(this);}
createLeaf(title){const leaf=new TreeOutline.TreeElement(title);leaf.selectable=false;this.appendChild(leaf);return leaf;}}
var SignedExchangeInfoView$1=Object.freeze({__proto__:null,SignedExchangeInfoView:SignedExchangeInfoView,Category:Category$1});class RequestPreviewView extends RequestResponseView{constructor(request){super(request);}
async showPreview(){const view=await super.showPreview();if(!(view instanceof View.SimpleView)){return view;}
const toolbar=new Toolbar.Toolbar('network-item-preview-toolbar',this.element);view.toolbarItems().then(items=>{items.map(item=>toolbar.appendToolbarItem(item));});return view;}
async _htmlPreview(){const contentData=await this.request.contentData();if(contentData.error){return new EmptyWidget.EmptyWidget(UIString.UIString('Failed to load response data'));}
const whitelist=new Set(['text/html','text/plain','application/xhtml+xml']);if(!whitelist.has(this.request.mimeType)){return null;}
const content=contentData.encoded?window.atob((contentData.content)):(contentData.content);const jsonView=await JSONView.JSONView.createView(content);if(jsonView){return jsonView;}
const dataURL=ContentProvider.contentAsDataURL(contentData.content,this.request.mimeType,contentData.encoded,this.request.charset());return dataURL?new RequestHTMLView(dataURL):null;}
async createPreview(){if(this.request.signedExchangeInfo()){return new SignedExchangeInfoView(this.request);}
const htmlErrorPreview=await this._htmlPreview();if(htmlErrorPreview){return htmlErrorPreview;}
const provided=await PreviewFactory.PreviewFactory.createPreview(this.request,this.request.mimeType);if(provided){return provided;}
return new EmptyWidget.EmptyWidget(UIString.UIString('Preview not available'));}}
var RequestPreviewView$1=Object.freeze({__proto__:null,RequestPreviewView:RequestPreviewView});class RequestTimingView extends Widget.VBox{constructor(request,calculator){super();this.element.classList.add('resource-timing-view');this._request=request;this._calculator=calculator;}
static _timeRangeTitle(name){switch(name){case RequestTimeRangeNames.Push:return UIString.UIString('Receiving Push');case RequestTimeRangeNames.Queueing:return UIString.UIString('Queueing');case RequestTimeRangeNames.Blocking:return UIString.UIString('Stalled');case RequestTimeRangeNames.Connecting:return UIString.UIString('Initial connection');case RequestTimeRangeNames.DNS:return UIString.UIString('DNS Lookup');case RequestTimeRangeNames.Proxy:return UIString.UIString('Proxy negotiation');case RequestTimeRangeNames.ReceivingPush:return UIString.UIString('Reading Push');case RequestTimeRangeNames.Receiving:return UIString.UIString('Content Download');case RequestTimeRangeNames.Sending:return UIString.UIString('Request sent');case RequestTimeRangeNames.ServiceWorker:return UIString.UIString('Request to ServiceWorker');case RequestTimeRangeNames.ServiceWorkerPreparation:return UIString.UIString('ServiceWorker Preparation');case RequestTimeRangeNames.SSL:return UIString.UIString('SSL');case RequestTimeRangeNames.Total:return UIString.UIString('Total');case RequestTimeRangeNames.Waiting:return UIString.UIString('Waiting (TTFB)');default:return UIString.UIString(name);}}
static calculateRequestTimeRanges(request,navigationStart){const result=[];function addRange(name,start,end){if(start<Number.MAX_VALUE&&start<=end){result.push({name:name,start:start,end:end});}}
function firstPositive(numbers){for(let i=0;i<numbers.length;++i){if(numbers[i]>0){return numbers[i];}}
return undefined;}
function addOffsetRange(name,start,end){if(start>=0&&end>=0){addRange(name,startTime+(start/1000),startTime+(end/1000));}}
const timing=request.timing;if(!timing){const start=request.issueTime()!==-1?request.issueTime():request.startTime!==-1?request.startTime:0;const middle=(request.responseReceivedTime===-1)?Number.MAX_VALUE:request.responseReceivedTime;const end=(request.endTime===-1)?Number.MAX_VALUE:request.endTime;addRange(RequestTimeRangeNames.Total,start,end);addRange(RequestTimeRangeNames.Blocking,start,middle);addRange(RequestTimeRangeNames.Receiving,middle,end);return result;}
const issueTime=request.issueTime();const startTime=timing.requestTime;const endTime=firstPositive([request.endTime,request.responseReceivedTime])||startTime;addRange(RequestTimeRangeNames.Total,issueTime<startTime?issueTime:startTime,endTime);if(timing.pushStart){const pushEnd=timing.pushEnd||endTime;if(pushEnd>navigationStart){addRange(RequestTimeRangeNames.Push,Math.max(timing.pushStart,navigationStart),pushEnd);}}
if(issueTime<startTime){addRange(RequestTimeRangeNames.Queueing,issueTime,startTime);}
const responseReceived=(request.responseReceivedTime-startTime)*1000;if(request.fetchedViaServiceWorker){addOffsetRange(RequestTimeRangeNames.Blocking,0,timing.workerStart);addOffsetRange(RequestTimeRangeNames.ServiceWorkerPreparation,timing.workerStart,timing.workerReady);addOffsetRange(RequestTimeRangeNames.ServiceWorker,timing.workerReady,timing.sendEnd);addOffsetRange(RequestTimeRangeNames.Waiting,timing.sendEnd,responseReceived);}else if(!timing.pushStart){const blockingEnd=firstPositive([timing.dnsStart,timing.connectStart,timing.sendStart,responseReceived])||0;addOffsetRange(RequestTimeRangeNames.Blocking,0,blockingEnd);addOffsetRange(RequestTimeRangeNames.Proxy,timing.proxyStart,timing.proxyEnd);addOffsetRange(RequestTimeRangeNames.DNS,timing.dnsStart,timing.dnsEnd);addOffsetRange(RequestTimeRangeNames.Connecting,timing.connectStart,timing.connectEnd);addOffsetRange(RequestTimeRangeNames.SSL,timing.sslStart,timing.sslEnd);addOffsetRange(RequestTimeRangeNames.Sending,timing.sendStart,timing.sendEnd);addOffsetRange(RequestTimeRangeNames.Waiting,Math.max(timing.sendEnd,timing.connectEnd,timing.dnsEnd,timing.proxyEnd,blockingEnd),responseReceived);}
if(request.endTime!==-1){addRange(timing.pushStart?RequestTimeRangeNames.ReceivingPush:RequestTimeRangeNames.Receiving,request.responseReceivedTime,endTime);}
return result;}
static createTimingTable(request,calculator){const tableElement=createElementWithClass('table','network-timing-table');Utils.appendStyle(tableElement,'network/networkTimingTable.css');const colgroup=tableElement.createChild('colgroup');colgroup.createChild('col','labels');colgroup.createChild('col','bars');colgroup.createChild('col','duration');const timeRanges=RequestTimingView.calculateRequestTimeRanges(request,calculator.minimumBoundary());const startTime=timeRanges.map(r=>r.start).reduce((a,b)=>Math.min(a,b));const endTime=timeRanges.map(r=>r.end).reduce((a,b)=>Math.max(a,b));const scale=100/(endTime-startTime);let connectionHeader;let dataHeader;let queueingHeader;let totalDuration=0;const startTimeHeader=tableElement.createChild('thead','network-timing-start');const tableHeaderRow=startTimeHeader.createChild('tr');const activityHeaderCell=tableHeaderRow.createChild('th');activityHeaderCell.createChild('span','network-timing-hidden-header').textContent=ls`Label`;activityHeaderCell.scope='col';const waterfallHeaderCell=tableHeaderRow.createChild('th');waterfallHeaderCell.createChild('span','network-timing-hidden-header').textContent=ls`Waterfall`;waterfallHeaderCell.scope='col';const durationHeaderCell=tableHeaderRow.createChild('th');durationHeaderCell.createChild('span','network-timing-hidden-header').textContent=ls`Duration`;durationHeaderCell.scope='col';const queuedCell=startTimeHeader.createChild('tr').createChild('td');const startedCell=startTimeHeader.createChild('tr').createChild('td');queuedCell.colSpan=startedCell.colSpan=3;queuedCell.createTextChild(UIString.UIString('Queued at %s',calculator.formatValue(request.issueTime(),2)));startedCell.createTextChild(UIString.UIString('Started at %s',calculator.formatValue(request.startTime,2)));let right;for(let i=0;i<timeRanges.length;++i){const range=timeRanges[i];const rangeName=range.name;if(rangeName===RequestTimeRangeNames.Total){totalDuration=range.end-range.start;continue;}
if(rangeName===RequestTimeRangeNames.Push){createHeader(UIString.UIString('Server Push'));}else if(rangeName===RequestTimeRangeNames.Queueing){if(!queueingHeader){queueingHeader=createHeader(ls`Resource Scheduling`);}}else if(ConnectionSetupRangeNames.has(rangeName)){if(!connectionHeader){connectionHeader=createHeader(UIString.UIString('Connection Start'));}}else{if(!dataHeader){dataHeader=createHeader(UIString.UIString('Request/Response'));}}
const left=(scale*(range.start-startTime));right=(scale*(endTime-range.end));const duration=range.end-range.start;const tr=tableElement.createChild('tr');tr.createChild('td').createTextChild(RequestTimingView._timeRangeTitle(rangeName));const row=tr.createChild('td').createChild('div','network-timing-row');const bar=row.createChild('span','network-timing-bar '+rangeName);bar.style.left=left+'%';bar.style.right=right+'%';bar.textContent='\u200B';ARIAUtils.setAccessibleName(row,ls`Started at ${calculator.formatValue(range.start, 2)}`);const label=tr.createChild('td').createChild('div','network-timing-bar-title');label.textContent=Number.secondsToString(duration,true);}
if(!request.finished){const cell=tableElement.createChild('tr').createChild('td','caution');cell.colSpan=3;cell.createTextChild(UIString.UIString('CAUTION: request is not finished yet!'));}
const footer=tableElement.createChild('tr','network-timing-footer');const note=footer.createChild('td');note.colSpan=1;note.appendChild(UIUtils.createDocumentationLink('network-performance/reference#timing-explanation',UIString.UIString('Explanation')));footer.createChild('td');footer.createChild('td').createTextChild(Number.secondsToString(totalDuration,true));const serverTimings=request.serverTimings;const lastTimingRightEdge=right===undefined?100:right;const breakElement=tableElement.createChild('tr','network-timing-table-header').createChild('td');breakElement.colSpan=3;breakElement.createChild('hr','break');const serverHeader=tableElement.createChild('tr','network-timing-table-header');serverHeader.createChild('td').createTextChild(UIString.UIString('Server Timing'));serverHeader.createChild('td');serverHeader.createChild('td').createTextChild(UIString.UIString('TIME'));if(!serverTimings){const informationRow=tableElement.createChild('tr');const information=informationRow.createChild('td');information.colSpan=3;const link=XLink.XLink.create('https://web.dev/custom-metrics/#server-timing-api',ls`the Server Timing API`);information.appendChild(UIUtils.formatLocalized('During development, you can use %s to add insights into the server-side timing of this request.',[link]));return tableElement;}
serverTimings.filter(item=>item.metric.toLowerCase()!=='total').forEach(item=>addTiming(item,lastTimingRightEdge));serverTimings.filter(item=>item.metric.toLowerCase()==='total').forEach(item=>addTiming(item,lastTimingRightEdge));return tableElement;function addTiming(serverTiming,right){const colorGenerator=new Color.Generator({min:0,max:360,count:36},{min:50,max:80},80);const isTotal=serverTiming.metric.toLowerCase()==='total';const tr=tableElement.createChild('tr',isTotal?'network-timing-footer':'');const metric=tr.createChild('td','network-timing-metric');const description=serverTiming.description||serverTiming.metric;metric.createTextChild(description);metric.title=description;const row=tr.createChild('td').createChild('div','network-timing-row');if(serverTiming.value===null){return;}
const left=scale*(endTime-startTime-(serverTiming.value/1000));if(left>=0){const bar=row.createChild('span','network-timing-bar server-timing');bar.style.left=left+'%';bar.style.right=right+'%';bar.textContent='\u200B';if(!isTotal){bar.style.backgroundColor=colorGenerator.colorForID(serverTiming.metric);}}
const label=tr.createChild('td').createChild('div','network-timing-bar-title');label.textContent=Number.millisToString(serverTiming.value,true);}
function createHeader(title){const dataHeader=tableElement.createChild('tr','network-timing-table-header');const headerCell=dataHeader.createChild('td');headerCell.createTextChild(title);ARIAUtils.markAsHeading(headerCell,2);dataHeader.createChild('td').createTextChild('');dataHeader.createChild('td').createTextChild(ls`DURATION`);return dataHeader;}}
wasShown(){this._request.addEventListener(NetworkRequest.Events.TimingChanged,this._refresh,this);this._request.addEventListener(NetworkRequest.Events.FinishedLoading,this._refresh,this);this._calculator.addEventListener(Events.BoundariesChanged,this._refresh,this);this._refresh();}
willHide(){this._request.removeEventListener(NetworkRequest.Events.TimingChanged,this._refresh,this);this._request.removeEventListener(NetworkRequest.Events.FinishedLoading,this._refresh,this);this._calculator.removeEventListener(Events.BoundariesChanged,this._refresh,this);}
_refresh(){if(this._tableElement){this._tableElement.remove();}
this._tableElement=RequestTimingView.createTimingTable(this._request,this._calculator);this._tableElement.classList.add('resource-timing-table');this.element.appendChild(this._tableElement);}}
const RequestTimeRangeNames={Push:'push',Queueing:'queueing',Blocking:'blocking',Connecting:'connecting',DNS:'dns',Proxy:'proxy',Receiving:'receiving',ReceivingPush:'receiving-push',Sending:'sending',ServiceWorker:'serviceworker',ServiceWorkerPreparation:'serviceworker-preparation',SSL:'ssl',Total:'total',Waiting:'waiting'};const ConnectionSetupRangeNames=new Set([RequestTimeRangeNames.Queueing,RequestTimeRangeNames.Blocking,RequestTimeRangeNames.Connecting,RequestTimeRangeNames.DNS,RequestTimeRangeNames.Proxy,RequestTimeRangeNames.SSL]);let RequestTimeRange;var RequestTimingView$1=Object.freeze({__proto__:null,RequestTimingView:RequestTimingView,RequestTimeRangeNames:RequestTimeRangeNames,ConnectionSetupRangeNames:ConnectionSetupRangeNames,RequestTimeRange:RequestTimeRange});class ResourceWebSocketFrameView extends Widget.VBox{constructor(request){super();this.registerRequiredCSS('network/webSocketFrameView.css');this.element.classList.add('websocket-frame-view');this._request=request;this._splitWidget=new SplitWidget.SplitWidget(false,true,'resourceWebSocketFrameSplitViewState');this._splitWidget.show(this.element);const columns=([{id:'data',title:UIString.UIString('Data'),sortable:false,weight:88},{id:'length',title:UIString.UIString('Length'),sortable:false,align:DataGrid.Align.Right,weight:5},{id:'time',title:UIString.UIString('Time'),sortable:true,weight:7}]);this._dataGrid=new SortableDataGrid.SortableDataGrid({displayName:ls`Web Socket Frame`,columns});this._dataGrid.setRowContextMenuCallback(onRowContextMenu.bind(this));this._dataGrid.setStickToBottom(true);this._dataGrid.setCellClass('websocket-frame-view-td');this._timeComparator=(ResourceWebSocketFrameNodeTimeComparator);this._dataGrid.sortNodes(this._timeComparator,false);this._dataGrid.markColumnAsSortedBy('time',DataGrid.Order.Ascending);this._dataGrid.addEventListener(DataGrid.Events.SortingChanged,this._sortItems,this);this._dataGrid.setName('ResourceWebSocketFrameView');this._dataGrid.addEventListener(DataGrid.Events.SelectedNode,event=>{this._onFrameSelected(event);},this);this._dataGrid.addEventListener(DataGrid.Events.DeselectedNode,this._onFrameDeselected,this);this._mainToolbar=new Toolbar.Toolbar('');this._clearAllButton=new Toolbar.ToolbarButton(UIString.UIString('Clear All'),'largeicon-clear');this._clearAllButton.addEventListener(Toolbar.ToolbarButton.Events.Click,this._clearFrames,this);this._mainToolbar.appendToolbarItem(this._clearAllButton);this._filterTypeCombobox=new Toolbar.ToolbarComboBox(this._updateFilterSetting.bind(this),ls`Filter`);for(const filterItem of _filterTypes){const option=this._filterTypeCombobox.createOption(filterItem.label,filterItem.name);this._filterTypeCombobox.addOption(option);}
this._mainToolbar.appendToolbarItem(this._filterTypeCombobox);this._filterType=null;const placeholder='Enter regex, for example: (web)?socket';this._filterTextInput=new Toolbar.ToolbarInput(UIString.UIString(placeholder),'',0.4);this._filterTextInput.addEventListener(Toolbar.ToolbarInput.Event.TextChanged,this._updateFilterSetting,this);this._mainToolbar.appendToolbarItem(this._filterTextInput);this._filterRegex=null;const mainContainer=new Widget.VBox();mainContainer.element.appendChild(this._mainToolbar.element);this._dataGrid.asWidget().show(mainContainer.element);mainContainer.setMinimumSize(0,72);this._splitWidget.setMainWidget(mainContainer);this._frameEmptyWidget=new EmptyWidget.EmptyWidget(UIString.UIString('Select message to browse its content.'));this._splitWidget.setSidebarWidget(this._frameEmptyWidget);this._selectedNode=null;function onRowContextMenu(contextMenu,genericNode){const node=(genericNode);const binaryView=node.binaryView();if(binaryView){binaryView.addCopyToContextMenu(contextMenu,ls`Copy message...`);}else{contextMenu.clipboardSection().appendItem(UIString.UIString('Copy message'),InspectorFrontendHost.InspectorFrontendHostInstance.copyText.bind(InspectorFrontendHost.InspectorFrontendHostInstance,node.data.data));}
contextMenu.footerSection().appendItem(UIString.UIString('Clear all'),this._clearFrames.bind(this));}}
static opCodeDescription(opCode,mask){const localizedDescription=opCodeDescriptions[opCode]||'';if(mask){return ls`${localizedDescription} (Opcode ${opCode}, mask)`;}
return ls`${localizedDescription} (Opcode ${opCode})`;}
wasShown(){this.refresh();this._request.addEventListener(NetworkRequest.Events.WebsocketFrameAdded,this._frameAdded,this);}
willHide(){this._request.removeEventListener(NetworkRequest.Events.WebsocketFrameAdded,this._frameAdded,this);}
_frameAdded(event){const frame=(event.data);if(!this._frameFilter(frame)){return;}
this._dataGrid.insertChild(new ResourceWebSocketFrameNode(this._request.url(),frame));}
_frameFilter(frame){if(this._filterType&&frame.type!==this._filterType){return false;}
return!this._filterRegex||this._filterRegex.test(frame.text);}
_clearFrames(){this._request[_clearFrameOffsetSymbol]=this._request.frames().length;this.refresh();}
_updateFilterSetting(){const text=this._filterTextInput.value();const type=this._filterTypeCombobox.selectedOption().value;this._filterRegex=text?new RegExp(text,'i'):null;this._filterType=type==='all'?null:type;this.refresh();}
async _onFrameSelected(event){this._currentSelectedNode=(event.data);const content=this._currentSelectedNode.dataText();const binaryView=this._currentSelectedNode.binaryView();if(binaryView){this._splitWidget.setSidebarWidget(binaryView);return;}
const jsonView=await JSONView.JSONView.createView(content);if(jsonView){this._splitWidget.setSidebarWidget(jsonView);return;}
this._splitWidget.setSidebarWidget(new ResourceSourceFrame.ResourceSourceFrame(StaticContentProvider.StaticContentProvider.fromString(this._request.url(),ResourceType.resourceTypes.WebSocket,content)));}
_onFrameDeselected(event){this._currentSelectedNode=null;this._splitWidget.setSidebarWidget(this._frameEmptyWidget);}
refresh(){this._dataGrid.rootNode().removeChildren();const url=this._request.url();let frames=this._request.frames();const offset=this._request[_clearFrameOffsetSymbol]||0;frames=frames.slice(offset);frames=frames.filter(this._frameFilter.bind(this));frames.forEach(frame=>this._dataGrid.insertChild(new ResourceWebSocketFrameNode(url,frame)));}
_sortItems(){this._dataGrid.sortNodes(this._timeComparator,!this._dataGrid.isSortOrderAscending());}}
const OpCodes={ContinuationFrame:0,TextFrame:1,BinaryFrame:2,ConnectionCloseFrame:8,PingFrame:9,PongFrame:10};const opCodeDescriptions=(function(){const opCodes=OpCodes;const map=[];map[opCodes.ContinuationFrame]=ls`Continuation Frame`;map[opCodes.TextFrame]=ls`Text Message`;map[opCodes.BinaryFrame]=ls`Binary Message`;map[opCodes.ContinuationFrame]=ls`Connection Close Message`;map[opCodes.PingFrame]=ls`Ping Message`;map[opCodes.PongFrame]=ls`Pong Message`;return map;})();const _filterTypes=[{name:'all',label:UIString.UIString('All')},{name:'send',label:UIString.UIString('Send')},{name:'receive',label:UIString.UIString('Receive')},];class ResourceWebSocketFrameNode extends SortableDataGrid.SortableDataGridNode{constructor(url,frame){let length=frame.text.length;const time=new Date(frame.time*1000);const timeText=('0'+time.getHours()).substr(-2)+':'+('0'+time.getMinutes()).substr(-2)+':'+
('0'+time.getSeconds()).substr(-2)+'.'+('00'+time.getMilliseconds()).substr(-3);const timeNode=createElement('div');timeNode.createTextChild(timeText);timeNode.title=time.toLocaleString();let dataText=frame.text;let description=ResourceWebSocketFrameView.opCodeDescription(frame.opCode,frame.mask);const isTextFrame=frame.opCode===OpCodes.TextFrame;if(frame.type===NetworkRequest.WebSocketFrameType.Error){description=dataText;length=ls`N/A`;}else if(isTextFrame){description=dataText;}else if(frame.opCode===OpCodes.BinaryFrame){length=Number.bytesToString(base64ToSize(frame.text));description=opCodeDescriptions[frame.opCode];}else{dataText=description;}
super({data:description,length:length,time:timeNode});this._url=url;this._frame=frame;this._isTextFrame=isTextFrame;this._dataText=dataText;}
createCells(element){element.classList.toggle('websocket-frame-view-row-error',this._frame.type===NetworkRequest.WebSocketFrameType.Error);element.classList.toggle('websocket-frame-view-row-send',this._frame.type===NetworkRequest.WebSocketFrameType.Send);element.classList.toggle('websocket-frame-view-row-receive',this._frame.type===NetworkRequest.WebSocketFrameType.Receive);super.createCells(element);}
nodeSelfHeight(){return 21;}
dataText(){return this._dataText;}
opCode(){return(this._frame.opCode);}
binaryView(){if(this._isTextFrame||this._frame.type===NetworkRequest.WebSocketFrameType.Error){return null;}
if(!this._binaryView){this._binaryView=new BinaryResourceView(this._dataText,'',ResourceType.resourceTypes.WebSocket);}
return this._binaryView;}}
function ResourceWebSocketFrameNodeTimeComparator(a,b){return a._frame.time-b._frame.time;}
const _clearFrameOffsetSymbol=Symbol('ClearFrameOffset');var ResourceWebSocketFrameView$1=Object.freeze({__proto__:null,ResourceWebSocketFrameView:ResourceWebSocketFrameView,OpCodes:OpCodes,opCodeDescriptions:opCodeDescriptions,_filterTypes:_filterTypes,ResourceWebSocketFrameNode:ResourceWebSocketFrameNode,ResourceWebSocketFrameNodeTimeComparator:ResourceWebSocketFrameNodeTimeComparator,_clearFrameOffsetSymbol:_clearFrameOffsetSymbol});class NetworkItemView extends TabbedPane.TabbedPane{constructor(request,calculator,initialTab){super();this._request=request;this.element.classList.add('network-item-view');this._resourceViewTabSetting=Settings.Settings.instance().createSetting('resourceViewTab','preview');this._headersView=new RequestHeadersView(request);this.appendTab(Tabs.Headers,UIString.UIString('Headers'),this._headersView,UIString.UIString('Headers and request body'));this.addEventListener(TabbedPane.Events.TabSelected,this._tabSelected,this);if(request.resourceType()===ResourceType.resourceTypes.WebSocket){const frameView=new ResourceWebSocketFrameView(request);this.appendTab(Tabs.WsFrames,UIString.UIString('Messages'),frameView,UIString.UIString('WebSocket messages'));}else if(request.mimeType==='text/event-stream'){this.appendTab(Tabs.EventSource,UIString.UIString('EventStream'),new EventSourceMessagesView(request));}else{this._responseView=new RequestResponseView(request);const previewView=new RequestPreviewView(request);this.appendTab(Tabs.Preview,UIString.UIString('Preview'),previewView,UIString.UIString('Response preview'));if(request.signedExchangeInfo()&&request.signedExchangeInfo().errors&&request.signedExchangeInfo().errors.length){const icon=Icon.Icon.create('smallicon-error');icon.title=UIString.UIString('SignedExchange error');this.setTabIcon(Tabs.Preview,icon);}
this.appendTab(Tabs.Response,UIString.UIString('Response'),this._responseView,UIString.UIString('Raw response data'));}
this.appendTab(Tabs.Initiator,ls`Initiator`,new RequestInitiatorView(request),ls`Request initiator call stack`);this.appendTab(Tabs.Timing,UIString.UIString('Timing'),new RequestTimingView(request,calculator),UIString.UIString('Request and response timeline'));this._cookiesView=null;this._initialTab=initialTab||this._resourceViewTabSetting.get();}
wasShown(){super.wasShown();this._request.addEventListener(NetworkRequest.Events.RequestHeadersChanged,this._maybeAppendCookiesPanel,this);this._request.addEventListener(NetworkRequest.Events.ResponseHeadersChanged,this._maybeAppendCookiesPanel,this);this._maybeAppendCookiesPanel();this._selectTab(this._initialTab);}
willHide(){this._request.removeEventListener(NetworkRequest.Events.RequestHeadersChanged,this._maybeAppendCookiesPanel,this);this._request.removeEventListener(NetworkRequest.Events.ResponseHeadersChanged,this._maybeAppendCookiesPanel,this);}
_maybeAppendCookiesPanel(){const cookiesPresent=this._request.requestCookies.length||this._request.responseCookies.length;console.assert(cookiesPresent||!this._cookiesView,'Cookies were introduced in headers and then removed!');if(cookiesPresent&&!this._cookiesView){this._cookiesView=new RequestCookiesView(this._request);this.appendTab(Tabs.Cookies,UIString.UIString('Cookies'),this._cookiesView,UIString.UIString('Request and response cookies'));}}
_selectTab(tabId){if(!this.selectTab(tabId)){this.selectTab('headers');}}
_tabSelected(event){if(!event.data.isUserGesture){return;}
this._resourceViewTabSetting.set(event.data.tabId);}
request(){return this._request;}
async revealResponseBody(line){this._selectTab(Tabs.Response);if(this._responseView&&typeof line==='number'){await this._responseView.revealLine((line));}}
revealRequestHeader(header){this._selectTab(Tabs.Headers);this._headersView.revealRequestHeader(header);}
revealResponseHeader(header){this._selectTab(Tabs.Headers);this._headersView.revealResponseHeader(header);}}
const Tabs={Cookies:'cookies',EventSource:'eventSource',Headers:'headers',Initiator:'initiator',Preview:'preview',Response:'response',Timing:'timing',WsFrames:'webSocketFrames'};var NetworkItemView$1=Object.freeze({__proto__:null,NetworkItemView:NetworkItemView,Tabs:Tabs});const Events$1={RequestSelected:Symbol('RequestSelected'),RequestActivated:Symbol('RequestActivated')};class NetworkLogViewInterface{static HTTPRequestsFilter(request){}
async onLoadFromFile(file){}
nodeForRequest(request){}
headerHeight(){}
setRecording(recording){}
setWindow(start,end){}
resetFocus(){}
columnExtensionResolved(){}
hoveredNode(){}
scheduleRefresh(){}
addFilmStripFrames(times){}
selectFilmStripFrame(time){}
clearFilmStripFrame(){}
timeCalculator(){}
calculator(){}
setCalculator(x){}
flatNodesList(){}
updateNodeBackground(){}
updateNodeSelectedClass(isSelected){}
stylesChanged(){}
setTextFilterValue(filterString){}
rowHeight(){}
switchViewMode(gridMode){}
handleContextMenuForRequest(contextMenu,request){}
async exportAll(){}
revealAndHighlightRequest(request){}
selectRequest(request){}
removeAllNodeHighlights(){}
static getDCLEventColor(){}
static getLoadEventColor(){}}
class NetworkNode extends SortableDataGrid.SortableDataGridNode{constructor(parentView){super({});this._parentView=parentView;this._isHovered=false;this._showingInitiatorChain=false;this._requestOrFirstKnownChildRequest=null;}
displayName(){return'';}
createCell(columnId){const cell=this.createTD(columnId);this.renderCell(cell,columnId);return cell;}
renderCell(cell,columnId){}
_isFailed(){return false;}
backgroundColor(){const bgColors=_backgroundColors;const hasFocus=document.hasFocus();const isSelected=this.dataGrid&&this.dataGrid.element===document.activeElement;const isFailed=this._isFailed();if(this.selected&&hasFocus&&isSelected&&isFailed){return bgColors.FocusSelectedHasError;}
if(this.selected&&hasFocus&&isSelected){return bgColors.FocusSelected;}
if(this.selected){return bgColors.Selected;}
if(this.hovered()){return bgColors.Hovered;}
if(this.isOnInitiatorPath()){return bgColors.InitiatorPath;}
if(this.isOnInitiatedPath()){return bgColors.InitiatedPath;}
if(this.isStriped()){return bgColors.Stripe;}
return bgColors.Default;}
updateBackgroundColor(){const element=this.existingElement();if(!element){return;}
element.style.backgroundColor=`var(${this.backgroundColor()})`;this._parentView.stylesChanged();}
setStriped(isStriped){super.setStriped(isStriped);this.updateBackgroundColor();}
select(supressSelectedEvent){super.select(supressSelectedEvent);this.updateBackgroundColor();this._parentView.updateNodeSelectedClass(true);}
deselect(supressSelectedEvent){super.deselect(supressSelectedEvent);this.updateBackgroundColor();this._parentView.updateNodeSelectedClass(false);}
parentView(){return this._parentView;}
hovered(){return this._isHovered;}
showingInitiatorChain(){return this._showingInitiatorChain;}
nodeSelfHeight(){return this._parentView.rowHeight();}
setHovered(hovered,showInitiatorChain){if(this._isHovered===hovered&&this._showingInitiatorChain===showInitiatorChain){return;}
if(this._isHovered!==hovered){this._isHovered=hovered;if(this.attached()){this.element().classList.toggle('hover',hovered);}}
if(this._showingInitiatorChain!==showInitiatorChain){this._showingInitiatorChain=showInitiatorChain;this.showingInitiatorChainChanged();}
this._parentView.stylesChanged();this.updateBackgroundColor();}
showingInitiatorChainChanged(){}
isOnInitiatorPath(){return false;}
isOnInitiatedPath(){return false;}
request(){return null;}
isNavigationRequest(){return false;}
clearFlatNodes(){super.clearFlatNodes();this._requestOrFirstKnownChildRequest=null;}
requestOrFirstKnownChildRequest(){if(this._requestOrFirstKnownChildRequest){return this._requestOrFirstKnownChildRequest;}
let request=this.request();if(request||!this.hasChildren()){this._requestOrFirstKnownChildRequest=request;return this._requestOrFirstKnownChildRequest;}
let firstChildRequest=null;const flatChildren=this.flatChildren();for(let i=0;i<flatChildren.length;i++){request=flatChildren[i].request();if(!firstChildRequest||(request&&request.issueTime()<firstChildRequest.issueTime())){firstChildRequest=request;}}
this._requestOrFirstKnownChildRequest=firstChildRequest;return this._requestOrFirstKnownChildRequest;}}
const _backgroundColors={Default:'--network-grid-default-color',Stripe:'--network-grid-stripe-color',Navigation:'--network-grid-navigation-color',Hovered:'--network-grid-hovered-color',InitiatorPath:'--network-grid-initiator-path-color',InitiatedPath:'--network-grid-initiated-path-color',Selected:'--network-grid-selected-color',FocusSelected:'--network-grid-focus-selected-color',FocusSelectedHasError:'--network-grid-focus-selected-color-has-error',FromFrame:'--network-grid-from-frame-color',};class NetworkRequestNode extends NetworkNode{constructor(parentView,request){super(parentView);this._nameCell=null;this._initiatorCell=null;this._request=request;this._isNavigationRequest=false;this.selectable=true;this._isOnInitiatorPath=false;this._isOnInitiatedPath=false;}
static NameComparator(a,b){const aName=a.displayName().toLowerCase();const bName=b.displayName().toLowerCase();if(aName===bName){const aRequest=a.requestOrFirstKnownChildRequest();const bRequest=b.requestOrFirstKnownChildRequest();if(aRequest&&bRequest){return aRequest.indentityCompare(bRequest);}
return aRequest?-1:1;}
return aName<bName?-1:1;}
static RemoteAddressComparator(a,b){const aRequest=a.requestOrFirstKnownChildRequest();const bRequest=b.requestOrFirstKnownChildRequest();if(!aRequest||!bRequest){return!aRequest?-1:1;}
const aRemoteAddress=aRequest.remoteAddress();const bRemoteAddress=bRequest.remoteAddress();if(aRemoteAddress>bRemoteAddress){return 1;}
if(bRemoteAddress>aRemoteAddress){return-1;}
return aRequest.indentityCompare(bRequest);}
static SizeComparator(a,b){const aRequest=a.requestOrFirstKnownChildRequest();const bRequest=b.requestOrFirstKnownChildRequest();if(!aRequest||!bRequest){return!aRequest?-1:1;}
if(bRequest.cached()&&!aRequest.cached()){return 1;}
if(aRequest.cached()&&!bRequest.cached()){return-1;}
return(aRequest.transferSize-bRequest.transferSize)||(aRequest.resourceSize-bRequest.resourceSize)||aRequest.indentityCompare(bRequest);}
static TypeComparator(a,b){const aRequest=a.requestOrFirstKnownChildRequest();const bRequest=b.requestOrFirstKnownChildRequest();if(!aRequest||!bRequest){return!aRequest?-1:1;}
const aSimpleType=a.displayType();const bSimpleType=b.displayType();if(aSimpleType>bSimpleType){return 1;}
if(bSimpleType>aSimpleType){return-1;}
return aRequest.indentityCompare(bRequest);}
static InitiatorComparator(a,b){const aRequest=a.requestOrFirstKnownChildRequest();const bRequest=b.requestOrFirstKnownChildRequest();if(!aRequest||!bRequest){return!aRequest?-1:1;}
if(!a._initiatorCell||!b._initiatorCell){return!a._initiatorCell?-1:1;}
const aText=a._linkifiedInitiatorAnchor?a._linkifiedInitiatorAnchor.textContent:a._initiatorCell.title;const bText=b._linkifiedInitiatorAnchor?b._linkifiedInitiatorAnchor.textContent:b._initiatorCell.title;return aText.localeCompare(bText);}
static RequestCookiesCountComparator(a,b){const aRequest=a.requestOrFirstKnownChildRequest();const bRequest=b.requestOrFirstKnownChildRequest();if(!aRequest||!bRequest){return!aRequest?-1:1;}
const aScore=aRequest.requestCookies.length;const bScore=bRequest.requestCookies.length;return(aScore-bScore)||aRequest.indentityCompare(bRequest);}
static ResponseCookiesCountComparator(a,b){const aRequest=a.requestOrFirstKnownChildRequest();const bRequest=b.requestOrFirstKnownChildRequest();if(!aRequest||!bRequest){return!aRequest?-1:1;}
const aScore=aRequest.responseCookies?aRequest.responseCookies.length:0;const bScore=bRequest.responseCookies?bRequest.responseCookies.length:0;return(aScore-bScore)||aRequest.indentityCompare(bRequest);}
static PriorityComparator(a,b){const aRequest=a.requestOrFirstKnownChildRequest();const bRequest=b.requestOrFirstKnownChildRequest();if(!aRequest||!bRequest){return!aRequest?-1:1;}
const aPriority=aRequest.priority();let aScore=aPriority?NetworkPriorities.networkPriorityWeight(aPriority):0;aScore=aScore||0;const bPriority=bRequest.priority();let bScore=bPriority?NetworkPriorities.networkPriorityWeight(bPriority):0;bScore=bScore||0;return aScore-bScore||aRequest.indentityCompare(bRequest);}
static RequestPropertyComparator(propertyName,a,b){const aRequest=a.requestOrFirstKnownChildRequest();const bRequest=b.requestOrFirstKnownChildRequest();if(!aRequest||!bRequest){return!aRequest?-1:1;}
const aValue=aRequest[propertyName];const bValue=bRequest[propertyName];if(aValue===bValue){return aRequest.indentityCompare(bRequest);}
return aValue>bValue?1:-1;}
static ResponseHeaderStringComparator(propertyName,a,b){const aRequest=a.requestOrFirstKnownChildRequest();const bRequest=b.requestOrFirstKnownChildRequest();if(!aRequest||!bRequest){return!aRequest?-1:1;}
const aValue=String(aRequest.responseHeaderValue(propertyName)||'');const bValue=String(bRequest.responseHeaderValue(propertyName)||'');return aValue.localeCompare(bValue)||aRequest.indentityCompare(bRequest);}
static ResponseHeaderNumberComparator(propertyName,a,b){const aRequest=a.requestOrFirstKnownChildRequest();const bRequest=b.requestOrFirstKnownChildRequest();if(!aRequest||!bRequest){return!aRequest?-1:1;}
const aValue=(aRequest.responseHeaderValue(propertyName)!==undefined)?parseFloat(aRequest.responseHeaderValue(propertyName)):-Infinity;const bValue=(bRequest.responseHeaderValue(propertyName)!==undefined)?parseFloat(bRequest.responseHeaderValue(propertyName)):-Infinity;if(aValue===bValue){return aRequest.indentityCompare(bRequest);}
return aValue>bValue?1:-1;}
static ResponseHeaderDateComparator(propertyName,a,b){const aRequest=a.requestOrFirstKnownChildRequest();const bRequest=b.requestOrFirstKnownChildRequest();if(!aRequest||!bRequest){return!aRequest?-1:1;}
const aHeader=aRequest.responseHeaderValue(propertyName);const bHeader=bRequest.responseHeaderValue(propertyName);const aValue=aHeader?new Date(aHeader).getTime():-Infinity;const bValue=bHeader?new Date(bHeader).getTime():-Infinity;if(aValue===bValue){return aRequest.indentityCompare(bRequest);}
return aValue>bValue?1:-1;}
showingInitiatorChainChanged(){const showInitiatorChain=this.showingInitiatorChain();const initiatorGraph=self.SDK.networkLog.initiatorGraphForRequest(this._request);for(const request of initiatorGraph.initiators){if(request===this._request){continue;}
const node=this.parentView().nodeForRequest(request);if(!node){continue;}
node._setIsOnInitiatorPath(showInitiatorChain);}
for(const request of initiatorGraph.initiated.keys()){if(request===this._request){continue;}
const node=this.parentView().nodeForRequest(request);if(!node){continue;}
node._setIsOnInitiatedPath(showInitiatorChain);}}
_setIsOnInitiatorPath(isOnInitiatorPath){if(this._isOnInitiatorPath===isOnInitiatorPath||!this.attached()){return;}
this._isOnInitiatorPath=isOnInitiatorPath;this.updateBackgroundColor();}
isOnInitiatorPath(){return this._isOnInitiatorPath;}
_setIsOnInitiatedPath(isOnInitiatedPath){if(this._isOnInitiatedPath===isOnInitiatedPath||!this.attached()){return;}
this._isOnInitiatedPath=isOnInitiatedPath;this.updateBackgroundColor();}
isOnInitiatedPath(){return this._isOnInitiatedPath;}
displayType(){const mimeType=this._request.mimeType||this._request.requestContentType()||'';const resourceType=this._request.resourceType();let simpleType=resourceType.name();if(resourceType===ResourceType.resourceTypes.Other||resourceType===ResourceType.resourceTypes.Image){simpleType=mimeType.replace(/^(application|image)\//,'');}
return simpleType;}
displayName(){return this._request.name();}
request(){return this._request;}
isNavigationRequest(){const pageLoad=NetworkLog.PageLoad.forRequest(this._request);return pageLoad?pageLoad.mainRequest===this._request:false;}
nodeSelfHeight(){return this.parentView().rowHeight();}
createCells(element){this._nameCell=null;this._initiatorCell=null;element.classList.toggle('network-error-row',this._isFailed());element.classList.toggle('network-navigation-row',this._isNavigationRequest);super.createCells(element);this.updateBackgroundColor();}
_setTextAndTitle(element,text){element.createTextChild(text);element.title=text;}
_setTextAndTitleAndLink(element,cellText,linkText,handler){element.createTextChild(cellText);element.createChild('span','separator-in-cell');const link=createElementWithClass('span','devtools-link');link.textContent=linkText;link.addEventListener('click',handler);element.appendChild(link);element.title=cellText;}
renderCell(cell,columnId){switch(columnId){case'name':{this._renderPrimaryCell(cell,columnId);break;}
case'path':{this._renderPrimaryCell(cell,columnId,this._request.pathname);break;}
case'url':{this._renderPrimaryCell(cell,columnId,this._request.url());break;}
case'method':{this._setTextAndTitle(cell,this._request.requestMethod);break;}
case'status':{this._renderStatusCell(cell);break;}
case'protocol':{this._setTextAndTitle(cell,this._request.protocol);break;}
case'scheme':{this._setTextAndTitle(cell,this._request.scheme);break;}
case'domain':{this._setTextAndTitle(cell,this._request.domain);break;}
case'remoteaddress':{this._setTextAndTitle(cell,this._request.remoteAddress());break;}
case'cookies':{this._setTextAndTitle(cell,this._arrayLength(this._request.requestCookies));break;}
case'setcookies':{this._setTextAndTitle(cell,this._arrayLength(this._request.responseCookies));break;}
case'priority':{const priority=this._request.priority();this._setTextAndTitle(cell,priority?NetworkPriorities.uiLabelForNetworkPriority(priority):'');break;}
case'connectionid':{this._setTextAndTitle(cell,this._request.connectionId);break;}
case'type':{this._setTextAndTitle(cell,this.displayType());break;}
case'initiator':{this._renderInitiatorCell(cell);break;}
case'size':{this._renderSizeCell(cell);break;}
case'time':{this._renderTimeCell(cell);break;}
case'timeline':{this._setTextAndTitle(cell,'');break;}
default:{this._setTextAndTitle(cell,this._request.responseHeaderValue(columnId)||'');break;}}}
_arrayLength(array){return array?''+array.length:'';}
select(supressSelectedEvent){super.select(supressSelectedEvent);this.parentView().dispatchEventToListeners(Events$1.RequestSelected,this._request);}
highlightMatchedSubstring(regexp){if(!regexp){return[];}
this.element();const domChanges=[];const matchInfo=this._nameCell.textContent.match(regexp);if(matchInfo){UIUtils.highlightSearchResult(this._nameCell,matchInfo.index,matchInfo[0].length,domChanges);}
return domChanges;}
_openInNewTab(){InspectorFrontendHost.InspectorFrontendHostInstance.openInNewTab(this._request.url());}
_isFailed(){return(this._request.failed&&!this._request.statusCode)||(this._request.statusCode>=400)||(!!this._request.signedExchangeInfo()&&!!this._request.signedExchangeInfo().errors);}
_renderPrimaryCell(cell,columnId,text){const columnIndex=this.dataGrid.indexOfVisibleColumn(columnId);const isFirstCell=(columnIndex===0);if(isFirstCell){const leftPadding=this.leftPadding?this.leftPadding+'px':'';cell.style.setProperty('padding-left',leftPadding);this._nameCell=cell;cell.addEventListener('dblclick',this._openInNewTab.bind(this),false);cell.addEventListener('click',()=>{this.parentView().dispatchEventToListeners(Events$1.RequestActivated,{showPanel:true});});let iconElement;if(this._request.resourceType()===ResourceType.resourceTypes.Image){const previewImage=createElementWithClass('img','image-network-icon-preview');previewImage.alt=this._request.resourceType().title();this._request.populateImageSource(previewImage);iconElement=createElementWithClass('div','icon');iconElement.appendChild(previewImage);}else{iconElement=createElementWithClass('img','icon');iconElement.alt=this._request.resourceType().title();}
iconElement.classList.add(this._request.resourceType().name());cell.appendChild(iconElement);}
if(columnId==='name'){const name=this._request.name().trimMiddle(100);const networkManager=NetworkManager.NetworkManager.forRequest(this._request);cell.createTextChild(networkManager?networkManager.target().decorateLabel(name):name);this._appendSubtitle(cell,this._request.path());cell.title=this._request.url();}else if(text){cell.createTextChild(text);cell.title=text;}}
_renderStatusCell(cell){cell.classList.toggle('network-dim-cell',!this._isFailed()&&(this._request.cached()||!this._request.statusCode));if(this._request.failed&&!this._request.canceled&&!this._request.wasBlocked()){const failText=UIString.UIString('(failed)');if(this._request.localizedFailDescription){cell.createTextChild(failText);this._appendSubtitle(cell,this._request.localizedFailDescription,true);cell.title=failText+' '+this._request.localizedFailDescription;}else{this._setTextAndTitle(cell,failText);}}else if(this._request.statusCode){cell.createTextChild(''+this._request.statusCode);this._appendSubtitle(cell,this._request.statusText);cell.title=this._request.statusCode+' '+this._request.statusText;}else if(this._request.parsedURL.isDataURL()){this._setTextAndTitle(cell,UIString.UIString('(data)'));}else if(this._request.canceled){this._setTextAndTitle(cell,UIString.UIString('(canceled)'));}else if(this._request.wasBlocked()){let reason=UIString.UIString('other');let displayShowHeadersLink=false;switch(this._request.blockedReason()){case Protocol.Network.BlockedReason.Other:reason=UIString.UIString('other');break;case Protocol.Network.BlockedReason.Csp:reason=UIString.UIString('csp');break;case Protocol.Network.BlockedReason.MixedContent:reason=UIString.UIString('mixed-content');break;case Protocol.Network.BlockedReason.Origin:reason=UIString.UIString('origin');break;case Protocol.Network.BlockedReason.Inspector:reason=UIString.UIString('devtools');break;case Protocol.Network.BlockedReason.SubresourceFilter:reason=UIString.UIString('subresource-filter');break;case Protocol.Network.BlockedReason.ContentType:reason=UIString.UIString('content-type');break;case Protocol.Network.BlockedReason.CollapsedByClient:reason=UIString.UIString('extension');break;case Protocol.Network.BlockedReason.CoepFrameResourceNeedsCoepHeader:displayShowHeadersLink=true;reason=UIString.UIString('CoepFrameResourceNeedsCoepHeader');break;case Protocol.Network.BlockedReason.CoopSandboxedIframeCannotNavigateToCoopPage:displayShowHeadersLink=true;reason=UIString.UIString('CoopSandboxedIframeCannotNavigateToCoopPage');break;case Protocol.Network.BlockedReason.CorpNotSameOrigin:displayShowHeadersLink=true;reason=UIString.UIString('NotSameOrigin');break;case Protocol.Network.BlockedReason.CorpNotSameSite:displayShowHeadersLink=true;reason=UIString.UIString('NotSameSite');break;case Protocol.Network.BlockedReason.CorpNotSameOriginAfterDefaultedToSameOriginByCoep:displayShowHeadersLink=true;reason=UIString.UIString('NotSameOriginAfterDefaultedToSameOriginByCoep');break;}
if(displayShowHeadersLink){this._setTextAndTitleAndLink(cell,UIString.UIString('(blocked:%s)',reason),'View Headers',()=>{this.parentView().dispatchEventToListeners(Events$1.RequestActivated,{showPanel:true,tab:Tabs.Headers});});}else{this._setTextAndTitle(cell,UIString.UIString('(blocked:%s)',reason));}}else if(this._request.finished){this._setTextAndTitle(cell,UIString.UIString('Finished'));}else{this._setTextAndTitle(cell,UIString.UIString('(pending)'));}}
_renderInitiatorCell(cell){this._initiatorCell=cell;const request=this._request;const initiator=self.SDK.networkLog.initiatorInfoForRequest(request);const timing=request.timing;if(timing&&timing.pushStart){cell.appendChild(createTextNode(UIString.UIString('Push / ')));}
switch(initiator.type){case NetworkRequest.InitiatorType.Parser:{cell.title=initiator.url+':'+(initiator.lineNumber+1);const uiSourceCode=Workspace.WorkspaceImpl.instance().uiSourceCodeForURL(initiator.url);cell.appendChild(Linkifier.Linkifier.linkifyURL(initiator.url,{text:uiSourceCode?uiSourceCode.displayName():undefined,lineNumber:initiator.lineNumber,columnNumber:initiator.columnNumber}));this._appendSubtitle(cell,UIString.UIString('Parser'));break;}
case NetworkRequest.InitiatorType.Redirect:{cell.title=initiator.url;const redirectSource=(request.redirectSource());console.assert(redirectSource);if(this.parentView().nodeForRequest(redirectSource)){cell.appendChild(Linkifier.Linkifier.linkifyRevealable(redirectSource,ResourceUtils.displayNameForURL(redirectSource.url())));}else{cell.appendChild(Linkifier.Linkifier.linkifyURL(redirectSource.url()));}
this._appendSubtitle(cell,UIString.UIString('Redirect'));break;}
case NetworkRequest.InitiatorType.Script:{const networkManager=NetworkManager.NetworkManager.forRequest(request);const linkifier=this.parentView().linkifier;if(initiator.stack){this._linkifiedInitiatorAnchor=linkifier.linkifyStackTraceTopFrame(networkManager.target(),initiator.stack);}else{this._linkifiedInitiatorAnchor=linkifier.linkifyScriptLocation(networkManager.target(),initiator.scriptId,initiator.url,initiator.lineNumber,{columnNumber:initiator.columnNumber});}
this._linkifiedInitiatorAnchor.title='';cell.appendChild(this._linkifiedInitiatorAnchor);this._appendSubtitle(cell,UIString.UIString('Script'));cell.classList.add('network-script-initiated');cell.request=request;break;}
case NetworkRequest.InitiatorType.Preload:{cell.title=UIString.UIString('Preload');cell.classList.add('network-dim-cell');cell.appendChild(createTextNode(UIString.UIString('Preload')));break;}
case NetworkRequest.InitiatorType.SignedExchange:{cell.appendChild(Linkifier.Linkifier.linkifyURL(initiator.url));this._appendSubtitle(cell,UIString.UIString('signed-exchange'));break;}
default:{cell.title=UIString.UIString('Other');cell.classList.add('network-dim-cell');cell.appendChild(createTextNode(UIString.UIString('Other')));}}}
_renderSizeCell(cell){const resourceSize=Number.bytesToString(this._request.resourceSize);if(this._request.cachedInMemory()){cell.createTextChild(ls`(memory cache)`);cell.title=ls`Served from memory cache, resource size: ${resourceSize}`;cell.classList.add('network-dim-cell');}else if(this._request.fetchedViaServiceWorker){cell.createTextChild(ls`(ServiceWorker)`);cell.title=ls`Served from ServiceWorker, resource size: ${resourceSize}`;cell.classList.add('network-dim-cell');}else if(this._request.redirectSource()&&this._request.redirectSource().signedExchangeInfo()&&!this._request.redirectSource().signedExchangeInfo().errors){cell.createTextChild(ls`(signed-exchange)`);cell.title=ls`Served from Signed HTTP Exchange, resource size: ${resourceSize}`;cell.classList.add('network-dim-cell');}else if(this._request.fromPrefetchCache()){cell.createTextChild(ls`(prefetch cache)`);cell.title=ls`Served from prefetch cache, resource size: ${resourceSize}`;cell.classList.add('network-dim-cell');}else if(this._request.cached()){cell.createTextChild(ls`(disk cache)`);cell.title=ls`Served from disk cache, resource size: ${resourceSize}`;cell.classList.add('network-dim-cell');}else{const transferSize=Number.bytesToString(this._request.transferSize);cell.createTextChild(transferSize);cell.title=`${transferSize} transferred over network, resource size: ${resourceSize}`;}
this._appendSubtitle(cell,resourceSize);}
_renderTimeCell(cell){if(this._request.duration>0){this._setTextAndTitle(cell,Number.secondsToString(this._request.duration));this._appendSubtitle(cell,Number.secondsToString(this._request.latency));}else{cell.classList.add('network-dim-cell');this._setTextAndTitle(cell,UIString.UIString('Pending'));}}
_appendSubtitle(cellElement,subtitleText,showInlineWhenSelected=false){const subtitleElement=createElement('div');subtitleElement.classList.add('network-cell-subtitle');if(showInlineWhenSelected){subtitleElement.classList.add('network-cell-subtitle-show-inline-when-selected');}
subtitleElement.textContent=subtitleText;cellElement.appendChild(subtitleElement);}}
class NetworkGroupNode extends NetworkNode{createCells(element){super.createCells(element);const primaryColumn=this.dataGrid.visibleColumnsArray[0];const localizedTitle=ls`${primaryColumn.title}`;const localizedLevel=ls`level 1`;this.nodeAccessibleText=`${localizedLevel} ${localizedTitle}: ${this.cellAccessibleTextMap.get(primaryColumn.id)}`;}
renderCell(cell,columnId){const columnIndex=this.dataGrid.indexOfVisibleColumn(columnId);if(columnIndex===0){const leftPadding=this.leftPadding?this.leftPadding+'px':'';cell.style.setProperty('padding-left',leftPadding);cell.classList.add('disclosure');this.setCellAccessibleName(cell.textContent,cell,columnId);}}
select(supressSelectedEvent){super.select(supressSelectedEvent);const firstChildNode=this.traverseNextNode(false,true);if(firstChildNode&&firstChildNode.request()){this.parentView().dispatchEventToListeners(Events$1.RequestSelected,firstChildNode.request());}}}
var NetworkDataGridNode=Object.freeze({__proto__:null,Events:Events$1,NetworkLogViewInterface:NetworkLogViewInterface,NetworkNode:NetworkNode,_backgroundColors:_backgroundColors,NetworkRequestNode:NetworkRequestNode,NetworkGroupNode:NetworkGroupNode});class NetworkFrameGrouper{constructor(parentView){this._parentView=parentView;this._activeGroups=new Map();}
groupNodeForRequest(request){const frame=ResourceTreeModel.ResourceTreeModel.frameForRequest(request);if(!frame||frame.isTopFrame()){return null;}
let groupNode=this._activeGroups.get(frame);if(groupNode){return groupNode;}
groupNode=new FrameGroupNode(this._parentView,frame);this._activeGroups.set(frame,groupNode);return groupNode;}
reset(){this._activeGroups.clear();}}
class FrameGroupNode extends NetworkGroupNode{constructor(parentView,frame){super(parentView);this._frame=frame;}
displayName(){return new ParsedURL.ParsedURL(this._frame.url).domain()||this._frame.name||'<iframe>';}
renderCell(cell,columnId){super.renderCell(cell,columnId);const columnIndex=this.dataGrid.indexOfVisibleColumn(columnId);if(columnIndex===0){const name=this.displayName();cell.appendChild(Icon.Icon.create('largeicon-navigator-frame','network-frame-group-icon'));cell.createTextChild(name);cell.title=name;this.setCellAccessibleName(cell.textContent,cell,columnId);}}}
var NetworkFrameGrouper$1=Object.freeze({__proto__:null,NetworkFrameGrouper:NetworkFrameGrouper,FrameGroupNode:FrameGroupNode});class NetworkManageCustomHeadersView extends Widget.VBox{constructor(columnData,addHeaderColumnCallback,changeHeaderColumnCallback,removeHeaderColumnCallback){super(true);this.registerRequiredCSS('network/networkManageCustomHeadersView.css');this.contentElement.classList.add('custom-headers-wrapper');this.contentElement.createChild('div','header').textContent=UIString.UIString('Manage Header Columns');this._list=new ListWidget.ListWidget(this);this._list.element.classList.add('custom-headers-list');this._list.registerRequiredCSS('network/networkManageCustomHeadersView.css');const placeholder=createElementWithClass('div','custom-headers-list-list-empty');placeholder.textContent=UIString.UIString('No custom headers');this._list.setEmptyPlaceholder(placeholder);this._list.show(this.contentElement);this.contentElement.appendChild(UIUtils.createTextButton(UIString.UIString('Add custom header…'),this._addButtonClicked.bind(this),'add-button'));this._columnConfigs=new Map();columnData.forEach(columnData=>this._columnConfigs.set(columnData.title.toLowerCase(),columnData));this._addHeaderColumnCallback=addHeaderColumnCallback;this._changeHeaderColumnCallback=changeHeaderColumnCallback;this._removeHeaderColumnCallback=removeHeaderColumnCallback;this.contentElement.tabIndex=0;}
wasShown(){this._headersUpdated();}
_headersUpdated(){this._list.clear();this._columnConfigs.forEach(headerData=>this._list.appendItem({header:headerData.title},headerData.editable));}
_addButtonClicked(){this._list.addNewItem(this._columnConfigs.size,{header:''});}
renderItem(item,editable){const element=createElementWithClass('div','custom-headers-list-item');const header=element.createChild('div','custom-header-name');header.textContent=item.header;header.title=item.header;return element;}
removeItemRequested(item,index){this._removeHeaderColumnCallback(item.header);this._columnConfigs.delete(item.header.toLowerCase());this._headersUpdated();}
commitEdit(item,editor,isNew){const headerId=editor.control('header').value.trim();let success;if(isNew){success=this._addHeaderColumnCallback(headerId);}else{success=this._changeHeaderColumnCallback(item.header,headerId);}
if(success&&!isNew){this._columnConfigs.delete(item.header.toLowerCase());}
if(success){this._columnConfigs.set(headerId.toLowerCase(),{title:headerId,editable:true});}
this._headersUpdated();}
beginEdit(item){const editor=this._createEditor();editor.control('header').value=item.header;return editor;}
_createEditor(){if(this._editor){return this._editor;}
const editor=new ListWidget.Editor();this._editor=editor;const content=editor.contentElement();const titles=content.createChild('div','custom-headers-edit-row');titles.createChild('div','custom-headers-header').textContent=UIString.UIString('Header Name');const fields=content.createChild('div','custom-headers-edit-row');fields.createChild('div','custom-headers-header').appendChild(editor.createInput('header','text','x-custom-header',validateHeader.bind(this)));return editor;function validateHeader(item,index,input){let valid=true;const headerId=editor.control('header').value.trim().toLowerCase();if(this._columnConfigs.has(headerId)&&item.header!==headerId){valid=false;}
return{valid};}}}
var NetworkManageCustomHeadersView$1=Object.freeze({__proto__:null,NetworkManageCustomHeadersView:NetworkManageCustomHeadersView});class NetworkWaterfallColumn extends Widget.VBox{constructor(calculator){super(false);this.registerRequiredCSS('network/networkWaterfallColumn.css');this._canvas=this.contentElement.createChild('canvas');this._canvas.tabIndex=-1;this.setDefaultFocusedElement(this._canvas);this._canvasPosition=this._canvas.getBoundingClientRect();this._leftPadding=5;this._fontSize=10;this._rightPadding=0;this._scrollTop=0;this._headerHeight=0;this._calculator=calculator;this._rawRowHeight=0;this._rowHeight=0;this._offsetWidth=0;this._offsetHeight=0;this._startTime=this._calculator.minimumBoundary();this._endTime=this._calculator.maximumBoundary();this._popoverHelper=new PopoverHelper.PopoverHelper(this.element,this._getPopoverRequest.bind(this));this._popoverHelper.setHasPadding(true);this._popoverHelper.setTimeout(300,300);this._nodes=[];this._hoveredNode=null;this._eventDividers=new Map();this._updateRequestID;this.element.addEventListener('mousemove',this._onMouseMove.bind(this),true);this.element.addEventListener('mouseleave',event=>this._setHoveredNode(null,false),true);this.element.addEventListener('click',this._onClick.bind(this),true);this._styleForTimeRangeName=NetworkWaterfallColumn._buildRequestTimeRangeStyle();const resourceStyleTuple=NetworkWaterfallColumn._buildResourceTypeStyle();this._styleForWaitingResourceType=resourceStyleTuple[0];this._styleForDownloadingResourceType=resourceStyleTuple[1];const baseLineColor=self.UI.themeSupport.patchColorText('#a5a5a5',UIUtils.ThemeSupport.ColorUsage.Foreground);this._wiskerStyle={borderColor:baseLineColor,lineWidth:1};this._hoverDetailsStyle={fillStyle:baseLineColor,lineWidth:1,borderColor:baseLineColor};this._pathForStyle=new Map();this._textLayers=[];this._computedDatagridStyle=null;}
static _buildRequestTimeRangeStyle(){const types=RequestTimeRangeNames;const styleMap=new Map();styleMap.set(types.Connecting,{fillStyle:'#FF9800'});styleMap.set(types.SSL,{fillStyle:'#9C27B0'});styleMap.set(types.DNS,{fillStyle:'#009688'});styleMap.set(types.Proxy,{fillStyle:'#A1887F'});styleMap.set(types.Blocking,{fillStyle:'#AAAAAA'});styleMap.set(types.Push,{fillStyle:'#8CDBff'});styleMap.set(types.Queueing,{fillStyle:'white',lineWidth:2,borderColor:'lightgrey'});styleMap.set(types.Receiving,{fillStyle:'#03A9F4',lineWidth:2,borderColor:'#03A9F4'});styleMap.set(types.Waiting,{fillStyle:'#00C853'});styleMap.set(types.ReceivingPush,{fillStyle:'#03A9F4'});styleMap.set(types.ServiceWorker,{fillStyle:'orange'});styleMap.set(types.ServiceWorkerPreparation,{fillStyle:'orange'});return styleMap;}
static _buildResourceTypeStyle(){const baseResourceTypeColors=new Map([['document','hsl(215, 100%, 80%)'],['font','hsl(8, 100%, 80%)'],['media','hsl(90, 50%, 80%)'],['image','hsl(90, 50%, 80%)'],['script','hsl(31, 100%, 80%)'],['stylesheet','hsl(272, 64%, 80%)'],['texttrack','hsl(8, 100%, 80%)'],['websocket','hsl(0, 0%, 95%)'],['xhr','hsl(53, 100%, 80%)'],['fetch','hsl(53, 100%, 80%)'],['other','hsl(0, 0%, 95%)'],]);const waitingStyleMap=new Map();const downloadingStyleMap=new Map();for(const resourceType of Object.values(ResourceType.resourceTypes)){let color=baseResourceTypeColors.get(resourceType.name());if(!color){color=baseResourceTypeColors.get('other');}
const borderColor=toBorderColor(color);waitingStyleMap.set(resourceType,{fillStyle:toWaitingColor(color),lineWidth:1,borderColor:borderColor});downloadingStyleMap.set(resourceType,{fillStyle:color,lineWidth:1,borderColor:borderColor});}
return[waitingStyleMap,downloadingStyleMap];function toBorderColor(color){const parsedColor=Color.Color.parse(color);const hsla=parsedColor.hsla();hsla[1]/=2;hsla[2]-=Math.min(hsla[2],0.2);return parsedColor.asString(null);}
function toWaitingColor(color){const parsedColor=Color.Color.parse(color);const hsla=parsedColor.hsla();hsla[2]*=1.1;return parsedColor.asString(null);}}
_resetPaths(){this._pathForStyle.clear();this._pathForStyle.set(this._wiskerStyle,new Path2D());this._styleForTimeRangeName.forEach(style=>this._pathForStyle.set(style,new Path2D()));this._styleForWaitingResourceType.forEach(style=>this._pathForStyle.set(style,new Path2D()));this._styleForDownloadingResourceType.forEach(style=>this._pathForStyle.set(style,new Path2D()));this._pathForStyle.set(this._hoverDetailsStyle,new Path2D());}
willHide(){this._popoverHelper.hidePopover();}
wasShown(){this.update();}
_onMouseMove(event){this._setHoveredNode(this.getNodeFromPoint(event.offsetX,event.offsetY),event.shiftKey);}
_onClick(event){const handled=this._setSelectedNode(this.getNodeFromPoint(event.offsetX,event.offsetY));if(handled){event.consume(true);}}
_getPopoverRequest(event){if(!this._hoveredNode){return null;}
const request=this._hoveredNode.request();if(!request){return null;}
const useTimingBars=!Settings.Settings.instance().moduleSetting('networkColorCodeResourceTypes').get()&&!this._calculator.startAtZero;let range;let start;let end;if(useTimingBars){range=RequestTimingView.calculateRequestTimeRanges(request,0).find(data=>data.name===RequestTimeRangeNames.Total);start=this._timeToPosition(range.start);end=this._timeToPosition(range.end);}else{range=this._getSimplifiedBarRange(request,0);start=range.start;end=range.end;}
if(end-start<50){const halfWidth=(end-start)/2;start=start+halfWidth-25;end=end-halfWidth+25;}
if(event.clientX<this._canvasPosition.left+start||event.clientX>this._canvasPosition.left+end){return null;}
const rowIndex=this._nodes.findIndex(node=>node.hovered());const barHeight=this._getBarHeight(range.name);const y=this._headerHeight+(this._rowHeight*rowIndex-this._scrollTop)+((this._rowHeight-barHeight)/2);if(event.clientY<this._canvasPosition.top+y||event.clientY>this._canvasPosition.top+y+barHeight){return null;}
const anchorBox=this.element.boxInWindow();anchorBox.x+=start;anchorBox.y+=y;anchorBox.width=end-start;anchorBox.height=barHeight;return{box:anchorBox,show:popover=>{const content=RequestTimingView.createTimingTable((request),this._calculator);popover.contentElement.appendChild(content);return Promise.resolve(true);}};}
_setHoveredNode(node,highlightInitiatorChain){if(this._hoveredNode){this._hoveredNode.setHovered(false,false);}
this._hoveredNode=node;if(this._hoveredNode){this._hoveredNode.setHovered(true,highlightInitiatorChain);}}
_setSelectedNode(node){if(node&&node.dataGrid){node.select();node.dataGrid.element.focus();return true;}
return false;}
setRowHeight(height){this._rawRowHeight=height;this._updateRowHeight();}
_updateRowHeight(){this._rowHeight=Math.round(this._rawRowHeight*window.devicePixelRatio)/window.devicePixelRatio;}
setHeaderHeight(height){this._headerHeight=height;}
setRightPadding(padding){this._rightPadding=padding;this._calculateCanvasSize();}
setCalculator(calculator){this._calculator=calculator;}
getNodeFromPoint(x,y){if(y<=this._headerHeight){return null;}
return this._nodes[Math.floor((this._scrollTop+y-this._headerHeight)/this._rowHeight)];}
scheduleDraw(){if(this._updateRequestID){return;}
this._updateRequestID=this.element.window().requestAnimationFrame(()=>this.update());}
update(scrollTop,eventDividers,nodes){if(scrollTop!==undefined&&this._scrollTop!==scrollTop){this._popoverHelper.hidePopover();this._scrollTop=scrollTop;}
if(nodes){this._nodes=nodes;this._calculateCanvasSize();}
if(eventDividers!==undefined){this._eventDividers=eventDividers;}
if(this._updateRequestID){this.element.window().cancelAnimationFrame(this._updateRequestID);delete this._updateRequestID;}
this._startTime=this._calculator.minimumBoundary();this._endTime=this._calculator.maximumBoundary();this._resetCanvas();this._resetPaths();this._textLayers=[];this._draw();}
_resetCanvas(){const ratio=window.devicePixelRatio;this._canvas.width=this._offsetWidth*ratio;this._canvas.height=this._offsetHeight*ratio;this._canvas.style.width=this._offsetWidth+'px';this._canvas.style.height=this._offsetHeight+'px';}
onResize(){super.onResize();this._updateRowHeight();this._calculateCanvasSize();this.scheduleDraw();}
_calculateCanvasSize(){this._offsetWidth=this.contentElement.offsetWidth-this._rightPadding;this._offsetHeight=this.contentElement.offsetHeight;this._calculator.setDisplayWidth(this._offsetWidth);this._canvasPosition=this._canvas.getBoundingClientRect();}
_timeToPosition(time){const availableWidth=this._offsetWidth-this._leftPadding;const timeToPixel=availableWidth/(this._endTime-this._startTime);return Math.floor(this._leftPadding+(time-this._startTime)*timeToPixel);}
_didDrawForTest(){}
_draw(){const useTimingBars=!Settings.Settings.instance().moduleSetting('networkColorCodeResourceTypes').get()&&!this._calculator.startAtZero;const nodes=this._nodes;const context=this._canvas.getContext('2d');context.save();context.scale(window.devicePixelRatio,window.devicePixelRatio);context.translate(0,this._headerHeight);context.rect(0,0,this._offsetWidth,this._offsetHeight);context.clip();const firstRequestIndex=Math.floor(this._scrollTop/this._rowHeight);const lastRequestIndex=Math.min(nodes.length,firstRequestIndex+Math.ceil(this._offsetHeight/this._rowHeight));for(let i=firstRequestIndex;i<lastRequestIndex;i++){const rowOffset=this._rowHeight*i;const node=nodes[i];this._decorateRow(context,node,rowOffset-this._scrollTop);let drawNodes=[];if(node.hasChildren()&&!node.expanded){drawNodes=(node.flatChildren());}
drawNodes.push(node);for(const drawNode of drawNodes){if(useTimingBars){this._buildTimingBarLayers(drawNode,rowOffset-this._scrollTop);}else{this._buildSimplifiedBarLayers(context,drawNode,rowOffset-this._scrollTop);}}}
this._drawLayers(context);context.save();context.fillStyle=self.UI.themeSupport.patchColorText('#888',UIUtils.ThemeSupport.ColorUsage.Foreground);for(const textData of this._textLayers){context.fillText(textData.text,textData.x,textData.y);}
context.restore();this._drawEventDividers(context);context.restore();const freeZoneAtLeft=75;const freeZoneAtRight=18;const dividersData=TimelineGrid.TimelineGrid.calculateGridOffsets(this._calculator);TimelineGrid.TimelineGrid.drawCanvasGrid(context,dividersData);TimelineGrid.TimelineGrid.drawCanvasHeaders(context,dividersData,time=>this._calculator.formatValue(time,dividersData.precision),this._fontSize,this._headerHeight,freeZoneAtLeft);context.clearRect(this._offsetWidth-freeZoneAtRight,0,freeZoneAtRight,this._headerHeight);this._didDrawForTest();}
_drawLayers(context){for(const entry of this._pathForStyle){const style=(entry[0]);const path=(entry[1]);context.save();context.beginPath();if(style.lineWidth){context.lineWidth=style.lineWidth;context.strokeStyle=style.borderColor;context.stroke(path);}
if(style.fillStyle){context.fillStyle=style.fillStyle;context.fill(path);}
context.restore();}}
_drawEventDividers(context){context.save();context.lineWidth=1;for(const color of this._eventDividers.keys()){context.strokeStyle=color;for(const time of this._eventDividers.get(color)){context.beginPath();const x=this._timeToPosition(time);context.moveTo(x,0);context.lineTo(x,this._offsetHeight);}
context.stroke();}
context.restore();}
_getBarHeight(type){const types=RequestTimeRangeNames;switch(type){case types.Connecting:case types.SSL:case types.DNS:case types.Proxy:case types.Blocking:case types.Push:case types.Queueing:return 7;default:return 13;}}
_getSimplifiedBarRange(request,borderOffset){const drawWidth=this._offsetWidth-this._leftPadding;const percentages=this._calculator.computeBarGraphPercentages(request);return{start:this._leftPadding+Math.floor((percentages.start/100)*drawWidth)+borderOffset,mid:this._leftPadding+Math.floor((percentages.middle/100)*drawWidth)+borderOffset,end:this._leftPadding+Math.floor((percentages.end/100)*drawWidth)+borderOffset};}
_buildSimplifiedBarLayers(context,node,y){const request=node.request();if(!request){return;}
const borderWidth=1;const borderOffset=borderWidth%2===0?0:0.5;const ranges=this._getSimplifiedBarRange(request,borderOffset);const height=this._getBarHeight();y+=Math.floor(this._rowHeight/2-height/2+borderWidth)-borderWidth/2;const waitingStyle=this._styleForWaitingResourceType.get(request.resourceType());const waitingPath=this._pathForStyle.get(waitingStyle);waitingPath.rect(ranges.start,y,ranges.mid-ranges.start,height-borderWidth);const barWidth=Math.max(2,ranges.end-ranges.mid);const downloadingStyle=this._styleForDownloadingResourceType.get(request.resourceType());const downloadingPath=this._pathForStyle.get(downloadingStyle);downloadingPath.rect(ranges.mid,y,barWidth,height-borderWidth);let labels=null;if(node.hovered()){labels=this._calculator.computeBarGraphLabels(request);const barDotLineLength=10;const leftLabelWidth=context.measureText(labels.left).width;const rightLabelWidth=context.measureText(labels.right).width;const hoverLinePath=this._pathForStyle.get(this._hoverDetailsStyle);if(leftLabelWidth<ranges.mid-ranges.start){const midBarX=ranges.start+(ranges.mid-ranges.start-leftLabelWidth)/2;this._textLayers.push({text:labels.left,x:midBarX,y:y+this._fontSize});}else if(barDotLineLength+leftLabelWidth+this._leftPadding<ranges.start){this._textLayers.push({text:labels.left,x:ranges.start-leftLabelWidth-barDotLineLength-1,y:y+this._fontSize});hoverLinePath.moveTo(ranges.start-barDotLineLength,y+Math.floor(height/2));hoverLinePath.arc(ranges.start,y+Math.floor(height/2),2,0,2*Math.PI);hoverLinePath.moveTo(ranges.start-barDotLineLength,y+Math.floor(height/2));hoverLinePath.lineTo(ranges.start,y+Math.floor(height/2));}
const endX=ranges.mid+barWidth+borderOffset;if(rightLabelWidth<endX-ranges.mid){const midBarX=ranges.mid+(endX-ranges.mid-rightLabelWidth)/2;this._textLayers.push({text:labels.right,x:midBarX,y:y+this._fontSize});}else if(endX+barDotLineLength+rightLabelWidth<this._offsetWidth-this._leftPadding){this._textLayers.push({text:labels.right,x:endX+barDotLineLength+1,y:y+this._fontSize});hoverLinePath.moveTo(endX,y+Math.floor(height/2));hoverLinePath.arc(endX,y+Math.floor(height/2),2,0,2*Math.PI);hoverLinePath.moveTo(endX,y+Math.floor(height/2));hoverLinePath.lineTo(endX+barDotLineLength,y+Math.floor(height/2));}}
if(!this._calculator.startAtZero){const queueingRange=RequestTimingView.calculateRequestTimeRanges(request,0).find(data=>data.name===RequestTimeRangeNames.Total);const leftLabelWidth=labels?context.measureText(labels.left).width:0;const leftTextPlacedInBar=leftLabelWidth<ranges.mid-ranges.start;const wiskerTextPadding=13;const textOffset=(labels&&!leftTextPlacedInBar)?leftLabelWidth+wiskerTextPadding:0;const queueingStart=this._timeToPosition(queueingRange.start);if(ranges.start-textOffset>queueingStart){const wiskerPath=this._pathForStyle.get(this._wiskerStyle);wiskerPath.moveTo(queueingStart,y+Math.floor(height/2));wiskerPath.lineTo(ranges.start-textOffset,y+Math.floor(height/2));const wiskerHeight=height/2;wiskerPath.moveTo(queueingStart+borderOffset,y+wiskerHeight/2);wiskerPath.lineTo(queueingStart+borderOffset,y+height-wiskerHeight/2-1);}}}
_buildTimingBarLayers(node,y){const request=node.request();if(!request){return;}
const ranges=RequestTimingView.calculateRequestTimeRanges(request,0);for(const range of ranges){if(range.name===RequestTimeRangeNames.Total||range.name===RequestTimeRangeNames.Sending||range.end-range.start===0){continue;}
const style=this._styleForTimeRangeName.get(range.name);const path=this._pathForStyle.get(style);const lineWidth=style.lineWidth||0;const height=this._getBarHeight(range.name);const middleBarY=y+Math.floor(this._rowHeight/2-height/2)+lineWidth/2;const start=this._timeToPosition(range.start);const end=this._timeToPosition(range.end);path.rect(start,middleBarY,end-start,height-lineWidth);}}
_decorateRow(context,node,y){if(!this._computedDatagridStyle&&node.dataGrid){this._computedDatagridStyle=window.getComputedStyle(node.dataGrid.element);}
if(!this._computedDatagridStyle){context.restore();return;}
const nodeBgColor=node.backgroundColor();context.save();context.beginPath();context.fillStyle=this._computedDatagridStyle.getPropertyValue(nodeBgColor);context.rect(0,y,this._offsetWidth,this._rowHeight);context.fill();context.restore();}}
let _TextLayer;let _LayerStyle;var NetworkWaterfallColumn$1=Object.freeze({__proto__:null,NetworkWaterfallColumn:NetworkWaterfallColumn,_TextLayer:_TextLayer,_LayerStyle:_LayerStyle});class NetworkLogViewColumns{constructor(networkLogView,timeCalculator,durationCalculator,networkLogLargeRowsSetting){this._networkLogView=networkLogView;this._persistantSettings=Settings.Settings.instance().createSetting('networkLogColumns',{});this._networkLogLargeRowsSetting=networkLogLargeRowsSetting;this._networkLogLargeRowsSetting.addChangeListener(this._updateRowsSize,this);this._eventDividers=new Map();this._eventDividersShown=false;this._gridMode=true;this._columns=[];this._waterfallRequestsAreStale=false;this._waterfallScrollerWidthIsStale=true;this._popupLinkifier=new Linkifier.Linkifier();this._calculatorsMap=new Map();this._calculatorsMap.set(_calculatorTypes.Time,timeCalculator);this._calculatorsMap.set(_calculatorTypes.Duration,durationCalculator);this._lastWheelTime=0;this._setupDataGrid();this._setupWaterfall();}
static _convertToDataGridDescriptor(columnConfig){return({id:columnConfig.id,title:columnConfig.title,sortable:columnConfig.sortable,align:columnConfig.align,nonSelectable:columnConfig.nonSelectable,weight:columnConfig.weight,allowInSortByEvenWhenHidden:columnConfig.allowInSortByEvenWhenHidden,});}
wasShown(){this._updateRowsSize();}
willHide(){this._popoverHelper.hidePopover();}
reset(){if(this._popoverHelper){this._popoverHelper.hidePopover();}
this._eventDividers.clear();}
_setupDataGrid(){const defaultColumns=_defaultColumns;const defaultColumnConfig=_defaultColumnConfig;this._columns=([]);for(const currentConfigColumn of defaultColumns){const descriptor=Object.assign({},defaultColumnConfig,currentConfigColumn);const columnConfig=(descriptor);columnConfig.id=columnConfig.id;if(columnConfig.subtitle){columnConfig.titleDOMFragment=this._makeHeaderFragment(columnConfig.title,columnConfig.subtitle);}
this._columns.push(columnConfig);}
this._loadCustomColumnsAndSettings();this._popoverHelper=new PopoverHelper.PopoverHelper(this._networkLogView.element,this._getPopoverRequest.bind(this));this._popoverHelper.setHasPadding(true);this._popoverHelper.setTimeout(300,300);this._dataGrid=new SortableDataGrid.SortableDataGrid({displayName:ls`Network Log`,columns:this._columns.map(NetworkLogViewColumns._convertToDataGridDescriptor)});this._dataGrid.element.addEventListener('mousedown',event=>{if(!this._dataGrid.selectedNode&&event.button){event.consume();}},true);this._dataGridScroller=this._dataGrid.scrollContainer;this._updateColumns();this._dataGrid.addEventListener(DataGrid.Events.SortingChanged,this._sortHandler,this);this._dataGrid.setHeaderContextMenuCallback(this._innerHeaderContextMenu.bind(this));this._activeWaterfallSortId=WaterfallSortIds.StartTime;this._dataGrid.markColumnAsSortedBy(_initialSortColumn,DataGrid.Order.Ascending);this._splitWidget=new SplitWidget.SplitWidget(true,true,'networkPanelSplitViewWaterfall',200);const widget=this._dataGrid.asWidget();widget.setMinimumSize(150,0);this._splitWidget.setMainWidget(widget);}
_setupWaterfall(){this._waterfallColumn=new NetworkWaterfallColumn(this._networkLogView.calculator());this._waterfallColumn.element.addEventListener('contextmenu',handleContextMenu.bind(this));this._waterfallColumn.element.addEventListener('mousewheel',this._onMouseWheel.bind(this,false),{passive:true});this._dataGridScroller.addEventListener('mousewheel',this._onMouseWheel.bind(this,true),true);this._waterfallScroller=this._waterfallColumn.contentElement.createChild('div','network-waterfall-v-scroll');this._waterfallScrollerContent=this._waterfallScroller.createChild('div','network-waterfall-v-scroll-content');this._dataGrid.addEventListener(DataGrid.Events.PaddingChanged,()=>{this._waterfallScrollerWidthIsStale=true;this._syncScrollers();});this._dataGrid.addEventListener(ViewportDataGrid.Events.ViewportCalculated,this._redrawWaterfallColumn.bind(this));this._createWaterfallHeader();this._waterfallColumn.contentElement.classList.add('network-waterfall-view');this._waterfallColumn.setMinimumSize(100,0);this._splitWidget.setSidebarWidget(this._waterfallColumn);this.switchViewMode(false);function handleContextMenu(event){const node=this._waterfallColumn.getNodeFromPoint(event.offsetX,event.offsetY);if(!node){return;}
const request=node.request();if(!request){return;}
const contextMenu=new ContextMenu.ContextMenu(event);this._networkLogView.handleContextMenuForRequest(contextMenu,request);contextMenu.show();}}
_onMouseWheel(shouldConsume,event){if(shouldConsume){event.consume(true);}
const hasRecentWheel=Date.now()-this._lastWheelTime<80;this._activeScroller.scrollBy({top:-event.wheelDeltaY,behavior:hasRecentWheel?'instant':'smooth'});this._syncScrollers();this._lastWheelTime=Date.now();}
_syncScrollers(){if(!this._waterfallColumn.isShowing()){return;}
this._waterfallScrollerContent.style.height=this._dataGridScroller.scrollHeight+'px';this._updateScrollerWidthIfNeeded();this._dataGridScroller.scrollTop=this._waterfallScroller.scrollTop;}
_updateScrollerWidthIfNeeded(){if(this._waterfallScrollerWidthIsStale){this._waterfallScrollerWidthIsStale=false;this._waterfallColumn.setRightPadding(this._waterfallScroller.offsetWidth-this._waterfallScrollerContent.offsetWidth);}}
_redrawWaterfallColumn(){if(!this._waterfallRequestsAreStale){this._updateScrollerWidthIfNeeded();this._waterfallColumn.update(this._activeScroller.scrollTop,this._eventDividersShown?this._eventDividers:undefined);return;}
this._syncScrollers();const nodes=this._networkLogView.flatNodesList();this._waterfallColumn.update(this._activeScroller.scrollTop,this._eventDividers,nodes);}
_createWaterfallHeader(){this._waterfallHeaderElement=this._waterfallColumn.contentElement.createChild('div','network-waterfall-header');this._waterfallHeaderElement.addEventListener('click',waterfallHeaderClicked.bind(this));this._waterfallHeaderElement.addEventListener('contextmenu',event=>this._innerHeaderContextMenu(new ContextMenu.ContextMenu(event)));const innerElement=this._waterfallHeaderElement.createChild('div');innerElement.textContent=UIString.UIString('Waterfall');this._waterfallColumnSortIcon=Icon.Icon.create('','sort-order-icon');this._waterfallHeaderElement.createChild('div','sort-order-icon-container').appendChild(this._waterfallColumnSortIcon);function waterfallHeaderClicked(){const sortOrders=DataGrid.Order;const wasSortedByWaterfall=this._dataGrid.sortColumnId()==='waterfall';const wasSortedAscending=this._dataGrid.isSortOrderAscending();const sortOrder=wasSortedByWaterfall&&wasSortedAscending?sortOrders.Descending:sortOrders.Ascending;this._dataGrid.markColumnAsSortedBy('waterfall',sortOrder);this._sortHandler();}}
setCalculator(x){this._waterfallColumn.setCalculator(x);}
scheduleRefresh(){this._waterfallColumn.scheduleDraw();}
_updateRowsSize(){const largeRows=!!this._networkLogLargeRowsSetting.get();this._dataGrid.element.classList.toggle('small',!largeRows);this._dataGrid.scheduleUpdate();this._waterfallScrollerWidthIsStale=true;this._waterfallColumn.setRowHeight(largeRows?41:21);this._waterfallScroller.classList.toggle('small',!largeRows);this._waterfallHeaderElement.classList.toggle('small',!largeRows);window.requestAnimationFrame(()=>{this._waterfallColumn.setHeaderHeight(this._waterfallScroller.offsetTop);});}
show(element){this._splitWidget.show(element);}
setHidden(value){ARIAUtils.setHidden(this._splitWidget.element,value);}
dataGrid(){return this._dataGrid;}
sortByCurrentColumn(){this._sortHandler();}
_sortHandler(){const columnId=this._dataGrid.sortColumnId();this._networkLogView.removeAllNodeHighlights();this._waterfallRequestsAreStale=true;if(columnId==='waterfall'){if(this._dataGrid.sortOrder()===DataGrid.Order.Ascending){this._waterfallColumnSortIcon.setIconType('smallicon-triangle-up');}else{this._waterfallColumnSortIcon.setIconType('smallicon-triangle-down');}
const sortFunction=NetworkRequestNode.RequestPropertyComparator.bind(null,this._activeWaterfallSortId);this._dataGrid.sortNodes(sortFunction,!this._dataGrid.isSortOrderAscending());this._dataGridSortedForTest();return;}
this._waterfallColumnSortIcon.setIconType('');const columnConfig=this._columns.find(columnConfig=>columnConfig.id===columnId);if(!columnConfig||!columnConfig.sortingFunction){return;}
this._dataGrid.sortNodes(columnConfig.sortingFunction,!this._dataGrid.isSortOrderAscending());this._dataGridSortedForTest();}
_dataGridSortedForTest(){}
_updateColumns(){if(!this._dataGrid){return;}
const visibleColumns=({});if(this._gridMode){for(const columnConfig of this._columns){visibleColumns[columnConfig.id]=columnConfig.visible;}}else{const visibleColumn=this._columns.find(c=>c.hideableGroup==='path'&&c.visible);if(visibleColumn){visibleColumns[visibleColumn.id]=true;}else{visibleColumns.name=true;}}
this._dataGrid.setColumnsVisiblity(visibleColumns);}
switchViewMode(gridMode){if(this._gridMode===gridMode){return;}
this._gridMode=gridMode;if(gridMode){this._splitWidget.showBoth();this._activeScroller=this._waterfallScroller;this._waterfallScroller.scrollTop=this._dataGridScroller.scrollTop;this._dataGrid.setScrollContainer(this._waterfallScroller);}else{this._networkLogView.removeAllNodeHighlights();this._splitWidget.hideSidebar();this._activeScroller=this._dataGridScroller;this._dataGrid.setScrollContainer(this._dataGridScroller);}
this._networkLogView.element.classList.toggle('brief-mode',!gridMode);this._updateColumns();this._updateRowsSize();}
_toggleColumnVisibility(columnConfig){this._loadCustomColumnsAndSettings();columnConfig.visible=!columnConfig.visible;this._saveColumnsSettings();this._updateColumns();}
_saveColumnsSettings(){const saveableSettings={};for(const columnConfig of this._columns){saveableSettings[columnConfig.id]={visible:columnConfig.visible,title:columnConfig.title};}
this._persistantSettings.set(saveableSettings);}
_loadCustomColumnsAndSettings(){const savedSettings=this._persistantSettings.get();const columnIds=Object.keys(savedSettings);for(const columnId of columnIds){const setting=savedSettings[columnId];let columnConfig=this._columns.find(columnConfig=>columnConfig.id===columnId);if(!columnConfig){columnConfig=this._addCustomHeader(setting.title,columnId);}
if(columnConfig.hideable&&typeof setting.visible==='boolean'){columnConfig.visible=!!setting.visible;}
if(typeof setting.title==='string'){columnConfig.title=setting.title;}}}
_makeHeaderFragment(title,subtitle){const fragment=createDocumentFragment();fragment.createTextChild(title);const subtitleDiv=fragment.createChild('div','network-header-subtitle');subtitleDiv.createTextChild(subtitle);return fragment;}
_innerHeaderContextMenu(contextMenu){const columnConfigs=this._columns.filter(columnConfig=>columnConfig.hideable);const nonResponseHeaders=columnConfigs.filter(columnConfig=>!columnConfig.isResponseHeader);const hideableGroups=new Map();const nonResponseHeadersWithoutGroup=[];for(const columnConfig of nonResponseHeaders){if(!columnConfig.hideableGroup){nonResponseHeadersWithoutGroup.push(columnConfig);}else{const name=columnConfig.hideableGroup;if(!hideableGroups.has(name)){hideableGroups.set(name,[]);}
hideableGroups.get(name).push(columnConfig);}}
for(const group of hideableGroups.values()){const visibleColumns=group.filter(columnConfig=>columnConfig.visible);for(const columnConfig of group){const isDisabled=visibleColumns.length===1&&visibleColumns[0]===columnConfig;contextMenu.headerSection().appendCheckboxItem(columnConfig.title,this._toggleColumnVisibility.bind(this,columnConfig),columnConfig.visible,isDisabled);}
contextMenu.headerSection().appendSeparator();}
for(const columnConfig of nonResponseHeadersWithoutGroup){contextMenu.headerSection().appendCheckboxItem(columnConfig.title,this._toggleColumnVisibility.bind(this,columnConfig),columnConfig.visible);}
const responseSubMenu=contextMenu.footerSection().appendSubMenuItem(UIString.UIString('Response Headers'));const responseHeaders=columnConfigs.filter(columnConfig=>columnConfig.isResponseHeader);for(const columnConfig of responseHeaders){responseSubMenu.defaultSection().appendCheckboxItem(columnConfig.title,this._toggleColumnVisibility.bind(this,columnConfig),columnConfig.visible);}
responseSubMenu.footerSection().appendItem(UIString.UIString('Manage Header Columns…'),this._manageCustomHeaderDialog.bind(this));const waterfallSortIds=WaterfallSortIds;const waterfallSubMenu=contextMenu.footerSection().appendSubMenuItem(UIString.UIString('Waterfall'));waterfallSubMenu.defaultSection().appendCheckboxItem(UIString.UIString('Start Time'),setWaterfallMode.bind(this,waterfallSortIds.StartTime),this._activeWaterfallSortId===waterfallSortIds.StartTime);waterfallSubMenu.defaultSection().appendCheckboxItem(UIString.UIString('Response Time'),setWaterfallMode.bind(this,waterfallSortIds.ResponseTime),this._activeWaterfallSortId===waterfallSortIds.ResponseTime);waterfallSubMenu.defaultSection().appendCheckboxItem(UIString.UIString('End Time'),setWaterfallMode.bind(this,waterfallSortIds.EndTime),this._activeWaterfallSortId===waterfallSortIds.EndTime);waterfallSubMenu.defaultSection().appendCheckboxItem(UIString.UIString('Total Duration'),setWaterfallMode.bind(this,waterfallSortIds.Duration),this._activeWaterfallSortId===waterfallSortIds.Duration);waterfallSubMenu.defaultSection().appendCheckboxItem(UIString.UIString('Latency'),setWaterfallMode.bind(this,waterfallSortIds.Latency),this._activeWaterfallSortId===waterfallSortIds.Latency);function setWaterfallMode(sortId){let calculator=this._calculatorsMap.get(_calculatorTypes.Time);const waterfallSortIds=WaterfallSortIds;if(sortId===waterfallSortIds.Duration||sortId===waterfallSortIds.Latency){calculator=this._calculatorsMap.get(_calculatorTypes.Duration);}
this._networkLogView.setCalculator(calculator);this._activeWaterfallSortId=sortId;this._dataGrid.markColumnAsSortedBy('waterfall',DataGrid.Order.Ascending);this._sortHandler();}}
_manageCustomHeaderDialog(){const customHeaders=[];for(const columnConfig of this._columns){if(columnConfig.isResponseHeader){customHeaders.push({title:columnConfig.title,editable:columnConfig.isCustomHeader});}}
const manageCustomHeaders=new NetworkManageCustomHeadersView(customHeaders,headerTitle=>!!this._addCustomHeader(headerTitle),this._changeCustomHeader.bind(this),this._removeCustomHeader.bind(this));const dialog=new Dialog.Dialog();manageCustomHeaders.show(dialog.contentElement);dialog.setSizeBehavior(GlassPane.SizeBehavior.MeasureContent);dialog.show(this._networkLogView.element);}
_removeCustomHeader(headerId){headerId=headerId.toLowerCase();const index=this._columns.findIndex(columnConfig=>columnConfig.id===headerId);if(index===-1){return false;}
this._columns.splice(index,1);this._dataGrid.removeColumn(headerId);this._saveColumnsSettings();this._updateColumns();return true;}
_addCustomHeader(headerTitle,headerId,index){if(!headerId){headerId=headerTitle.toLowerCase();}
if(index===undefined){index=this._columns.length-1;}
const currentColumnConfig=this._columns.find(columnConfig=>columnConfig.id===headerId);if(currentColumnConfig){return null;}
const columnConfigBase=Object.assign({},_defaultColumnConfig,{id:headerId,title:headerTitle,isResponseHeader:true,isCustomHeader:true,visible:true,sortingFunction:NetworkRequestNode.ResponseHeaderStringComparator.bind(null,headerId)});const columnConfig=(columnConfigBase);this._columns.splice(index,0,columnConfig);if(this._dataGrid){this._dataGrid.addColumn(NetworkLogViewColumns._convertToDataGridDescriptor(columnConfig),index);}
this._saveColumnsSettings();this._updateColumns();return columnConfig;}
_changeCustomHeader(oldHeaderId,newHeaderTitle,newHeaderId){if(!newHeaderId){newHeaderId=newHeaderTitle.toLowerCase();}
oldHeaderId=oldHeaderId.toLowerCase();const oldIndex=this._columns.findIndex(columnConfig=>columnConfig.id===oldHeaderId);const oldColumnConfig=this._columns[oldIndex];const currentColumnConfig=this._columns.find(columnConfig=>columnConfig.id===newHeaderId);if(!oldColumnConfig||(currentColumnConfig&&oldHeaderId!==newHeaderId)){return false;}
this._removeCustomHeader(oldHeaderId);this._addCustomHeader(newHeaderTitle,newHeaderId,oldIndex);return true;}
_getPopoverRequest(event){if(!this._gridMode){return null;}
const hoveredNode=this._networkLogView.hoveredNode();if(!hoveredNode){return null;}
const anchor=event.target.enclosingNodeOrSelfWithClass('network-script-initiated');if(!anchor){return null;}
const request=hoveredNode.request();if(!request){return null;}
return{box:anchor.boxInWindow(),show:popover=>{const content=RequestInitiatorView.createStackTracePreview((request),this._popupLinkifier,false,()=>popover.setSizeBehavior(GlassPane.SizeBehavior.MeasureContent));popover.contentElement.appendChild(content.element);return Promise.resolve(true);},hide:this._popupLinkifier.reset.bind(this._popupLinkifier)};}
addEventDividers(times,className){let color='transparent';switch(className){case'network-dcl-divider':color='#0867CB';break;case'network-load-divider':color='#B31412';break;default:return;}
const currentTimes=this._eventDividers.get(color)||[];this._eventDividers.set(color,currentTimes.concat(times));this._networkLogView.scheduleRefresh();}
hideEventDividers(){this._eventDividersShown=true;this._redrawWaterfallColumn();}
showEventDividers(){this._eventDividersShown=false;this._redrawWaterfallColumn();}
selectFilmStripFrame(time){this._eventDividers.set(_filmStripDividerColor,[time]);this._redrawWaterfallColumn();}
clearFilmStripFrame(){this._eventDividers.delete(_filmStripDividerColor);this._redrawWaterfallColumn();}}
const _initialSortColumn='waterfall';const _calculatorTypes={Duration:'Duration',Time:'Time'};const _defaultColumnConfig={subtitle:null,visible:false,weight:6,sortable:true,hideable:true,hideableGroup:null,nonSelectable:false,isResponseHeader:false,isCustomHeader:false,allowInSortByEvenWhenHidden:false};const _defaultColumns=[{id:'name',title:UIString.UIString('Name'),subtitle:UIString.UIString('Path'),visible:true,weight:20,hideable:true,hideableGroup:'path',sortingFunction:NetworkRequestNode.NameComparator},{id:'path',title:ls`Path`,hideable:true,hideableGroup:'path',sortingFunction:NetworkRequestNode.RequestPropertyComparator.bind(null,'path')},{id:'url',title:ls`Url`,hideable:true,hideableGroup:'path',sortingFunction:NetworkRequestNode.RequestPropertyComparator.bind(null,'url')},{id:'method',title:UIString.UIString('Method'),sortingFunction:NetworkRequestNode.RequestPropertyComparator.bind(null,'requestMethod')},{id:'status',title:UIString.UIString('Status'),visible:true,subtitle:UIString.UIString('Text'),sortingFunction:NetworkRequestNode.RequestPropertyComparator.bind(null,'statusCode')},{id:'protocol',title:UIString.UIString('Protocol'),sortingFunction:NetworkRequestNode.RequestPropertyComparator.bind(null,'protocol')},{id:'scheme',title:UIString.UIString('Scheme'),sortingFunction:NetworkRequestNode.RequestPropertyComparator.bind(null,'scheme')},{id:'domain',title:UIString.UIString('Domain'),sortingFunction:NetworkRequestNode.RequestPropertyComparator.bind(null,'domain')},{id:'remoteaddress',title:UIString.UIString('Remote Address'),weight:10,align:DataGrid.Align.Right,sortingFunction:NetworkRequestNode.RemoteAddressComparator},{id:'type',title:UIString.UIString('Type'),visible:true,sortingFunction:NetworkRequestNode.TypeComparator},{id:'initiator',title:UIString.UIString('Initiator'),visible:true,weight:10,sortingFunction:NetworkRequestNode.InitiatorComparator},{id:'cookies',title:UIString.UIString('Cookies'),align:DataGrid.Align.Right,sortingFunction:NetworkRequestNode.RequestCookiesCountComparator},{id:'setcookies',title:UIString.UIString('Set Cookies'),align:DataGrid.Align.Right,sortingFunction:NetworkRequestNode.ResponseCookiesCountComparator},{id:'size',title:UIString.UIString('Size'),visible:true,subtitle:UIString.UIString('Content'),align:DataGrid.Align.Right,sortingFunction:NetworkRequestNode.SizeComparator},{id:'time',title:UIString.UIString('Time'),visible:true,subtitle:UIString.UIString('Latency'),align:DataGrid.Align.Right,sortingFunction:NetworkRequestNode.RequestPropertyComparator.bind(null,'duration')},{id:'priority',title:UIString.UIString('Priority'),sortingFunction:NetworkRequestNode.PriorityComparator},{id:'connectionid',title:UIString.UIString('Connection ID'),sortingFunction:NetworkRequestNode.RequestPropertyComparator.bind(null,'connectionId')},{id:'cache-control',isResponseHeader:true,title:UIString.UIString('Cache-Control'),sortingFunction:NetworkRequestNode.ResponseHeaderStringComparator.bind(null,'cache-control')},{id:'connection',isResponseHeader:true,title:ls`${'Connection'}`,sortingFunction:NetworkRequestNode.ResponseHeaderStringComparator.bind(null,'connection')},{id:'content-encoding',isResponseHeader:true,title:UIString.UIString('Content-Encoding'),sortingFunction:NetworkRequestNode.ResponseHeaderStringComparator.bind(null,'content-encoding')},{id:'content-length',isResponseHeader:true,title:UIString.UIString('Content-Length'),align:DataGrid.Align.Right,sortingFunction:NetworkRequestNode.ResponseHeaderNumberComparator.bind(null,'content-length')},{id:'etag',isResponseHeader:true,title:UIString.UIString('ETag'),sortingFunction:NetworkRequestNode.ResponseHeaderStringComparator.bind(null,'etag')},{id:'keep-alive',isResponseHeader:true,title:UIString.UIString('Keep-Alive'),sortingFunction:NetworkRequestNode.ResponseHeaderStringComparator.bind(null,'keep-alive')},{id:'last-modified',isResponseHeader:true,title:UIString.UIString('Last-Modified'),sortingFunction:NetworkRequestNode.ResponseHeaderDateComparator.bind(null,'last-modified')},{id:'server',isResponseHeader:true,title:UIString.UIString('Server'),sortingFunction:NetworkRequestNode.ResponseHeaderStringComparator.bind(null,'server')},{id:'vary',isResponseHeader:true,title:UIString.UIString('Vary'),sortingFunction:NetworkRequestNode.ResponseHeaderStringComparator.bind(null,'vary')},{id:'waterfall',title:ls`Waterfall`,visible:false,hideable:false,allowInSortByEvenWhenHidden:true}];const _filmStripDividerColor='#fccc49';const WaterfallSortIds={StartTime:'startTime',ResponseTime:'responseReceivedTime',EndTime:'endTime',Duration:'duration',Latency:'latency'};let Descriptor;var NetworkLogViewColumns$1=Object.freeze({__proto__:null,NetworkLogViewColumns:NetworkLogViewColumns,_initialSortColumn:_initialSortColumn,_calculatorTypes:_calculatorTypes,_defaultColumnConfig:_defaultColumnConfig,_defaultColumns:_defaultColumns,_filmStripDividerColor:_filmStripDividerColor,WaterfallSortIds:WaterfallSortIds,Descriptor:Descriptor});class NetworkLogView extends Widget.VBox{constructor(filterBar,progressBarContainer,networkLogLargeRowsSetting){super();this.setMinimumSize(50,64);this.registerRequiredCSS('network/networkLogView.css');this.element.id='network-container';this.element.classList.add('no-node-selected');this._networkHideDataURLSetting=Settings.Settings.instance().createSetting('networkHideDataURL',false);this._networkShowIssuesOnlySetting=Settings.Settings.instance().createSetting('networkShowIssuesOnly',false);this._networkOnlyBlockedRequestsSetting=Settings.Settings.instance().createSetting('networkOnlyBlockedRequests',false);this._networkResourceTypeFiltersSetting=Settings.Settings.instance().createSetting('networkResourceTypeFilters',{});this._rawRowHeight=0;this._progressBarContainer=progressBarContainer;this._networkLogLargeRowsSetting=networkLogLargeRowsSetting;this._networkLogLargeRowsSetting.addChangeListener(updateRowHeight.bind(this),this);function updateRowHeight(){this._rawRowHeight=!!this._networkLogLargeRowsSetting.get()?41:21;this._rowHeight=this._computeRowHeight();}
this._rawRowHeight=0;this._rowHeight=0;updateRowHeight.call(this);this._timeCalculator=new NetworkTransferTimeCalculator();this._durationCalculator=new NetworkTransferDurationCalculator();this._calculator=this._timeCalculator;this._columns=new NetworkLogViewColumns(this,this._timeCalculator,this._durationCalculator,networkLogLargeRowsSetting);this._columns.show(this.element);this._staleRequests=new Set();this._mainRequestLoadTime=-1;this._mainRequestDOMContentLoadedTime=-1;this._highlightedSubstringChanges=[];this._filters=[];this._timeFilter=null;this._hoveredNode=null;this._recordingHint=null;this._refreshRequestId=null;this._highlightedNode=null;this.linkifier=new Linkifier.Linkifier();this._recording=false;this._needsRefresh=false;this._headerHeight=0;this._groupLookups=new Map();this._groupLookups.set('Frame',new NetworkFrameGrouper(this));this._activeGroupLookup=null;this._textFilterUI=new FilterBar.TextFilterUI();this._textFilterUI.addEventListener(FilterBar.FilterUI.Events.FilterChanged,this._filterChanged,this);filterBar.addFilter(this._textFilterUI);this._dataURLFilterUI=new FilterBar.CheckboxFilterUI('hide-data-url',UIString.UIString('Hide data URLs'),true,this._networkHideDataURLSetting);this._dataURLFilterUI.addEventListener(FilterBar.FilterUI.Events.FilterChanged,this._filterChanged.bind(this),this);this._dataURLFilterUI.element().title=ls`Hides data: and blob: URLs`;filterBar.addFilter(this._dataURLFilterUI);const filterItems=Object.values(ResourceType.resourceCategories).map(category=>({name:category.title,label:category.shortTitle,title:category.title}));this._resourceCategoryFilterUI=new FilterBar.NamedBitSetFilterUI(filterItems,this._networkResourceTypeFiltersSetting);ARIAUtils.setAccessibleName(this._resourceCategoryFilterUI.element(),ls`Resource types to include`);this._resourceCategoryFilterUI.addEventListener(FilterBar.FilterUI.Events.FilterChanged,this._filterChanged.bind(this),this);filterBar.addFilter(this._resourceCategoryFilterUI);this._onlyIssuesFilterUI=new FilterBar.CheckboxFilterUI('only-show-issues',ls`Has blocked cookies`,true,this._networkShowIssuesOnlySetting);this._onlyIssuesFilterUI.addEventListener(FilterBar.FilterUI.Events.FilterChanged,this._filterChanged.bind(this),this);this._onlyIssuesFilterUI.element().title=ls`Only show requests with blocked response cookies`;filterBar.addFilter(this._onlyIssuesFilterUI);this._onlyBlockedRequestsUI=new FilterBar.CheckboxFilterUI('only-show-blocked-requests',ls`Blocked Requests`,true,this._networkOnlyBlockedRequestsSetting);this._onlyBlockedRequestsUI.addEventListener(FilterBar.FilterUI.Events.FilterChanged,this._filterChanged.bind(this),this);this._onlyBlockedRequestsUI.element().title=ls`Only show blocked requests`;filterBar.addFilter(this._onlyBlockedRequestsUI);this._filterParser=new TextUtils.FilterParser(_searchKeys);this._suggestionBuilder=new FilterSuggestionBuilder.FilterSuggestionBuilder(_searchKeys,NetworkLogView._sortSearchValues);this._resetSuggestionBuilder();this._dataGrid=this._columns.dataGrid();this._setupDataGrid();this._columns.sortByCurrentColumn();filterBar.filterButton().addEventListener(Toolbar.ToolbarButton.Events.Click,this._dataGrid.scheduleUpdate.bind(this._dataGrid,true));this._summaryToolbar=new Toolbar.Toolbar('network-summary-bar',this.element);new DropTarget.DropTarget(this.element,[DropTarget.Type.File],UIString.UIString('Drop HAR files here'),this._handleDrop.bind(this));Settings.Settings.instance().moduleSetting('networkColorCodeResourceTypes').addChangeListener(this._invalidateAllItems.bind(this,false),this);SDKModel.TargetManager.instance().observeModels(NetworkManager.NetworkManager,this);self.SDK.networkLog.addEventListener(NetworkLog.Events.RequestAdded,this._onRequestUpdated,this);self.SDK.networkLog.addEventListener(NetworkLog.Events.RequestUpdated,this._onRequestUpdated,this);self.SDK.networkLog.addEventListener(NetworkLog.Events.Reset,this._reset,this);this._updateGroupByFrame();Settings.Settings.instance().moduleSetting('network.group-by-frame').addChangeListener(()=>this._updateGroupByFrame());this._filterBar=filterBar;}
_updateGroupByFrame(){const value=Settings.Settings.instance().moduleSetting('network.group-by-frame').get();this._setGrouping(value?'Frame':null);}
static _sortSearchValues(key,values){if(key===FilterType.Priority){values.sort((a,b)=>{const aPriority=(NetworkPriorities.uiLabelToNetworkPriority(a));const bPriority=(NetworkPriorities.uiLabelToNetworkPriority(b));return NetworkPriorities.networkPriorityWeight(aPriority)-
NetworkPriorities.networkPriorityWeight(bPriority);});}else{values.sort();}}
static _negativeFilter(filter,request){return!filter(request);}
static _requestPathFilter(regex,request){if(!regex){return false;}
return regex.test(request.path()+'/'+request.name());}
static _subdomains(domain){const result=[domain];let indexOfPeriod=domain.indexOf('.');while(indexOfPeriod!==-1){result.push('*'+domain.substring(indexOfPeriod));indexOfPeriod=domain.indexOf('.',indexOfPeriod+1);}
return result;}
static _createRequestDomainFilter(value){function escapeForRegExp(string){return string.escapeForRegExp();}
const escapedPattern=value.split('*').map(escapeForRegExp).join('.*');return NetworkLogView._requestDomainFilter.bind(null,new RegExp('^'+escapedPattern+'$','i'));}
static _requestDomainFilter(regex,request){return regex.test(request.domain);}
static _runningRequestFilter(request){return!request.finished;}
static _fromCacheRequestFilter(request){return request.cached();}
static _interceptedByServiceWorkerFilter(request){return request.fetchedViaServiceWorker;}
static _initiatedByServiceWorkerFilter(request){return request.initiatedByServiceWorker();}
static _requestResponseHeaderFilter(value,request){return request.responseHeaderValue(value)!==undefined;}
static _requestMethodFilter(value,request){return request.requestMethod===value;}
static _requestPriorityFilter(value,request){return request.priority()===value;}
static _requestMimeTypeFilter(value,request){return request.mimeType===value;}
static _requestMixedContentFilter(value,request){if(value===MixedContentFilterValues.Displayed){return request.mixedContentType===Protocol.Security.MixedContentType.OptionallyBlockable;}
if(value===MixedContentFilterValues.Blocked){return request.mixedContentType===Protocol.Security.MixedContentType.Blockable&&request.wasBlocked();}
if(value===MixedContentFilterValues.BlockOverridden){return request.mixedContentType===Protocol.Security.MixedContentType.Blockable&&!request.wasBlocked();}
if(value===MixedContentFilterValues.All){return request.mixedContentType!==Protocol.Security.MixedContentType.None;}
return false;}
static _requestSchemeFilter(value,request){return request.scheme===value;}
static _requestCookieDomainFilter(value,request){return request.allCookiesIncludingBlockedOnes().some(cookie=>cookie.domain()===value);}
static _requestCookieNameFilter(value,request){return request.allCookiesIncludingBlockedOnes().some(cookie=>cookie.name()===value);}
static _requestCookiePathFilter(value,request){return request.allCookiesIncludingBlockedOnes().some(cookie=>cookie.path()===value);}
static _requestCookieValueFilter(value,request){return request.allCookiesIncludingBlockedOnes().some(cookie=>cookie.value()===value);}
static _requestSetCookieDomainFilter(value,request){return request.responseCookies.some(cookie=>cookie.domain()===value);}
static _requestSetCookieNameFilter(value,request){return request.responseCookies.some(cookie=>cookie.name()===value);}
static _requestSetCookieValueFilter(value,request){return request.responseCookies.some(cookie=>cookie.value()===value);}
static _requestSizeLargerThanFilter(value,request){return request.transferSize>=value;}
static _statusCodeFilter(value,request){return(''+request.statusCode)===value;}
static HTTPRequestsFilter(request){return request.parsedURL.isValid&&(request.scheme in HTTPSchemas);}
static _requestTimeFilter(windowStart,windowEnd,request){if(request.issueTime()>windowEnd){return false;}
if(request.endTime!==-1&&request.endTime<windowStart){return false;}
return true;}
static _copyRequestHeaders(request){InspectorFrontendHost.InspectorFrontendHostInstance.copyText(request.requestHeadersText());}
static _copyResponseHeaders(request){InspectorFrontendHost.InspectorFrontendHostInstance.copyText(request.responseHeadersText);}
static async _copyResponse(request){const contentData=await request.contentData();let content=contentData.content||'';if(!request.contentType().isTextType()){content=ContentProvider.contentAsDataURL(content,request.mimeType,contentData.encoded);}else if(contentData.encoded){content=window.atob(content);}
InspectorFrontendHost.InspectorFrontendHostInstance.copyText(content);}
_handleDrop(dataTransfer){const items=dataTransfer.items;if(!items.length){return;}
const entry=items[0].webkitGetAsEntry();if(entry.isDirectory){return;}
entry.file(this.onLoadFromFile.bind(this));}
async onLoadFromFile(file){const outputStream=new StringOutputStream.StringOutputStream();const reader=new FileUtils.ChunkedFileReader(file,10000000);const success=await reader.read(outputStream);if(!success){this._harLoadFailed(reader.error().message);return;}
let harRoot;try{harRoot=new HARFormat.HARRoot(JSON.parse(outputStream.data()));}catch(e){this._harLoadFailed(e);return;}
self.SDK.networkLog.importRequests(HARImporter.Importer.requestsFromHARLog(harRoot.log));}
_harLoadFailed(message){Console.Console.instance().error('Failed to load HAR file with following error: '+message);}
_setGrouping(groupKey){if(this._activeGroupLookup){this._activeGroupLookup.reset();}
const groupLookup=groupKey?this._groupLookups.get(groupKey)||null:null;this._activeGroupLookup=groupLookup;this._invalidateAllItems();}
_computeRowHeight(){return Math.round(this._rawRowHeight*window.devicePixelRatio)/window.devicePixelRatio;}
nodeForRequest(request){return request[_networkNodeSymbol]||null;}
headerHeight(){return this._headerHeight;}
setRecording(recording){this._recording=recording;this._updateSummaryBar();}
modelAdded(networkManager){if(networkManager.target().parentTarget()){return;}
const resourceTreeModel=networkManager.target().model(ResourceTreeModel.ResourceTreeModel);if(resourceTreeModel){resourceTreeModel.addEventListener(ResourceTreeModel.Events.Load,this._loadEventFired,this);resourceTreeModel.addEventListener(ResourceTreeModel.Events.DOMContentLoaded,this._domContentLoadedEventFired,this);}}
modelRemoved(networkManager){if(!networkManager.target().parentTarget()){const resourceTreeModel=networkManager.target().model(ResourceTreeModel.ResourceTreeModel);if(resourceTreeModel){resourceTreeModel.removeEventListener(ResourceTreeModel.Events.Load,this._loadEventFired,this);resourceTreeModel.removeEventListener(ResourceTreeModel.Events.DOMContentLoaded,this._domContentLoadedEventFired,this);}}}
setWindow(start,end){if(!start&&!end){this._timeFilter=null;this._timeCalculator.setWindow(null);}else{this._timeFilter=NetworkLogView._requestTimeFilter.bind(null,start,end);this._timeCalculator.setWindow(new NetworkTimeBoundary(start,end));}
this._filterRequests();}
resetFocus(){this._dataGrid.element.focus();}
_resetSuggestionBuilder(){this._suggestionBuilder.clear();this._suggestionBuilder.addItem(FilterType.Is,IsFilterType.Running);this._suggestionBuilder.addItem(FilterType.Is,IsFilterType.FromCache);this._suggestionBuilder.addItem(FilterType.Is,IsFilterType.ServiceWorkerIntercepted);this._suggestionBuilder.addItem(FilterType.Is,IsFilterType.ServiceWorkerInitiated);this._suggestionBuilder.addItem(FilterType.LargerThan,'100');this._suggestionBuilder.addItem(FilterType.LargerThan,'10k');this._suggestionBuilder.addItem(FilterType.LargerThan,'1M');this._textFilterUI.setSuggestionProvider(this._suggestionBuilder.completions.bind(this._suggestionBuilder));}
_filterChanged(event){this.removeAllNodeHighlights();this._parseFilterQuery(this._textFilterUI.value());this._filterRequests();}
async resetFilter(){this._textFilterUI.clear();}
_showRecordingHint(){this._hideRecordingHint();this._recordingHint=this.element.createChild('div','network-status-pane fill');const hintText=this._recordingHint.createChild('div','recording-hint');let reloadShortcutNode=null;const reloadShortcutDescriptor=self.UI.shortcutRegistry.shortcutDescriptorsForAction('inspector_main.reload')[0];if(reloadShortcutDescriptor){reloadShortcutNode=this._recordingHint.createChild('b');reloadShortcutNode.textContent=reloadShortcutDescriptor.name;}
if(this._recording){const recordingText=hintText.createChild('span');recordingText.textContent=UIString.UIString('Recording network activity…');if(reloadShortcutNode){hintText.createChild('br');hintText.appendChild(UIUtils.formatLocalized('Perform a request or hit %s to record the reload.',[reloadShortcutNode]));}}else{const recordNode=hintText.createChild('b');recordNode.textContent=self.UI.shortcutRegistry.shortcutTitleForAction('network.toggle-recording');if(reloadShortcutNode){hintText.appendChild(UIUtils.formatLocalized('Record (%s) or reload (%s) to display network activity.',[recordNode,reloadShortcutNode]));}else{hintText.appendChild(UIUtils.formatLocalized('Record (%s) to display network activity.',[recordNode]));}}
hintText.createChild('br');hintText.appendChild(XLink.XLink.create('https://developers.google.com/web/tools/chrome-devtools/network/?utm_source=devtools&utm_campaign=2019Q1','Learn more'));this._setHidden(true);this._dataGrid.updateGridAccessibleName('');}
_hideRecordingHint(){this._setHidden(false);if(this._recordingHint){this._recordingHint.remove();}
this._dataGrid.updateGridAccessibleName(ls`Network Data Available`);this._recordingHint=null;}
_setHidden(value){this._columns.setHidden(value);ARIAUtils.setHidden(this._summaryToolbar.element,value);}
elementsToRestoreScrollPositionsFor(){if(!this._dataGrid)
{return[];}
return[this._dataGrid.scrollContainer];}
columnExtensionResolved(){this._invalidateAllItems(true);}
_setupDataGrid(){this._dataGrid.setRowContextMenuCallback((contextMenu,node)=>{const request=node.request();if(request){this.handleContextMenuForRequest(contextMenu,request);}});this._dataGrid.setStickToBottom(true);this._dataGrid.setName('networkLog');this._dataGrid.setResizeMethod(DataGrid.ResizeMethod.Last);this._dataGrid.element.classList.add('network-log-grid');this._dataGrid.element.addEventListener('mousedown',this._dataGridMouseDown.bind(this),true);this._dataGrid.element.addEventListener('mousemove',this._dataGridMouseMove.bind(this),true);this._dataGrid.element.addEventListener('mouseleave',()=>this._setHoveredNode(null),true);this._dataGrid.element.addEventListener('keydown',event=>{if(isEnterOrSpaceKey(event)){this.dispatchEventToListeners(Events$1.RequestActivated,{showPanel:true});event.consume(true);}});this._dataGrid.element.addEventListener('focus',this._onDataGridFocus.bind(this),true);this._dataGrid.element.addEventListener('blur',this._onDataGridBlur.bind(this),true);return this._dataGrid;}
_dataGridMouseMove(event){const node=(this._dataGrid.dataGridNodeFromNode((event.target)));const highlightInitiatorChain=event.shiftKey;this._setHoveredNode(node,highlightInitiatorChain);}
hoveredNode(){return this._hoveredNode;}
_setHoveredNode(node,highlightInitiatorChain){if(this._hoveredNode){this._hoveredNode.setHovered(false,false);}
this._hoveredNode=node;if(this._hoveredNode){this._hoveredNode.setHovered(true,!!highlightInitiatorChain);}}
_dataGridMouseDown(event){if(!this._dataGrid.selectedNode&&event.button){event.consume();}}
_updateSummaryBar(){this._hideRecordingHint();let transferSize=0;let resourceSize=0;let selectedNodeNumber=0;let selectedTransferSize=0;let selectedResourceSize=0;let baseTime=-1;let maxTime=-1;let nodeCount=0;for(const request of self.SDK.networkLog.requests()){const node=request[_networkNodeSymbol];if(!node){continue;}
nodeCount++;const requestTransferSize=request.transferSize;transferSize+=requestTransferSize;const requestResourceSize=request.resourceSize;resourceSize+=requestResourceSize;if(!node[isFilteredOutSymbol]){selectedNodeNumber++;selectedTransferSize+=requestTransferSize;selectedResourceSize+=requestResourceSize;}
const networkManager=NetworkManager.NetworkManager.forRequest(request);if(networkManager&&request.url()===networkManager.target().inspectedURL()&&request.resourceType()===ResourceType.resourceTypes.Document&&!networkManager.target().parentTarget()){baseTime=request.startTime;}
if(request.endTime>maxTime){maxTime=request.endTime;}}
if(!nodeCount){this._showRecordingHint();return;}
this._summaryToolbar.removeToolbarItems();const appendChunk=(chunk,title)=>{const toolbarText=new Toolbar.ToolbarText(chunk);toolbarText.setTitle(title?title:chunk);this._summaryToolbar.appendToolbarItem(toolbarText);return toolbarText.element;};if(selectedNodeNumber!==nodeCount){appendChunk(ls`${selectedNodeNumber} / ${nodeCount} requests`);this._summaryToolbar.appendSeparator();appendChunk(ls`${Number.bytesToString(selectedTransferSize)} / ${Number.bytesToString(transferSize)} transferred`,ls`${selectedTransferSize} B / ${transferSize} B transferred over network`);this._summaryToolbar.appendSeparator();appendChunk(ls`${Number.bytesToString(selectedResourceSize)} / ${Number.bytesToString(resourceSize)} resources`,ls`${selectedResourceSize} B / ${resourceSize} B resources loaded by the page`);}else{appendChunk(ls`${nodeCount} requests`);this._summaryToolbar.appendSeparator();appendChunk(ls`${Number.bytesToString(transferSize)} transferred`,ls`${transferSize} B transferred over network`);this._summaryToolbar.appendSeparator();appendChunk(ls`${Number.bytesToString(resourceSize)} resources`,ls`${resourceSize} B resources loaded by the page`);}
if(baseTime!==-1&&maxTime!==-1){this._summaryToolbar.appendSeparator();appendChunk(ls`Finish: ${Number.secondsToString(maxTime - baseTime)}`);if(this._mainRequestDOMContentLoadedTime!==-1&&this._mainRequestDOMContentLoadedTime>baseTime){this._summaryToolbar.appendSeparator();const domContentLoadedText=ls`DOMContentLoaded: ${Number.secondsToString(this._mainRequestDOMContentLoadedTime - baseTime)}`;appendChunk(domContentLoadedText).style.color=NetworkLogView.getDCLEventColor();}
if(this._mainRequestLoadTime!==-1){this._summaryToolbar.appendSeparator();const loadText=ls`Load: ${Number.secondsToString(this._mainRequestLoadTime - baseTime)}`;appendChunk(loadText).style.color=NetworkLogView.getLoadEventColor();}}}
scheduleRefresh(){if(this._needsRefresh){return;}
this._needsRefresh=true;if(this.isShowing()&&!this._refreshRequestId){this._refreshRequestId=this.element.window().requestAnimationFrame(this._refresh.bind(this));}}
addFilmStripFrames(times){this._columns.addEventDividers(times,'network-frame-divider');}
selectFilmStripFrame(time){this._columns.selectFilmStripFrame(time);}
clearFilmStripFrame(){this._columns.clearFilmStripFrame();}
_refreshIfNeeded(){if(this._needsRefresh){this._refresh();}}
_invalidateAllItems(deferUpdate){this._staleRequests=new Set(self.SDK.networkLog.requests());if(deferUpdate){this.scheduleRefresh();}else{this._refresh();}}
timeCalculator(){return this._timeCalculator;}
calculator(){return this._calculator;}
setCalculator(x){if(!x||this._calculator===x){return;}
if(this._calculator!==x){this._calculator=x;this._columns.setCalculator(this._calculator);}
this._calculator.reset();if(this._calculator.startAtZero){this._columns.hideEventDividers();}else{this._columns.showEventDividers();}
this._invalidateAllItems();}
_loadEventFired(event){if(!this._recording){return;}
const time=(event.data.loadTime);if(time){this._mainRequestLoadTime=time;this._columns.addEventDividers([time],'network-load-divider');}}
_domContentLoadedEventFired(event){if(!this._recording){return;}
const data=(event.data);if(data){this._mainRequestDOMContentLoadedTime=data;this._columns.addEventDividers([data],'network-dcl-divider');}}
wasShown(){this._refreshIfNeeded();this._columns.wasShown();}
willHide(){this._columns.willHide();}
onResize(){this._rowHeight=this._computeRowHeight();}
flatNodesList(){return this._dataGrid.rootNode().flatChildren();}
_onDataGridFocus(){this.element.classList.add('grid-focused');this.updateNodeBackground();}
_onDataGridBlur(){this.element.classList.remove('grid-focused');this.updateNodeBackground();}
updateNodeBackground(){if(this._dataGrid.selectedNode){this._dataGrid.selectedNode.updateBackgroundColor();}}
updateNodeSelectedClass(isSelected){if(isSelected){this.element.classList.remove('no-node-selected');}else{this.element.classList.add('no-node-selected');}}
stylesChanged(){this._columns.scheduleRefresh();}
_refresh(){this._needsRefresh=false;if(this._refreshRequestId){this.element.window().cancelAnimationFrame(this._refreshRequestId);this._refreshRequestId=null;}
this.removeAllNodeHighlights();this._timeCalculator.updateBoundariesForEventTime(this._mainRequestLoadTime);this._durationCalculator.updateBoundariesForEventTime(this._mainRequestLoadTime);this._timeCalculator.updateBoundariesForEventTime(this._mainRequestDOMContentLoadedTime);this._durationCalculator.updateBoundariesForEventTime(this._mainRequestDOMContentLoadedTime);const nodesToInsert=new Map();const nodesToRefresh=[];const staleNodes=new Set();while(this._staleRequests.size){const request=this._staleRequests.firstValue();this._staleRequests.delete(request);let node=request[_networkNodeSymbol];if(!node){node=this._createNodeForRequest(request);}
staleNodes.add(node);}
for(const node of staleNodes){const isFilteredOut=!this._applyFilter(node);if(isFilteredOut&&node===this._hoveredNode){this._setHoveredNode(null);}
if(!isFilteredOut){nodesToRefresh.push(node);}
const request=node.request();this._timeCalculator.updateBoundaries(request);this._durationCalculator.updateBoundaries(request);const newParent=this._parentNodeForInsert(node);if(node[isFilteredOutSymbol]===isFilteredOut&&node.parent===newParent){continue;}
node[isFilteredOutSymbol]=isFilteredOut;const removeFromParent=node.parent&&(isFilteredOut||node.parent!==newParent);if(removeFromParent){let parent=node.parent;parent.removeChild(node);while(parent&&!parent.hasChildren()&&parent.dataGrid&&parent.dataGrid.rootNode()!==parent){const grandparent=parent.parent;grandparent.removeChild(parent);parent=grandparent;}}
if(!newParent||isFilteredOut){continue;}
if(!newParent.dataGrid&&!nodesToInsert.has(newParent)){nodesToInsert.set(newParent,this._dataGrid.rootNode());nodesToRefresh.push(newParent);}
nodesToInsert.set(node,newParent);}
for(const node of nodesToInsert.keys()){nodesToInsert.get(node).appendChild(node);}
for(const node of nodesToRefresh){node.refresh();}
this._updateSummaryBar();if(nodesToInsert.size){this._columns.sortByCurrentColumn();}
this._dataGrid.updateInstantly();this._didRefreshForTest();}
_didRefreshForTest(){}
_parentNodeForInsert(node){if(!this._activeGroupLookup){return this._dataGrid.rootNode();}
const groupNode=this._activeGroupLookup.groupNodeForRequest(node.request());if(!groupNode){return this._dataGrid.rootNode();}
return groupNode;}
_reset(){this.dispatchEventToListeners(Events$1.RequestActivated,{showPanel:false});this._setHoveredNode(null);this._columns.reset();this._timeFilter=null;this._calculator.reset();this._timeCalculator.setWindow(null);this.linkifier.reset();if(this._activeGroupLookup){this._activeGroupLookup.reset();}
this._staleRequests.clear();this._resetSuggestionBuilder();this._mainRequestLoadTime=-1;this._mainRequestDOMContentLoadedTime=-1;this._dataGrid.rootNode().removeChildren();this._updateSummaryBar();this._dataGrid.setStickToBottom(true);this.scheduleRefresh();}
setTextFilterValue(filterString){this._textFilterUI.setValue(filterString);this._dataURLFilterUI.setChecked(false);this._onlyIssuesFilterUI.setChecked(false);this._onlyBlockedRequestsUI.setChecked(false);this._resourceCategoryFilterUI.reset();}
_createNodeForRequest(request){const node=new NetworkRequestNode(this,request);request[_networkNodeSymbol]=node;node[isFilteredOutSymbol]=true;for(let redirect=request.redirectSource();redirect;redirect=redirect.redirectSource()){this._refreshRequest(redirect);}
return node;}
_onRequestUpdated(event){const request=(event.data);this._refreshRequest(request);}
_refreshRequest(request){NetworkLogView._subdomains(request.domain).forEach(this._suggestionBuilder.addItem.bind(this._suggestionBuilder,FilterType.Domain));this._suggestionBuilder.addItem(FilterType.Method,request.requestMethod);this._suggestionBuilder.addItem(FilterType.MimeType,request.mimeType);this._suggestionBuilder.addItem(FilterType.Scheme,''+request.scheme);this._suggestionBuilder.addItem(FilterType.StatusCode,''+request.statusCode);const priority=request.priority();if(priority){this._suggestionBuilder.addItem(FilterType.Priority,NetworkPriorities.uiLabelForNetworkPriority(priority));}
if(request.mixedContentType!==Protocol.Security.MixedContentType.None){this._suggestionBuilder.addItem(FilterType.MixedContent,MixedContentFilterValues.All);}
if(request.mixedContentType===Protocol.Security.MixedContentType.OptionallyBlockable){this._suggestionBuilder.addItem(FilterType.MixedContent,MixedContentFilterValues.Displayed);}
if(request.mixedContentType===Protocol.Security.MixedContentType.Blockable){const suggestion=request.wasBlocked()?MixedContentFilterValues.Blocked:MixedContentFilterValues.BlockOverridden;this._suggestionBuilder.addItem(FilterType.MixedContent,suggestion);}
const responseHeaders=request.responseHeaders;for(let i=0,l=responseHeaders.length;i<l;++i){this._suggestionBuilder.addItem(FilterType.HasResponseHeader,responseHeaders[i].name);}
for(const cookie of request.responseCookies){this._suggestionBuilder.addItem(FilterType.SetCookieDomain,cookie.domain());this._suggestionBuilder.addItem(FilterType.SetCookieName,cookie.name());this._suggestionBuilder.addItem(FilterType.SetCookieValue,cookie.value());}
for(const cookie of request.allCookiesIncludingBlockedOnes()){this._suggestionBuilder.addItem(FilterType.CookieDomain,cookie.domain());this._suggestionBuilder.addItem(FilterType.CookieName,cookie.name());this._suggestionBuilder.addItem(FilterType.CookiePath,cookie.path());this._suggestionBuilder.addItem(FilterType.CookieValue,cookie.value());}
this._staleRequests.add(request);this.scheduleRefresh();}
rowHeight(){return this._rowHeight;}
switchViewMode(gridMode){this._columns.switchViewMode(gridMode);}
handleContextMenuForRequest(contextMenu,request){contextMenu.appendApplicableItems(request);let copyMenu=contextMenu.clipboardSection().appendSubMenuItem(UIString.UIString('Copy'));const footerSection=copyMenu.footerSection();if(request){copyMenu.defaultSection().appendItem(UIUtils.copyLinkAddressLabel(),InspectorFrontendHost.InspectorFrontendHostInstance.copyText.bind(InspectorFrontendHost.InspectorFrontendHostInstance,request.contentURL()));if(request.requestHeadersText()){copyMenu.defaultSection().appendItem(UIString.UIString('Copy request headers'),NetworkLogView._copyRequestHeaders.bind(null,request));}
if(request.responseHeadersText){copyMenu.defaultSection().appendItem(UIString.UIString('Copy response headers'),NetworkLogView._copyResponseHeaders.bind(null,request));}
if(request.finished){copyMenu.defaultSection().appendItem(UIString.UIString('Copy response'),NetworkLogView._copyResponse.bind(null,request));}
const disableIfBlob=request.isBlobRequest();if(Platform.isWin()){footerSection.appendItem(UIString.UIString('Copy as PowerShell'),this._copyPowerShellCommand.bind(this,request),disableIfBlob);footerSection.appendItem(UIString.UIString('Copy as fetch'),this._copyFetchCall.bind(this,request,false),disableIfBlob);footerSection.appendItem(UIString.UIString('Copy as Node.js fetch'),this._copyFetchCall.bind(this,request,true),disableIfBlob);footerSection.appendItem(UIString.UIString('Copy as cURL (cmd)'),this._copyCurlCommand.bind(this,request,'win'),disableIfBlob);footerSection.appendItem(UIString.UIString('Copy as cURL (bash)'),this._copyCurlCommand.bind(this,request,'unix'),disableIfBlob);footerSection.appendItem(UIString.UIString('Copy all as PowerShell'),this._copyAllPowerShellCommand.bind(this));footerSection.appendItem(UIString.UIString('Copy all as fetch'),this._copyAllFetchCall.bind(this,false));footerSection.appendItem(UIString.UIString('Copy all as Node.js fetch'),this._copyAllFetchCall.bind(this,true));footerSection.appendItem(UIString.UIString('Copy all as cURL (cmd)'),this._copyAllCurlCommand.bind(this,'win'));footerSection.appendItem(UIString.UIString('Copy all as cURL (bash)'),this._copyAllCurlCommand.bind(this,'unix'));}else{footerSection.appendItem(UIString.UIString('Copy as fetch'),this._copyFetchCall.bind(this,request,false),disableIfBlob);footerSection.appendItem(UIString.UIString('Copy as Node.js fetch'),this._copyFetchCall.bind(this,request,true),disableIfBlob);footerSection.appendItem(UIString.UIString('Copy as cURL'),this._copyCurlCommand.bind(this,request,'unix'),disableIfBlob);footerSection.appendItem(UIString.UIString('Copy all as fetch'),this._copyAllFetchCall.bind(this,false));footerSection.appendItem(UIString.UIString('Copy all as Node.js fetch'),this._copyAllFetchCall.bind(this,true));footerSection.appendItem(UIString.UIString('Copy all as cURL'),this._copyAllCurlCommand.bind(this,'unix'));}}else{copyMenu=contextMenu.clipboardSection().appendSubMenuItem(UIString.UIString('Copy'));}
footerSection.appendItem(UIString.UIString('Copy all as HAR'),this._copyAll.bind(this));contextMenu.saveSection().appendItem(ls`Save all as HAR with content`,this.exportAll.bind(this));contextMenu.editSection().appendItem(UIString.UIString('Clear browser cache'),this._clearBrowserCache.bind(this));contextMenu.editSection().appendItem(UIString.UIString('Clear browser cookies'),this._clearBrowserCookies.bind(this));if(request){const maxBlockedURLLength=20;const manager=self.SDK.multitargetNetworkManager;let patterns=manager.blockedPatterns();function addBlockedURL(url){patterns.push({enabled:true,url:url});manager.setBlockedPatterns(patterns);manager.setBlockingEnabled(true);ViewManager.ViewManager.instance().showView('network.blocked-urls');}
function removeBlockedURL(url){patterns=patterns.filter(pattern=>pattern.url!==url);manager.setBlockedPatterns(patterns);ViewManager.ViewManager.instance().showView('network.blocked-urls');}
const urlWithoutScheme=request.parsedURL.urlWithoutScheme();if(urlWithoutScheme&&!patterns.find(pattern=>pattern.url===urlWithoutScheme)){contextMenu.debugSection().appendItem(UIString.UIString('Block request URL'),addBlockedURL.bind(null,urlWithoutScheme));}else if(urlWithoutScheme){const croppedURL=urlWithoutScheme.trimMiddle(maxBlockedURLLength);contextMenu.debugSection().appendItem(UIString.UIString('Unblock %s',croppedURL),removeBlockedURL.bind(null,urlWithoutScheme));}
const domain=request.parsedURL.domain();if(domain&&!patterns.find(pattern=>pattern.url===domain)){contextMenu.debugSection().appendItem(UIString.UIString('Block request domain'),addBlockedURL.bind(null,domain));}else if(domain){const croppedDomain=domain.trimMiddle(maxBlockedURLLength);contextMenu.debugSection().appendItem(UIString.UIString('Unblock %s',croppedDomain),removeBlockedURL.bind(null,domain));}
if(NetworkManager.NetworkManager.canReplayRequest(request)){contextMenu.debugSection().appendItem(UIString.UIString('Replay XHR'),NetworkManager.NetworkManager.replayRequest.bind(null,request));}}}
_harRequests(){return self.SDK.networkLog.requests().filter(NetworkLogView.HTTPRequestsFilter).filter(request=>{return request.finished||(request.resourceType()===ResourceType.resourceTypes.WebSocket&&request.responseReceivedTime);});}
async _copyAll(){const harArchive={log:await HARLog.HARLog.build(this._harRequests())};InspectorFrontendHost.InspectorFrontendHostInstance.copyText(JSON.stringify(harArchive,null,2));}
async _copyCurlCommand(request,platform){const command=await this._generateCurlCommand(request,platform);InspectorFrontendHost.InspectorFrontendHostInstance.copyText(command);}
async _copyAllCurlCommand(platform){const commands=await this._generateAllCurlCommand(self.SDK.networkLog.requests(),platform);InspectorFrontendHost.InspectorFrontendHostInstance.copyText(commands);}
async _copyFetchCall(request,includeCookies){const command=await this._generateFetchCall(request,includeCookies);InspectorFrontendHost.InspectorFrontendHostInstance.copyText(command);}
async _copyAllFetchCall(includeCookies){const commands=await this._generateAllFetchCall(self.SDK.networkLog.requests(),includeCookies);InspectorFrontendHost.InspectorFrontendHostInstance.copyText(commands);}
async _copyPowerShellCommand(request){const command=await this._generatePowerShellCommand(request);InspectorFrontendHost.InspectorFrontendHostInstance.copyText(command);}
async _copyAllPowerShellCommand(){const commands=await this._generateAllPowerShellCommand(self.SDK.networkLog.requests());InspectorFrontendHost.InspectorFrontendHostInstance.copyText(commands);}
async exportAll(){const url=SDKModel.TargetManager.instance().mainTarget().inspectedURL();const parsedURL=ParsedURL.ParsedURL.fromString(url);const filename=parsedURL?parsedURL.host:'network-log';const stream=new FileUtils.FileOutputStream();if(!await stream.open(filename+'.har')){return;}
const progressIndicator=new ProgressIndicator.ProgressIndicator();this._progressBarContainer.appendChild(progressIndicator.element);await HARWriter.write(stream,this._harRequests(),progressIndicator);progressIndicator.done();stream.close();}
_clearBrowserCache(){if(confirm(UIString.UIString('Are you sure you want to clear browser cache?'))){self.SDK.multitargetNetworkManager.clearBrowserCache();}}
_clearBrowserCookies(){if(confirm(UIString.UIString('Are you sure you want to clear browser cookies?'))){self.SDK.multitargetNetworkManager.clearBrowserCookies();}}
_removeAllHighlights(){this.removeAllNodeHighlights();for(let i=0;i<this._highlightedSubstringChanges.length;++i){UIUtils.revertDomChanges(this._highlightedSubstringChanges[i]);}
this._highlightedSubstringChanges=[];}
_applyFilter(node){const request=node.request();if(this._timeFilter&&!this._timeFilter(request)){return false;}
const categoryName=request.resourceType().category().title;if(!this._resourceCategoryFilterUI.accept(categoryName)){return false;}
if(this._dataURLFilterUI.checked()&&(request.parsedURL.isDataURL()||request.parsedURL.isBlobURL())){return false;}
if(this._onlyIssuesFilterUI.checked()&&!RelatedIssue.hasIssues(request)){return false;}
if(this._onlyBlockedRequestsUI.checked()&&!request.wasBlocked()){return false;}
if(request.statusText==='Service Worker Fallback Required'){return false;}
for(let i=0;i<this._filters.length;++i){if(!this._filters[i](request)){return false;}}
return true;}
_parseFilterQuery(query){const descriptors=this._filterParser.parse(query);this._filters=descriptors.map(descriptor=>{const key=descriptor.key;const text=descriptor.text||'';const regex=descriptor.regex;let filter;if(key){const defaultText=(key+':'+text).escapeForRegExp();filter=this._createSpecialFilter((key),text)||NetworkLogView._requestPathFilter.bind(null,new RegExp(defaultText,'i'));}else if(descriptor.regex){filter=NetworkLogView._requestPathFilter.bind(null,(regex));}else{filter=NetworkLogView._requestPathFilter.bind(null,new RegExp(text.escapeForRegExp(),'i'));}
return descriptor.negative?NetworkLogView._negativeFilter.bind(null,filter):filter;});}
_createSpecialFilter(type,value){switch(type){case FilterType.Domain:return NetworkLogView._createRequestDomainFilter(value);case FilterType.HasResponseHeader:return NetworkLogView._requestResponseHeaderFilter.bind(null,value);case FilterType.Is:if(value.toLowerCase()===IsFilterType.Running){return NetworkLogView._runningRequestFilter;}
if(value.toLowerCase()===IsFilterType.FromCache){return NetworkLogView._fromCacheRequestFilter;}
if(value.toLowerCase()===IsFilterType.ServiceWorkerIntercepted){return NetworkLogView._interceptedByServiceWorkerFilter;}
if(value.toLowerCase()===IsFilterType.ServiceWorkerInitiated){return NetworkLogView._initiatedByServiceWorkerFilter;}
break;case FilterType.LargerThan:return this._createSizeFilter(value.toLowerCase());case FilterType.Method:return NetworkLogView._requestMethodFilter.bind(null,value);case FilterType.MimeType:return NetworkLogView._requestMimeTypeFilter.bind(null,value);case FilterType.MixedContent:return NetworkLogView._requestMixedContentFilter.bind(null,(value));case FilterType.Scheme:return NetworkLogView._requestSchemeFilter.bind(null,value);case FilterType.SetCookieDomain:return NetworkLogView._requestSetCookieDomainFilter.bind(null,value);case FilterType.SetCookieName:return NetworkLogView._requestSetCookieNameFilter.bind(null,value);case FilterType.SetCookieValue:return NetworkLogView._requestSetCookieValueFilter.bind(null,value);case FilterType.CookieDomain:return NetworkLogView._requestCookieDomainFilter.bind(null,value);case FilterType.CookieName:return NetworkLogView._requestCookieNameFilter.bind(null,value);case FilterType.CookiePath:return NetworkLogView._requestCookiePathFilter.bind(null,value);case FilterType.CookieValue:return NetworkLogView._requestCookieValueFilter.bind(null,value);case FilterType.Priority:return NetworkLogView._requestPriorityFilter.bind(null,NetworkPriorities.uiLabelToNetworkPriority(value));case FilterType.StatusCode:return NetworkLogView._statusCodeFilter.bind(null,value);}
return null;}
_createSizeFilter(value){let multiplier=1;if(value.endsWith('k')){multiplier=1024;value=value.substring(0,value.length-1);}else if(value.endsWith('m')){multiplier=1024*1024;value=value.substring(0,value.length-1);}
const quantity=Number(value);if(isNaN(quantity)){return null;}
return NetworkLogView._requestSizeLargerThanFilter.bind(null,quantity*multiplier);}
_filterRequests(){this._removeAllHighlights();this._invalidateAllItems();}
_reveal(request){this.removeAllNodeHighlights();const node=request[_networkNodeSymbol];if(!node||!node.dataGrid){return null;}
if(node.parent&&node.parent instanceof NetworkGroupNode){node.parent.reveal();node.parent.expand();}
node.reveal();return node;}
revealAndHighlightRequest(request){const node=this._reveal(request);if(node){this._highlightNode(node);}}
selectRequest(request){this.setTextFilterValue('');const node=this._reveal(request);if(node){node.select();}}
removeAllNodeHighlights(){if(this._highlightedNode){this._highlightedNode.element().classList.remove('highlighted-row');this._highlightedNode=null;}}
_highlightNode(node){UIUtils.runCSSAnimationOnce(node.element(),'highlighted-row');this._highlightedNode=node;}
_filterOutBlobRequests(requests){return requests.filter(request=>!request.isBlobRequest());}
async _generateFetchCall(request,includeCookies){const ignoredHeaders={'method':1,'path':1,'scheme':1,'version':1,'accept-charset':1,'accept-encoding':1,'access-control-request-headers':1,'access-control-request-method':1,'connection':1,'content-length':1,'cookie':1,'cookie2':1,'date':1,'dnt':1,'expect':1,'host':1,'keep-alive':1,'origin':1,'referer':1,'te':1,'trailer':1,'transfer-encoding':1,'upgrade':1,'via':1,'user-agent':1};const credentialHeaders={'cookie':1,'authorization':1};const url=JSON.stringify(request.url());const requestHeaders=request.requestHeaders();const headerData=requestHeaders.reduce((result,header)=>{const name=header.name;if(!ignoredHeaders[name.toLowerCase()]&&!name.includes(':')){result.append(name,header.value);}
return result;},new Headers());const headers={};for(const headerArray of headerData){headers[headerArray[0]]=headerArray[1];}
const credentials=request.requestCookies.length||requestHeaders.some(({name})=>credentialHeaders[name.toLowerCase()])?'include':'omit';const referrerHeader=requestHeaders.find(({name})=>name.toLowerCase()==='referer');const referrer=referrerHeader?referrerHeader.value:void 0;const referrerPolicy=request.referrerPolicy()||void 0;const requestBody=await request.requestFormData();const fetchOptions={headers:Object.keys(headers).length?headers:void 0,referrer,referrerPolicy,body:requestBody,method:request.requestMethod,mode:'cors'};if(includeCookies){const cookieHeader=requestHeaders.find(header=>header.name.toLowerCase()==='cookie');if(cookieHeader){fetchOptions.headers={...headers,'cookie':cookieHeader.value,};}}else{fetchOptions.credentials=credentials;}
const options=JSON.stringify(fetchOptions,null,2);return`fetch(${url}, ${options});`;}
async _generateAllFetchCall(requests,includeCookies){const nonBlobRequests=this._filterOutBlobRequests(requests);const commands=await Promise.all(nonBlobRequests.map(request=>this._generateFetchCall(request,includeCookies)));return commands.join(' ;\n');}
async _generateCurlCommand(request,platform){let command=[];const ignoredHeaders={'accept-encoding':1,'host':1,'method':1,'path':1,'scheme':1,'version':1};function escapeStringWin(str){const encapsChars=/[\r\n]/.test(str)?'^"':'"';return encapsChars+
str.replace(/\\/g,'\\\\').replace(/"/g,'\\"').replace(/[^a-zA-Z0-9\s_\-:=+~'\/.',?;()*`]/g,'^$&').replace(/%(?=[a-zA-Z0-9_])/g,'%^').replace(/\r\n|[\n\r]/g,'^\n\n')+
encapsChars;}
function escapeStringPosix(str){function escapeCharacter(x){const code=x.charCodeAt(0);let hexString=code.toString(16);while(hexString.length<4){hexString='0'+hexString;}
return'\\u'+hexString;}
if(/[\0-\x1F\x7F-\x9F!]|\'/.test(str)){return'$\''+
str.replace(/\\/g,'\\\\').replace(/\'/g,'\\\'').replace(/\n/g,'\\n').replace(/\r/g,'\\r').replace(/[\0-\x1F\x7F-\x9F!]/g,escapeCharacter)+'\'';}
return'\''+str+'\'';}
const escapeString=platform==='win'?escapeStringWin:escapeStringPosix;command.push(escapeString(request.url()).replace(/[[{}\]]/g,'\\$&'));let inferredMethod='GET';const data=[];const requestContentType=request.requestContentType();const formData=await request.requestFormData();if(requestContentType&&requestContentType.startsWith('application/x-www-form-urlencoded')&&formData){data.push('--data-raw '+escapeString(formData));ignoredHeaders['content-length']=true;inferredMethod='POST';}else if(formData){data.push('--data-binary '+escapeString(formData));ignoredHeaders['content-length']=true;inferredMethod='POST';}
if(request.requestMethod!==inferredMethod){command.push('-X '+escapeString(request.requestMethod));}
const requestHeaders=request.requestHeaders();for(let i=0;i<requestHeaders.length;i++){const header=requestHeaders[i];const name=header.name.replace(/^:/,'');if(name.toLowerCase()in ignoredHeaders){continue;}
command.push('-H '+escapeString(name+': '+header.value));}
command=command.concat(data);command.push('--compressed');if(request.securityState()===Protocol.Security.SecurityState.Insecure){command.push('--insecure');}
return'curl '+command.join(command.length>=3?(platform==='win'?' ^\n  ':' \\\n  '):' ');}
async _generateAllCurlCommand(requests,platform){const nonBlobRequests=this._filterOutBlobRequests(requests);const commands=await Promise.all(nonBlobRequests.map(request=>this._generateCurlCommand(request,platform)));if(platform==='win'){return commands.join(' &\r\n');}
return commands.join(' ;\n');}
async _generatePowerShellCommand(request){const command=[];const ignoredHeaders=new Set(['host','connection','proxy-connection','content-length','expect','range','content-type']);function escapeString(str){return'"'+
str.replace(/[`\$"]/g,'`$&').replace(/[^\x20-\x7E]/g,char=>'$([char]'+char.charCodeAt(0)+')')+'"';}
command.push('-Uri '+escapeString(request.url()));if(request.requestMethod!=='GET'){command.push('-Method '+escapeString(request.requestMethod));}
const requestHeaders=request.requestHeaders();const headerNameValuePairs=[];for(const header of requestHeaders){const name=header.name.replace(/^:/,'');if(ignoredHeaders.has(name.toLowerCase())){continue;}
headerNameValuePairs.push(escapeString(name)+'='+escapeString(header.value));}
if(headerNameValuePairs.length){command.push('-Headers @{\n'+headerNameValuePairs.join('\n  ')+'\n}');}
const contentTypeHeader=requestHeaders.find(({name})=>name.toLowerCase()==='content-type');if(contentTypeHeader){command.push('-ContentType '+escapeString(contentTypeHeader.value));}
const formData=await request.requestFormData();if(formData){const body=escapeString(formData);if(/[^\x20-\x7E]/.test(formData)){command.push('-Body ([System.Text.Encoding]::UTF8.GetBytes('+body+'))');}else{command.push('-Body '+body);}}
return'Invoke-WebRequest '+command.join(command.length>=3?' `\n':' ');}
async _generateAllPowerShellCommand(requests){const nonBlobRequests=this._filterOutBlobRequests(requests);const commands=await Promise.all(nonBlobRequests.map(request=>this._generatePowerShellCommand(request)));return commands.join(';\r\n');}
static getDCLEventColor(){if(self.UI.themeSupport.themeName()==='dark'){return'#03A9F4';}
return'#0867CB';}
static getLoadEventColor(){return self.UI.themeSupport.patchColorText('#B31412',UIUtils.ThemeSupport.ColorUsage.Foreground);}}
const isFilteredOutSymbol=Symbol('isFilteredOut');const _networkNodeSymbol=Symbol('NetworkNode');const HTTPSchemas={'http':true,'https':true,'ws':true,'wss':true};const FilterType={Domain:'domain',HasResponseHeader:'has-response-header',Is:'is',LargerThan:'larger-than',Method:'method',MimeType:'mime-type',MixedContent:'mixed-content',Priority:'priority',Scheme:'scheme',SetCookieDomain:'set-cookie-domain',SetCookieName:'set-cookie-name',SetCookieValue:'set-cookie-value',CookieDomain:'cookie-domain',CookieName:'cookie-name',CookiePath:'cookie-path',CookieValue:'cookie-value',StatusCode:'status-code'};const MixedContentFilterValues={All:'all',Displayed:'displayed',Blocked:'blocked',BlockOverridden:'block-overridden'};const IsFilterType={Running:'running',FromCache:'from-cache',ServiceWorkerIntercepted:'service-worker-intercepted',ServiceWorkerInitiated:'service-worker-initiated'};const _searchKeys=Object.keys(FilterType).map(key=>FilterType[key]);class GroupLookupInterface{groupNodeForRequest(request){}
reset(){}}
let Filter;var NetworkLogView$1=Object.freeze({__proto__:null,NetworkLogView:NetworkLogView,isFilteredOutSymbol:isFilteredOutSymbol,_networkNodeSymbol:_networkNodeSymbol,HTTPSchemas:HTTPSchemas,FilterType:FilterType,MixedContentFilterValues:MixedContentFilterValues,IsFilterType:IsFilterType,_searchKeys:_searchKeys,GroupLookupInterface:GroupLookupInterface,Filter:Filter});class NetworkSearchScope{performIndexing(progress){setImmediate(progress.done.bind(progress));}
async performSearch(searchConfig,progress,searchResultCallback,searchFinishedCallback){const promises=[];const requests=self.SDK.networkLog.requests().filter(request=>searchConfig.filePathMatchesFileQuery(request.url()));progress.setTotalWork(requests.length);for(const request of requests){const promise=this._searchRequest(searchConfig,request,progress);promises.push(promise);}
const results=await Promise.all(promises);if(progress.isCanceled()){searchFinishedCallback(false);return;}
for(const result of results.sort((r1,r2)=>r1.label().localeCompare(r2.label()))){if(result.matchesCount()>0){searchResultCallback(result);}}
progress.done();searchFinishedCallback(true);}
async _searchRequest(searchConfig,request,progress){let bodyMatches=[];if(request.contentType().isTextType()){bodyMatches=await request.searchInContent(searchConfig.query(),!searchConfig.ignoreCase(),searchConfig.isRegex());}
if(progress.isCanceled()){return null;}
const locations=[];if(stringMatchesQuery(request.url())){locations.push(UIRequestLocation.urlMatch(request));}
for(const header of request.requestHeaders()){if(headerMatchesQuery(header)){locations.push(UIRequestLocation.requestHeaderMatch(request,header));}}
for(const header of request.responseHeaders){if(headerMatchesQuery(header)){locations.push(UIRequestLocation.responseHeaderMatch(request,header));}}
for(const match of bodyMatches){locations.push(UIRequestLocation.bodyMatch(request,match));}
progress.worked();return new NetworkSearchResult(request,locations);function headerMatchesQuery(header){return stringMatchesQuery(`${header.name}: ${header.value}`);}
function stringMatchesQuery(string){const flags=searchConfig.ignoreCase()?'i':'';const regExps=searchConfig.queries().map(query=>new RegExp(query,flags));let pos=0;for(const regExp of regExps){const match=string.substr(pos).match(regExp);if(!match){return false;}
pos+=match.index+match[0].length;}
return true;}}
stopSearch(){}}
class UIRequestLocation{constructor(request,requestHeader,responseHeader,searchMatch,urlMatch){this.request=request;this.requestHeader=requestHeader;this.responseHeader=responseHeader;this.searchMatch=searchMatch;this.isUrlMatch=urlMatch;}
static requestHeaderMatch(request,header){return new UIRequestLocation(request,header,null,null,false);}
static responseHeaderMatch(request,header){return new UIRequestLocation(request,null,header,null,false);}
static bodyMatch(request,searchMatch){return new UIRequestLocation(request,null,null,searchMatch,false);}
static urlMatch(request){return new UIRequestLocation(request,null,null,null,true);}}
class NetworkSearchResult{constructor(request,locations){this._request=request;this._locations=locations;}
matchesCount(){return this._locations.length;}
label(){return this._request.displayName;}
description(){const parsedUrl=this._request.parsedURL;if(!parsedUrl){return this._request.url();}
return parsedUrl.urlWithoutScheme();}
matchLineContent(index){const location=this._locations[index];if(location.isUrlMatch){return this._request.url();}
const header=location.requestHeader||location.responseHeader;if(header){return header.value;}
return location.searchMatch.lineContent;}
matchRevealable(index){return this._locations[index];}
matchLabel(index){const location=this._locations[index];if(location.isUrlMatch){return UIString.UIString('URL');}
const header=location.requestHeader||location.responseHeader;if(header){return`${header.name}:`;}
return location.searchMatch.lineNumber+1;}}
var NetworkSearchScope$1=Object.freeze({__proto__:null,NetworkSearchScope:NetworkSearchScope,UIRequestLocation:UIRequestLocation,NetworkSearchResult:NetworkSearchResult});class NetworkOverview extends TimelineOverviewPane.TimelineOverviewBase{constructor(){super();this._selectedFilmStripTime=-1;this.element.classList.add('network-overview');this._numBands=1;this._updateScheduled=false;this._highlightedRequest=null;SDKModel.TargetManager.instance().addModelListener(ResourceTreeModel.ResourceTreeModel,ResourceTreeModel.Events.Load,this._loadEventFired,this);SDKModel.TargetManager.instance().addModelListener(ResourceTreeModel.ResourceTreeModel,ResourceTreeModel.Events.DOMContentLoaded,this._domContentLoadedEventFired,this);this.reset();}
setHighlightedRequest(request){this._highlightedRequest=request;this.scheduleUpdate();}
setFilmStripModel(filmStripModel){this._filmStripModel=filmStripModel;this.scheduleUpdate();}
selectFilmStripFrame(time){this._selectedFilmStripTime=time;this.scheduleUpdate();}
clearFilmStripFrame(){this._selectedFilmStripTime=-1;this.scheduleUpdate();}
_loadEventFired(event){const time=(event.data.loadTime);if(time){this._loadEvents.push(time*1000);}
this.scheduleUpdate();}
_domContentLoadedEventFired(event){const data=(event.data);if(data){this._domContentLoadedEvents.push(data*1000);}
this.scheduleUpdate();}
_bandId(connectionId){if(!connectionId||connectionId==='0'){return-1;}
if(this._bandMap.has(connectionId)){return(this._bandMap.get(connectionId));}
const result=this._nextBand++;this._bandMap.set(connectionId,result);return result;}
updateRequest(request){if(!this._requestsSet.has(request)){this._requestsSet.add(request);this._requestsList.push(request);}
this.scheduleUpdate();}
wasShown(){this.onResize();}
onResize(){const width=this.element.offsetWidth;const height=this.element.offsetHeight;this.calculator().setDisplayWidth(width);this.resetCanvas();const numBands=(((height-_padding-1)/_bandHeight)-1)|0;this._numBands=(numBands>0)?numBands:1;this.scheduleUpdate();}
reset(){this._filmStripModel=null;this._span=1;this._lastBoundary=null;this._nextBand=0;this._bandMap=new Map();this._requestsList=[];this._requestsSet=new Set();this._loadEvents=[];this._domContentLoadedEvents=[];this.resetCanvas();}
scheduleUpdate(){if(this._updateScheduled||!this.isShowing()){return;}
this._updateScheduled=true;this.element.window().requestAnimationFrame(this.update.bind(this));}
update(){this._updateScheduled=false;const calculator=this.calculator();const newBoundary=new NetworkTimeBoundary(calculator.minimumBoundary(),calculator.maximumBoundary());if(!this._lastBoundary||!newBoundary.equals(this._lastBoundary)){const span=calculator.boundarySpan();while(this._span<span){this._span*=1.25;}
calculator.setBounds(calculator.minimumBoundary(),calculator.minimumBoundary()+this._span);this._lastBoundary=new NetworkTimeBoundary(calculator.minimumBoundary(),calculator.maximumBoundary());}
const context=this.context();const linesByType={};const paddingTop=_padding;function drawLines(type){const lines=linesByType[type];if(!lines){return;}
const n=lines.length;context.beginPath();context.strokeStyle=RequestTimeRangeNameToColor[type];for(let i=0;i<n;){const y=lines[i++]*_bandHeight+paddingTop;const startTime=lines[i++];let endTime=lines[i++];if(endTime===Number.MAX_VALUE){endTime=calculator.maximumBoundary();}
context.moveTo(calculator.computePosition(startTime),y);context.lineTo(calculator.computePosition(endTime)+1,y);}
context.stroke();}
function addLine(type,y,start,end){let lines=linesByType[type];if(!lines){lines=[];linesByType[type]=lines;}
lines.push(y,start,end);}
const requests=this._requestsList;const n=requests.length;for(let i=0;i<n;++i){const request=requests[i];const band=this._bandId(request.connectionId);const y=(band===-1)?0:(band%this._numBands+1);const timeRanges=RequestTimingView.calculateRequestTimeRanges(request,this.calculator().minimumBoundary());for(let j=0;j<timeRanges.length;++j){const type=timeRanges[j].name;if(band!==-1||type===RequestTimeRangeNames.Total){addLine(type,y,timeRanges[j].start*1000,timeRanges[j].end*1000);}}}
context.clearRect(0,0,this.width(),this.height());context.save();context.scale(window.devicePixelRatio,window.devicePixelRatio);context.lineWidth=2;drawLines(RequestTimeRangeNames.Total);drawLines(RequestTimeRangeNames.Blocking);drawLines(RequestTimeRangeNames.Connecting);drawLines(RequestTimeRangeNames.ServiceWorker);drawLines(RequestTimeRangeNames.ServiceWorkerPreparation);drawLines(RequestTimeRangeNames.Push);drawLines(RequestTimeRangeNames.Proxy);drawLines(RequestTimeRangeNames.DNS);drawLines(RequestTimeRangeNames.SSL);drawLines(RequestTimeRangeNames.Sending);drawLines(RequestTimeRangeNames.Waiting);drawLines(RequestTimeRangeNames.Receiving);if(this._highlightedRequest){const size=5;const borderSize=2;const request=this._highlightedRequest;const band=this._bandId(request.connectionId);const y=((band===-1)?0:(band%this._numBands+1))*_bandHeight+paddingTop;const timeRanges=RequestTimingView.calculateRequestTimeRanges(request,this.calculator().minimumBoundary());context.fillStyle='#1a73e8';const start=timeRanges[0].start*1000;const end=timeRanges[0].end*1000;context.fillRect(calculator.computePosition(start)-borderSize,y-size/2-borderSize,calculator.computePosition(end)-calculator.computePosition(start)+1+2*borderSize,size*borderSize);for(let j=0;j<timeRanges.length;++j){const type=timeRanges[j].name;if(band!==-1||type===RequestTimeRangeNames.Total){context.beginPath();context.strokeStyle=RequestTimeRangeNameToColor[type];context.lineWidth=size;const start=timeRanges[j].start*1000;const end=timeRanges[j].end*1000;context.moveTo(calculator.computePosition(start)-0,y);context.lineTo(calculator.computePosition(end)+1,y);context.stroke();}}}
const height=this.element.offsetHeight;context.lineWidth=1;context.beginPath();context.strokeStyle=NetworkLogView.getDCLEventColor();for(let i=this._domContentLoadedEvents.length-1;i>=0;--i){const x=Math.round(calculator.computePosition(this._domContentLoadedEvents[i]))+0.5;context.moveTo(x,0);context.lineTo(x,height);}
context.stroke();context.beginPath();context.strokeStyle=NetworkLogView.getLoadEventColor();for(let i=this._loadEvents.length-1;i>=0;--i){const x=Math.round(calculator.computePosition(this._loadEvents[i]))+0.5;context.moveTo(x,0);context.lineTo(x,height);}
context.stroke();if(this._selectedFilmStripTime!==-1){context.lineWidth=2;context.beginPath();context.strokeStyle='#FCCC49';const x=Math.round(calculator.computePosition(this._selectedFilmStripTime));context.moveTo(x,0);context.lineTo(x,height);context.stroke();}
context.restore();}}
const RequestTimeRangeNameToColor={[RequestTimeRangeNames.Total]:'#CCCCCC',[RequestTimeRangeNames.Blocking]:'#AAAAAA',[RequestTimeRangeNames.Connecting]:'#FF9800',[RequestTimeRangeNames.ServiceWorker]:'#FF9800',[RequestTimeRangeNames.ServiceWorkerPreparation]:'#FF9800',[RequestTimeRangeNames.Push]:'#8CDBff',[RequestTimeRangeNames.Proxy]:'#A1887F',[RequestTimeRangeNames.DNS]:'#009688',[RequestTimeRangeNames.SSL]:'#9C27B0',[RequestTimeRangeNames.Sending]:'#B0BEC5',[RequestTimeRangeNames.Waiting]:'#00C853',[RequestTimeRangeNames.Receiving]:'#03A9F4',};const _bandHeight=3;const _padding=5;var NetworkOverview$1=Object.freeze({__proto__:null,NetworkOverview:NetworkOverview,RequestTimeRangeNameToColor:RequestTimeRangeNameToColor,_bandHeight:_bandHeight,_padding:_padding});class NetworkPanel extends Panel.Panel{constructor(){super('network');this.registerRequiredCSS('network/networkPanel.css');this._networkLogShowOverviewSetting=Settings.Settings.instance().createSetting('networkLogShowOverview',true);this._networkLogLargeRowsSetting=Settings.Settings.instance().createSetting('networkLogLargeRows',false);this._networkRecordFilmStripSetting=Settings.Settings.instance().createSetting('networkRecordFilmStripSetting',false);this._toggleRecordAction=(self.UI.actionRegistry.action('network.toggle-recording'));this._pendingStopTimer;this._networkItemView=null;this._filmStripView=null;this._filmStripRecorder=null;this._currentRequest=null;const panel=new Widget.VBox();const networkToolbarContainer=panel.contentElement.createChild('div','network-toolbar-container');this._panelToolbar=new Toolbar.Toolbar('',networkToolbarContainer);this._rightToolbar=new Toolbar.Toolbar('',networkToolbarContainer);this._filterBar=new FilterBar.FilterBar('networkPanel',true);this._filterBar.show(panel.contentElement);this._filterBar.addEventListener(FilterBar.FilterBar.Events.Changed,this._handleFilterChanged.bind(this));this._settingsPane=new Widget.HBox();this._settingsPane.element.classList.add('network-settings-pane');this._settingsPane.show(panel.contentElement);this._showSettingsPaneSetting=Settings.Settings.instance().createSetting('networkShowSettingsToolbar',false);this._showSettingsPaneSetting.addChangeListener(this._updateSettingsPaneVisibility.bind(this));this._updateSettingsPaneVisibility();this._filmStripPlaceholderElement=panel.contentElement.createChild('div','network-film-strip-placeholder');this._overviewPane=new TimelineOverviewPane.TimelineOverviewPane('network');this._overviewPane.addEventListener(TimelineOverviewPane.Events.WindowChanged,this._onWindowChanged.bind(this));this._overviewPane.element.id='network-overview-panel';this._networkOverview=new NetworkOverview();this._overviewPane.setOverviewControls([this._networkOverview]);this._overviewPlaceholderElement=panel.contentElement.createChild('div');this._calculator=new NetworkTransferTimeCalculator();this._splitWidget=new SplitWidget.SplitWidget(true,false,'networkPanelSplitViewState');this._splitWidget.hideMain();this._splitWidget.show(panel.contentElement);panel.setDefaultFocusedChild(this._filterBar);const initialSidebarWidth=225;const splitWidget=new SplitWidget.SplitWidget(true,false,'networkPanelSidebarState',initialSidebarWidth);splitWidget.hideSidebar();splitWidget.enableShowModeSaving();splitWidget.show(this.element);this._sidebarLocation=ViewManager.ViewManager.instance().createTabbedLocation(async()=>{ViewManager.ViewManager.instance().showView('network');splitWidget.showBoth();},'network-sidebar',true);const tabbedPane=this._sidebarLocation.tabbedPane();tabbedPane.setMinimumSize(100,25);tabbedPane.element.classList.add('network-tabbed-pane');tabbedPane.element.addEventListener('keydown',event=>{if(event.key!=='Escape'){return;}
splitWidget.hideSidebar();event.consume();});const closeSidebar=new Toolbar.ToolbarButton(UIString.UIString('Close'),'largeicon-delete');closeSidebar.addEventListener(Toolbar.ToolbarButton.Events.Click,()=>splitWidget.hideSidebar());tabbedPane.rightToolbar().appendToolbarItem(closeSidebar);splitWidget.setSidebarWidget(tabbedPane);splitWidget.setMainWidget(panel);splitWidget.setDefaultFocusedChild(panel);this.setDefaultFocusedChild(splitWidget);this._progressBarContainer=createElement('div');this._networkLogView=new NetworkLogView(this._filterBar,this._progressBarContainer,this._networkLogLargeRowsSetting);this._splitWidget.setSidebarWidget(this._networkLogView);this._fileSelectorElement=UIUtils.createFileSelectorElement(this._networkLogView.onLoadFromFile.bind(this._networkLogView));panel.element.appendChild(this._fileSelectorElement);this._detailsWidget=new Widget.VBox();this._detailsWidget.element.classList.add('network-details-view');this._splitWidget.setMainWidget(this._detailsWidget);this._closeButtonElement=createElement('div','dt-close-button');this._closeButtonElement.addEventListener('click',async()=>await self.UI.actionRegistry.action('network.hide-request-details').execute(),false);this._closeButtonElement.style.margin='0 5px';this._networkLogShowOverviewSetting.addChangeListener(this._toggleShowOverview,this);this._networkLogLargeRowsSetting.addChangeListener(this._toggleLargerRequests,this);this._networkRecordFilmStripSetting.addChangeListener(this._toggleRecordFilmStrip,this);this._preserveLogSetting=Settings.Settings.instance().moduleSetting('network_log.preserve-log');this._throttlingSelect=this._createThrottlingConditionsSelect();this._setupToolbarButtons(splitWidget);this._toggleRecord(true);this._toggleShowOverview();this._toggleLargerRequests();this._toggleRecordFilmStrip();this._updateUI();SDKModel.TargetManager.instance().addModelListener(ResourceTreeModel.ResourceTreeModel,ResourceTreeModel.Events.WillReloadPage,this._willReloadPage,this);SDKModel.TargetManager.instance().addModelListener(ResourceTreeModel.ResourceTreeModel,ResourceTreeModel.Events.Load,this._load,this);this._networkLogView.addEventListener(Events$1.RequestSelected,this._onRequestSelected,this);this._networkLogView.addEventListener(Events$1.RequestActivated,this._onRequestActivated,this);self.SDK.networkLog.addEventListener(NetworkLog.Events.RequestAdded,this._onUpdateRequest,this);self.SDK.networkLog.addEventListener(NetworkLog.Events.RequestUpdated,this._onUpdateRequest,this);self.SDK.networkLog.addEventListener(NetworkLog.Events.Reset,this._onNetworkLogReset,this);}
static revealAndFilter(filters){const panel=NetworkPanel._instance();let filterString='';for(const filter of filters){filterString+=`${filter.filterType}:${filter.filterValue} `;}
panel._networkLogView.setTextFilterValue(filterString);ViewManager.ViewManager.instance().showView('network');}
static async selectAndShowRequest(request,tab){const panel=NetworkPanel._instance();await panel.selectAndActivateRequest(request,tab);}
static _instance(){return(self.runtime.sharedInstance(NetworkPanel));}
throttlingSelectForTest(){return this._throttlingSelect;}
_onWindowChanged(event){const startTime=Math.max(this._calculator.minimumBoundary(),event.data.startTime/1000);const endTime=Math.min(this._calculator.maximumBoundary(),event.data.endTime/1000);this._networkLogView.setWindow(startTime,endTime);}
async _searchToggleClick(event){await self.UI.actionRegistry.action('network.search').execute();}
_setupToolbarButtons(splitWidget){const searchToggle=new Toolbar.ToolbarToggle(ls`Search`,'largeicon-search');function updateSidebarToggle(){const isSidebarShowing=splitWidget.showMode()!==SplitWidget.ShowMode.OnlyMain;searchToggle.setToggled(isSidebarShowing);if(!isSidebarShowing){searchToggle.element.focus();}}
this._panelToolbar.appendToolbarItem(Toolbar.Toolbar.createActionButton(this._toggleRecordAction));const clearButton=new Toolbar.ToolbarButton(UIString.UIString('Clear'),'largeicon-clear');clearButton.addEventListener(Toolbar.ToolbarButton.Events.Click,()=>self.SDK.networkLog.reset(),this);this._panelToolbar.appendToolbarItem(clearButton);this._panelToolbar.appendSeparator();this._panelToolbar.appendToolbarItem(this._filterBar.filterButton());updateSidebarToggle();splitWidget.addEventListener(SplitWidget.Events.ShowModeChanged,updateSidebarToggle);searchToggle.addEventListener(Toolbar.ToolbarButton.Events.Click,event=>{this._searchToggleClick(event);});this._panelToolbar.appendToolbarItem(searchToggle);this._panelToolbar.appendSeparator();this._panelToolbar.appendToolbarItem(new Toolbar.ToolbarSettingCheckbox(this._preserveLogSetting,UIString.UIString('Do not clear log on page reload / navigation'),UIString.UIString('Preserve log')));const disableCacheCheckbox=new Toolbar.ToolbarSettingCheckbox(Settings.Settings.instance().moduleSetting('cacheDisabled'),UIString.UIString('Disable cache (while DevTools is open)'),UIString.UIString('Disable cache'));this._panelToolbar.appendToolbarItem(disableCacheCheckbox);this._panelToolbar.appendSeparator();this._panelToolbar.appendToolbarItem(this._throttlingSelect);this._rightToolbar.appendToolbarItem(new Toolbar.ToolbarItem(this._progressBarContainer));this._rightToolbar.appendSeparator();this._rightToolbar.appendToolbarItem(new Toolbar.ToolbarSettingToggle(this._showSettingsPaneSetting,'largeicon-settings-gear',ls`Network settings`));const settingsToolbarLeft=new Toolbar.Toolbar('',this._settingsPane.element);settingsToolbarLeft.makeVertical();settingsToolbarLeft.appendToolbarItem(new Toolbar.ToolbarSettingCheckbox(this._networkLogLargeRowsSetting,ls`Show more information in request rows`,ls`Use large request rows`));settingsToolbarLeft.appendToolbarItem(new Toolbar.ToolbarSettingCheckbox(this._networkLogShowOverviewSetting,ls`Show overview of network requests`,ls`Show overview`));const settingsToolbarRight=new Toolbar.Toolbar('',this._settingsPane.element);settingsToolbarRight.makeVertical();settingsToolbarRight.appendToolbarItem(new Toolbar.ToolbarSettingCheckbox(Settings.Settings.instance().moduleSetting('network.group-by-frame'),ls`Group requests by top level request frame`,ls`Group by frame`));settingsToolbarRight.appendToolbarItem(new Toolbar.ToolbarSettingCheckbox(this._networkRecordFilmStripSetting,ls`Capture screenshots when loading a page`,ls`Capture screenshots`));this._panelToolbar.appendSeparator();const importHarButton=new Toolbar.ToolbarButton(ls`Import HAR file...`,'largeicon-load');importHarButton.addEventListener(Toolbar.ToolbarButton.Events.Click,()=>this._fileSelectorElement.click(),this);this._panelToolbar.appendToolbarItem(importHarButton);const exportHarButton=new Toolbar.ToolbarButton(ls`Export HAR...`,'largeicon-download');exportHarButton.addEventListener(Toolbar.ToolbarButton.Events.Click,event=>{this._networkLogView.exportAll();},this);this._panelToolbar.appendToolbarItem(exportHarButton);}
_updateSettingsPaneVisibility(){this._settingsPane.element.classList.toggle('hidden',!this._showSettingsPaneSetting.get());}
_createThrottlingConditionsSelect(){const toolbarItem=new Toolbar.ToolbarComboBox(null,ls`Throttling`);toolbarItem.setMaxWidth(160);ThrottlingManager.throttlingManager().decorateSelectWithNetworkThrottling(toolbarItem.selectElement());return toolbarItem;}
_toggleRecording(){if(!this._preserveLogSetting.get()&&!this._toggleRecordAction.toggled()){self.SDK.networkLog.reset();}
this._toggleRecord(!this._toggleRecordAction.toggled());}
_toggleRecord(toggled){this._toggleRecordAction.setToggled(toggled);this._networkLogView.setRecording(toggled);if(!toggled&&this._filmStripRecorder){this._filmStripRecorder.stopRecording(this._filmStripAvailable.bind(this));}
self.SDK.networkLog.setIsRecording(toggled);}
_filmStripAvailable(filmStripModel){if(!filmStripModel){return;}
const calculator=this._networkLogView.timeCalculator();this._filmStripView.setModel(filmStripModel,calculator.minimumBoundary()*1000,calculator.boundarySpan()*1000);this._networkOverview.setFilmStripModel(filmStripModel);const timestamps=filmStripModel.frames().map(mapTimestamp);function mapTimestamp(frame){return frame.timestamp/1000;}
this._networkLogView.addFilmStripFrames(timestamps);}
_onNetworkLogReset(){BlockedURLsPane.reset();if(!this._preserveLogSetting.get()){this._calculator.reset();this._overviewPane.reset();}
if(this._filmStripView){this._resetFilmStripView();}}
_willReloadPage(event){this._toggleRecord(true);if(this._pendingStopTimer){clearTimeout(this._pendingStopTimer);delete this._pendingStopTimer;}
if(this.isShowing()&&this._filmStripRecorder){this._filmStripRecorder.startRecording();}}
_load(event){if(this._filmStripRecorder&&this._filmStripRecorder.isRecording()){this._pendingStopTimer=setTimeout(this._stopFilmStripRecording.bind(this),displayScreenshotDelay);}}
_stopFilmStripRecording(){this._filmStripRecorder.stopRecording(this._filmStripAvailable.bind(this));delete this._pendingStopTimer;}
_toggleLargerRequests(){this._updateUI();}
_toggleShowOverview(){const toggled=this._networkLogShowOverviewSetting.get();if(toggled){this._overviewPane.show(this._overviewPlaceholderElement);}else{this._overviewPane.detach();}
this.doResize();}
_toggleRecordFilmStrip(){const toggled=this._networkRecordFilmStripSetting.get();if(toggled&&!this._filmStripRecorder){this._filmStripView=new FilmStripView.FilmStripView();this._filmStripView.setMode(FilmStripView.Modes.FrameBased);this._filmStripView.element.classList.add('network-film-strip');this._filmStripRecorder=new FilmStripRecorder(this._networkLogView.timeCalculator(),this._filmStripView);this._filmStripView.show(this._filmStripPlaceholderElement);this._filmStripView.addEventListener(FilmStripView.Events.FrameSelected,this._onFilmFrameSelected,this);this._filmStripView.addEventListener(FilmStripView.Events.FrameEnter,this._onFilmFrameEnter,this);this._filmStripView.addEventListener(FilmStripView.Events.FrameExit,this._onFilmFrameExit,this);this._resetFilmStripView();}
if(!toggled&&this._filmStripRecorder){this._filmStripView.detach();this._filmStripView=null;this._filmStripRecorder=null;}}
_resetFilmStripView(){const reloadShortcutDescriptor=self.UI.shortcutRegistry.shortcutDescriptorsForAction('inspector_main.reload')[0];this._filmStripView.reset();if(reloadShortcutDescriptor){this._filmStripView.setStatusText(UIString.UIString('Hit %s to reload and capture filmstrip.',reloadShortcutDescriptor.name));}}
elementsToRestoreScrollPositionsFor(){return this._networkLogView.elementsToRestoreScrollPositionsFor();}
wasShown(){self.UI.context.setFlavor(NetworkPanel,this);userMetrics.panelLoaded('network','DevTools.Launch.Network');}
willHide(){self.UI.context.setFlavor(NetworkPanel,null);}
revealAndHighlightRequest(request){this._hideRequestPanel();if(request){this._networkLogView.revealAndHighlightRequest(request);}}
async selectAndActivateRequest(request,shownTab){await ViewManager.ViewManager.instance().showView('network');this._networkLogView.selectRequest(request);this._showRequestPanel(shownTab);return this._networkItemView;}
_handleFilterChanged(event){this._hideRequestPanel();}
_onRowSizeChanged(event){this._updateUI();}
_onRequestSelected(event){const request=(event.data);this._currentRequest=request;this._networkOverview.setHighlightedRequest(request);this._updateNetworkItemView();}
_onRequestActivated(event){const eventData=(event.data);if(eventData.showPanel){this._showRequestPanel(eventData.tab);}else{this._hideRequestPanel();}}
_showRequestPanel(shownTab){this._clearNetworkItemView();if(this._currentRequest){this._createNetworkItemView(shownTab);}
this._updateUI();}
_hideRequestPanel(){this._clearNetworkItemView();this._splitWidget.hideMain();this._updateUI();}
_updateNetworkItemView(){if(this._splitWidget.showMode()===SplitWidget.ShowMode.Both){this._clearNetworkItemView();this._createNetworkItemView();this._updateUI();}}
_clearNetworkItemView(){if(this._networkItemView){this._networkItemView.detach();this._networkItemView=null;}}
_createNetworkItemView(initialTab){if(!this._currentRequest){return;}
this._networkItemView=new NetworkItemView(this._currentRequest,this._networkLogView.timeCalculator(),initialTab);this._networkItemView.leftToolbar().appendToolbarItem(new Toolbar.ToolbarItem(this._closeButtonElement));this._networkItemView.show(this._detailsWidget.element);this._splitWidget.showBoth();}
_updateUI(){this._detailsWidget.element.classList.toggle('network-details-view-tall-header',this._networkLogLargeRowsSetting.get());this._networkLogView.switchViewMode(!this._splitWidget.isResizable());}
appendApplicableItems(event,contextMenu,target){function reveal(request){ViewManager.ViewManager.instance().showView('network').then(this._networkLogView.resetFilter.bind(this._networkLogView)).then(this.revealAndHighlightRequest.bind(this,request));}
function appendRevealItem(request){contextMenu.revealSection().appendItem(UIString.UIString('Reveal in Network panel'),reveal.bind(this,request));}
if(event.target.isSelfOrDescendant(this.element)){return;}
if(target instanceof Resource.Resource){const resource=(target);if(resource.request){appendRevealItem.call(this,resource.request);}
return;}
if(target instanceof UISourceCode.UISourceCode){const uiSourceCode=(target);const resource=ResourceUtils.resourceForURL(uiSourceCode.url());if(resource&&resource.request){appendRevealItem.call(this,resource.request);}
return;}
if(!(target instanceof NetworkRequest.NetworkRequest)){return;}
const request=(target);if(this._networkItemView&&this._networkItemView.isShowing()&&this._networkItemView.request()===request){return;}
appendRevealItem.call(this,request);}
_onFilmFrameSelected(event){const timestamp=(event.data);this._overviewPane.setWindowTimes(0,timestamp);}
_onFilmFrameEnter(event){const timestamp=(event.data);this._networkOverview.selectFilmStripFrame(timestamp);this._networkLogView.selectFilmStripFrame(timestamp/1000);}
_onFilmFrameExit(event){this._networkOverview.clearFilmStripFrame();this._networkLogView.clearFilmStripFrame();}
_onUpdateRequest(event){const request=(event.data);this._calculator.updateBoundaries(request);this._overviewPane.setBounds(this._calculator.minimumBoundary()*1000,this._calculator.maximumBoundary()*1000);this._networkOverview.updateRequest(request);this._overviewPane.scheduleUpdate();}
resolveLocation(locationName){if(locationName==='network-sidebar'){return this._sidebarLocation;}
return null;}}
const displayScreenshotDelay=1000;class ContextMenuProvider{appendApplicableItems(event,contextMenu,target){NetworkPanel._instance().appendApplicableItems(event,contextMenu,target);}}
class RequestRevealer{reveal(request){if(!(request instanceof NetworkRequest.NetworkRequest)){return Promise.reject(new Error('Internal error: not a network request'));}
const panel=NetworkPanel._instance();return ViewManager.ViewManager.instance().showView('network').then(panel.revealAndHighlightRequest.bind(panel,request));}}
class FilmStripRecorder{constructor(timeCalculator,filmStripView){this._tracingManager=null;this._resourceTreeModel=null;this._timeCalculator=timeCalculator;this._filmStripView=filmStripView;this._tracingModel=null;this._callback=null;}
traceEventsCollected(events){if(this._tracingModel){this._tracingModel.addEvents(events);}}
tracingComplete(){if(!this._tracingModel||!this._tracingManager){return;}
this._tracingModel.tracingComplete();this._tracingManager=null;this._callback(new FilmStripModel.FilmStripModel(this._tracingModel,this._timeCalculator.minimumBoundary()*1000));this._callback=null;if(this._resourceTreeModel){this._resourceTreeModel.resumeReload();}
this._resourceTreeModel=null;}
tracingBufferUsage(){}
eventsRetrievalProgress(progress){}
startRecording(){this._filmStripView.reset();this._filmStripView.setStatusText(UIString.UIString('Recording frames...'));const tracingManagers=SDKModel.TargetManager.instance().models(TracingManager.TracingManager);if(this._tracingManager||!tracingManagers.length){return;}
this._tracingManager=tracingManagers[0];this._resourceTreeModel=this._tracingManager.target().model(ResourceTreeModel.ResourceTreeModel);if(this._tracingModel){this._tracingModel.dispose();}
this._tracingModel=new TracingModel.TracingModel(new TempFile.TempFileBackingStorage());this._tracingManager.start(this,'-*,disabled-by-default-devtools.screenshot','');userMetrics.actionTaken(UserMetrics.Action.FilmStripStartedRecording);}
isRecording(){return!!this._tracingManager;}
stopRecording(callback){if(!this._tracingManager){return;}
this._tracingManager.stop();if(this._resourceTreeModel){this._resourceTreeModel.suspendReload();}
this._callback=callback;this._filmStripView.setStatusText(UIString.UIString('Fetching frames...'));}}
class ActionDelegate{handleAction(context,actionId){const panel=self.UI.context.flavor(NetworkPanel);console.assert(panel&&panel instanceof NetworkPanel);switch(actionId){case'network.toggle-recording':{panel._toggleRecording();return true;}
case'network.hide-request-details':{if(!panel._networkItemView){return false;}
panel._hideRequestPanel();panel._networkLogView.resetFocus();return true;}
case'network.search':{const selection=self.UI.inspectorView.element.window().getSelection();let queryCandidate='';if(selection.rangeCount){queryCandidate=selection.toString().replace(/\r?\n.*/,'');}
SearchNetworkView.openSearch(queryCandidate);return true;}}
return false;}}
class RequestLocationRevealer{async reveal(match){const location=(match);const view=await NetworkPanel._instance().selectAndActivateRequest(location.request);if(!view){return;}
if(location.searchMatch){await view.revealResponseBody(location.searchMatch.lineNumber);}
if(location.requestHeader){view.revealRequestHeader(location.requestHeader.name);}
if(location.responseHeader){view.revealResponseHeader(location.responseHeader.name);}}}
class SearchNetworkView extends SearchView.SearchView{constructor(){super('network');}
static async openSearch(query,searchImmediately){await ViewManager.ViewManager.instance().showView('network.search-network-tab');const searchView=(self.runtime.sharedInstance(SearchNetworkView));searchView.toggle(query,!!searchImmediately);return searchView;}
createScope(){return new NetworkSearchScope();}}
var NetworkPanel$1=Object.freeze({__proto__:null,NetworkPanel:NetworkPanel,displayScreenshotDelay:displayScreenshotDelay,ContextMenuProvider:ContextMenuProvider,RequestRevealer:RequestRevealer,FilmStripRecorder:FilmStripRecorder,ActionDelegate:ActionDelegate,RequestLocationRevealer:RequestLocationRevealer,SearchNetworkView:SearchNetworkView});export{BinaryResourceView$1 as BinaryResourceView,BlockedURLsPane$1 as BlockedURLsPane,EventSourceMessagesView$1 as EventSourceMessagesView,HARWriter$1 as HARWriter,NetworkConfigView$1 as NetworkConfigView,NetworkDataGridNode,NetworkFrameGrouper$1 as NetworkFrameGrouper,NetworkItemView$1 as NetworkItemView,NetworkLogView$1 as NetworkLogView,NetworkLogViewColumns$1 as NetworkLogViewColumns,NetworkManageCustomHeadersView$1 as NetworkManageCustomHeadersView,NetworkOverview$1 as NetworkOverview,NetworkPanel$1 as NetworkPanel,NetworkSearchScope$1 as NetworkSearchScope,NetworkTimeCalculator$1 as NetworkTimeCalculator,NetworkWaterfallColumn$1 as NetworkWaterfallColumn,RequestCookiesView$1 as RequestCookiesView,RequestHTMLView$1 as RequestHTMLView,RequestHeadersView$1 as RequestHeadersView,RequestInitiatorView$1 as RequestInitiatorView,RequestPreviewView$1 as RequestPreviewView,RequestResponseView$1 as RequestResponseView,RequestTimingView$1 as RequestTimingView,ResourceWebSocketFrameView$1 as ResourceWebSocketFrameView,SignedExchangeInfoView$1 as SignedExchangeInfoView};