import{ObjectWrapper as e,EventTarget as t,ParsedURL as s,Settings as i,Linkifier as n}from"../common/common.js";import{i18n as r}from"../i18n/i18n.js";import{SDKModel as o,ServiceWorkerManager as a,RuntimeModel as l,ChildTargetManager as d,DOMModel as h,ResourceTreeModel as c,NetworkManager as u}from"../sdk/sdk.js";import{DeviceModeModel as p,EmulatedDevices as g,InspectedPagePlaceholder as m}from"../emulation/emulation.js";import{userMetrics as _,UserMetrics as f}from"../host/host.js";import{Runtime as b}from"../root/root.js";import{UIUtils as y,Tooltip as v,InspectorView as w,Toolbar as S,ARIAUtils as C,Fragment as T,Widget as x,XLink as L,Dialog as E,Utils as A,GlassPane as k,Geometry as P,Panel as R,DropTarget as M}from"../ui/ui.js";import{serviceManager as I}from"../services/services.js";import{Linkifier as D}from"../components/components.js";import{DateUtilities as O}from"../platform/platform.js";import{ThemeSupport as U}from"../theme_support/theme_support.js";import{TimelinePanel as N}from"../timeline/timeline.js";import{FileManager as B}from"../workspace/workspace.js";
/**
 * @license
 * Copyright 2017 The Lighthouse Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS-IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const F={label:"pass",minScore:.9},H={label:"average",minScore:.5},$={label:"fail"},j={label:"error"},G=["com","co","gov","edu","ac","org","go","gob","or","net","in","ne","nic","gouv","web","spb","blog","jus","kiev","mil","wi","qc","ca","bel","on"];class V{static get PASS_THRESHOLD(){return.9}static get MS_DISPLAY_VALUE(){return"%10d ms"}static prepareReportResult(e){const t=JSON.parse(JSON.stringify(e));t.configSettings.locale||(t.configSettings.locale="en");for(const e of Object.values(t.audits))if("not_applicable"!==e.scoreDisplayMode&&"not-applicable"!==e.scoreDisplayMode||(e.scoreDisplayMode="notApplicable"),e.details&&(void 0!==e.details.type&&"diagnostic"!==e.details.type||(e.details.type="debugdata"),"filmstrip"===e.details.type))for(const t of e.details.items)t.data.startsWith("data:image/jpeg;base64,")||(t.data="data:image/jpeg;base64,"+t.data);if("object"!=typeof t.categories)throw new Error("No categories provided.");for(const e of Object.values(t.categories))e.auditRefs.forEach((e=>{const s=t.audits[e.id];e.result=s,t.stackPacks&&t.stackPacks.forEach((t=>{t.descriptions[e.id]&&(e.stackPacks=e.stackPacks||[],e.stackPacks.push({title:t.title,iconDataURL:t.iconDataURL,description:t.descriptions[e.id]}))}))}));return t}static showAsPassed(e){switch(e.scoreDisplayMode){case"manual":case"notApplicable":return!0;case"error":case"informative":return!1;case"numeric":case"binary":default:return Number(e.score)>=F.minScore}}static calculateRating(e,t){if("manual"===t||"notApplicable"===t)return F.label;if("error"===t)return j.label;if(null===e)return $.label;let s=$.label;return e>=F.minScore?s=F.label:e>=H.minScore&&(s=H.label),s}static splitMarkdownCodeSpans(e){const t=[],s=e.split(/`(.*?)`/g);for(let e=0;e<s.length;e++){const i=s[e];if(!i)continue;const n=e%2!=0;t.push({isCode:n,text:i})}return t}static splitMarkdownLink(e){const t=[],s=e.split(/\[([^\]]+?)\]\((https?:\/\/.*?)\)/g);for(;s.length;){const[e,i,n]=s.splice(0,3);e&&t.push({isLink:!1,text:e}),i&&n&&t.push({isLink:!0,text:i,linkHref:n})}return t}static getURLDisplayName(e,t){const s=void 0!==(t=t||{numPathParts:void 0,preserveQuery:void 0,preserveHost:void 0}).numPathParts?t.numPathParts:2,i=void 0===t.preserveQuery||t.preserveQuery,n=t.preserveHost||!1;let r;if("about:"===e.protocol||"data:"===e.protocol)r=e.href;else{r=e.pathname;const t=r.split("/").filter((e=>e.length));s&&t.length>s&&(r="…"+t.slice(-1*s).join("/")),n&&(r=`${e.host}/${r.replace(/^\//,"")}`),i&&(r=`${r}${e.search}`)}if(r=r.replace(/([a-f0-9]{7})[a-f0-9]{13}[a-f0-9]*/g,"$1…"),r=r.replace(/([a-zA-Z0-9-_]{9})(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])[a-zA-Z0-9-_]{10,}/g,"$1…"),r=r.replace(/(\d{3})\d{6,}/g,"$1…"),r=r.replace(/\u2026+/g,"…"),r.length>64&&r.includes("?")&&(r=r.replace(/\?([^=]*)(=)?.*/,"?$1$2…"),r.length>64&&(r=r.replace(/\?.*/,"?…"))),r.length>64){const e=r.lastIndexOf(".");r=e>=0?r.slice(0,63-(r.length-e))+"…"+r.slice(e):r.slice(0,63)+"…"}return r}static parseURL(e){const t=new URL(e);return{file:V.getURLDisplayName(t),hostname:t.hostname,origin:t.origin}}static createOrReturnURL(e){return e instanceof URL?e:new URL(e)}static getTld(e){const t=e.split(".").slice(-2);return G.includes(t[0])?"."+t.join("."):"."+t[t.length-1]}static getRootDomain(e){const t=V.createOrReturnURL(e).hostname,s=V.getTld(t).split(".");return t.split(".").slice(-s.length).join(".")}static getEnvironmentDisplayValues(e){const t=V.getEmulationDescriptions(e);return[{name:V.i18n.strings.runtimeSettingsDevice,description:t.deviceEmulation},{name:V.i18n.strings.runtimeSettingsNetworkThrottling,description:t.networkThrottling},{name:V.i18n.strings.runtimeSettingsCPUThrottling,description:t.cpuThrottling}]}static getEmulationDescriptions(e){let t,s;const i=e.throttling;switch(e.throttlingMethod){case"provided":t=V.i18n.strings.throttlingProvided,s=V.i18n.strings.throttlingProvided;break;case"devtools":{const{cpuSlowdownMultiplier:e,requestLatencyMs:n}=i;t=V.i18n.formatNumber(e)+"x slowdown (DevTools)",s=V.i18n.formatNumber(n)+" ms HTTP RTT, "+V.i18n.formatNumber(i.downloadThroughputKbps)+" Kbps down, "+V.i18n.formatNumber(i.uploadThroughputKbps)+" Kbps up (DevTools)";break}case"simulate":{const{cpuSlowdownMultiplier:e,rttMs:n,throughputKbps:r}=i;t=V.i18n.formatNumber(e)+"x slowdown (Simulated)",s=V.i18n.formatNumber(n)+" ms TCP RTT, "+V.i18n.formatNumber(r)+" Kbps throughput (Simulated)";break}default:t=V.i18n.strings.runtimeUnknown,s=V.i18n.strings.runtimeUnknown}return{deviceEmulation:"mobile"===e.formFactor?V.i18n.strings.runtimeMobileEmulation:V.i18n.strings.runtimeDesktopEmulation,cpuThrottling:t,networkThrottling:s}}static filterRelevantLines(e,t,s){if(0===t.length)return e.slice(0,2*s+1);const i=new Set;return(t=t.sort(((e,t)=>(e.lineNumber||0)-(t.lineNumber||0)))).forEach((({lineNumber:e})=>{let t=e-s,n=e+s;for(;t<1;)t++,n++;i.has(t-3-1)&&(t-=3);for(let e=t;e<=n;e++){const t=e;i.add(t)}})),e.filter((e=>i.has(e.lineNumber)))}static isPluginCategory(e){return e.startsWith("lighthouse-plugin-")}}V.reportJson=null,V.getUniqueSuffix=(()=>{let e=0;return function(){return e++}})(),V.i18n=null,V.UIStrings={varianceDisclaimer:"Values are estimated and may vary. The [performance score is calculated](https://web.dev/performance-scoring/) directly from these metrics.",calculatorLink:"See calculator.",opportunityResourceColumnLabel:"Opportunity",opportunitySavingsColumnLabel:"Estimated Savings",errorMissingAuditInfo:"Report error: no audit information",errorLabel:"Error!",warningHeader:"Warnings: ",auditGroupExpandTooltip:"Show audits",warningAuditsGroupTitle:"Passed audits but with warnings",passedAuditsGroupTitle:"Passed audits",notApplicableAuditsGroupTitle:"Not applicable",manualAuditsGroupTitle:"Additional items to manually check",toplevelWarningsMessage:"There were issues affecting this run of Lighthouse:",crcInitialNavigation:"Initial Navigation",crcLongestDurationLabel:"Maximum critical path latency:",snippetExpandButtonLabel:"Expand snippet",snippetCollapseButtonLabel:"Collapse snippet",lsPerformanceCategoryDescription:"[Lighthouse](https://developers.google.com/web/tools/lighthouse/) analysis of the current page on an emulated mobile network. Values are estimated and may vary.",labDataTitle:"Lab Data",thirdPartyResourcesLabel:"Show 3rd-party resources",dropdownPrintSummary:"Print Summary",dropdownPrintExpanded:"Print Expanded",dropdownCopyJSON:"Copy JSON",dropdownSaveHTML:"Save as HTML",dropdownSaveJSON:"Save as JSON",dropdownViewer:"Open in Viewer",dropdownSaveGist:"Save as Gist",dropdownDarkTheme:"Toggle Dark Theme",runtimeSettingsTitle:"Runtime Settings",runtimeSettingsUrl:"URL",runtimeSettingsFetchTime:"Fetch Time",runtimeSettingsDevice:"Device",runtimeSettingsNetworkThrottling:"Network throttling",runtimeSettingsCPUThrottling:"CPU throttling",runtimeSettingsChannel:"Channel",runtimeSettingsUA:"User agent (host)",runtimeSettingsUANetwork:"User agent (network)",runtimeSettingsBenchmark:"CPU/Memory Power",runtimeSettingsAxeVersion:"Axe version",footerIssue:"File an issue",runtimeNoEmulation:"No emulation",runtimeMobileEmulation:"Emulated Moto G4",runtimeDesktopEmulation:"Emulated Desktop",runtimeUnknown:"Unknown",throttlingProvided:"Provided by environment"},"undefined"!=typeof module&&module.exports?module.exports=V:self.Util=V;class W{constructor(e){this._document=e,this._lighthouseChannel="unknown"}createElement(e,t,s={}){const i=this._document.createElement(e);return t&&(i.className=t),Object.keys(s).forEach((e=>{const t=s[e];void 0!==t&&i.setAttribute(e,t)})),i}createElementNS(e,t,s,i={}){const n=this._document.createElementNS(e,t);return s&&(n.className=s),Object.keys(i).forEach((e=>{const t=i[e];void 0!==t&&n.setAttribute(e,t)})),n}createFragment(){return this._document.createDocumentFragment()}createChildOf(e,t,s,i){const n=this.createElement(t,s,i);return e.appendChild(n),n}cloneTemplate(e,t){const s=t.querySelector(e);if(!s)throw new Error("Template not found: template"+e);const i=this._document.importNode(s.content,!0);return s.hasAttribute("data-stamped")&&this.findAll("style",i).forEach((e=>e.remove())),s.setAttribute("data-stamped","true"),i}resetTemplates(){this.findAll("template[data-stamped]",this._document).forEach((e=>{e.removeAttribute("data-stamped")}))}convertMarkdownLinkSnippets(e){const t=this.createElement("span");for(const s of V.splitMarkdownLink(e)){if(!s.isLink){t.appendChild(this._document.createTextNode(s.text));continue}const e=new URL(s.linkHref);["https://developers.google.com","https://web.dev"].includes(e.origin)&&(e.searchParams.set("utm_source","lighthouse"),e.searchParams.set("utm_medium",this._lighthouseChannel));const i=this.createElement("a");i.rel="noopener",i.target="_blank",i.textContent=s.text,i.href=e.href,t.appendChild(i)}return t}convertMarkdownCodeSnippets(e){const t=this.createElement("span");for(const s of V.splitMarkdownCodeSpans(e))if(s.isCode){const e=this.createElement("code");e.textContent=s.text,t.appendChild(e)}else t.appendChild(this._document.createTextNode(s.text));return t}setLighthouseChannel(e){this._lighthouseChannel=e}document(){return this._document}isDevTools(){return!!this._document.querySelector(".lh-devtools")}find(e,t){const s=t.querySelector(e);if(null===s)throw new Error(`query ${e} not found`);return s}findAll(e,t){return Array.from(t.querySelectorAll(e))}}"undefined"!=typeof module&&module.exports?module.exports=W:self.DOM=W,function(){var e,t,s,i,n=document.createElement("details"),r="undefined"!=typeof HTMLDetailsElement&&n instanceof HTMLDetailsElement,o="open"in n||r,a="ontoggle"in n,l='\ndetails, summary {\n  display: block;\n}\ndetails:not([open]) > *:not(summary) {\n  display: none;\n}\nsummary::before {\n  content: "►";\n  padding-right: 0.3rem;\n  font-size: 0.6rem;\n  cursor: default;\n}\n[open] > summary::before {\n  content: "▼";\n}\n',d=[],h=d.forEach,c=d.slice;function u(e){(function(e,t){return(e.tagName==t?[e]:[]).concat("function"==typeof e.getElementsByTagName?c.call(e.getElementsByTagName(t)):[])})(e,"SUMMARY").forEach((function(e){var t=_(e,"DETAILS");e.setAttribute("aria-expanded",t.hasAttribute("open")),e.hasAttribute("tabindex")||e.setAttribute("tabindex","0"),e.hasAttribute("role")||e.setAttribute("role","button")}))}function p(e){return!(e.defaultPrevented||e.ctrlKey||e.metaKey||e.shiftKey||e.target.isContentEditable)}function g(e){addEventListener("click",(function(t){if(p(t)&&t.which<=1){var s=_(t.target,"SUMMARY");s&&s.parentNode&&"DETAILS"==s.parentNode.tagName&&e(s.parentNode)}}),!1),addEventListener("keydown",(function(t){if(p(t)&&(13==t.keyCode||32==t.keyCode)){var s=_(t.target,"SUMMARY");s&&s.parentNode&&"DETAILS"==s.parentNode.tagName&&(e(s.parentNode),t.preventDefault())}}),!1)}function m(e){var t=document.createEvent("Event");t.initEvent("toggle",!1,!1),e.dispatchEvent(t)}function _(e,t){if("function"==typeof e.closest)return e.closest(t);for(;e;){if(e.tagName==t)return e;e=e.parentNode}}o||(document.head.insertAdjacentHTML("afterbegin","<style>"+l+"</style>"),e=document.createElement("details").constructor.prototype,t=e.setAttribute,s=e.removeAttribute,i=Object.getOwnPropertyDescriptor(e,"open"),Object.defineProperties(e,{open:{get:function(){return"DETAILS"==this.tagName?this.hasAttribute("open"):i&&i.get?i.get.call(this):void 0},set:function(e){return"DETAILS"==this.tagName?e?this.setAttribute("open",""):this.removeAttribute("open"):i&&i.set?i.set.call(this,e):void 0}},setAttribute:{value:function(e,s){var i=this,n=function(){return t.call(i,e,s)};if("open"==e&&"DETAILS"==this.tagName){var r=this.hasAttribute("open"),o=n();if(!r){var a=this.querySelector("summary");a&&a.setAttribute("aria-expanded",!0),m(this)}return o}return n()}},removeAttribute:{value:function(e){var t=this,i=function(){return s.call(t,e)};if("open"==e&&"DETAILS"==this.tagName){var n=this.hasAttribute("open"),r=i();if(n){var o=this.querySelector("summary");o&&o.setAttribute("aria-expanded",!1),m(this)}return r}return i()}}}),g((function(e){e.hasAttribute("open")?e.removeAttribute("open"):e.setAttribute("open","")})),u(document),window.MutationObserver?new MutationObserver((function(e){h.call(e,(function(e){h.call(e.addedNodes,u)}))})).observe(document.documentElement,{subtree:!0,childList:!0}):document.addEventListener("DOMNodeInserted",(function(e){u(e.target)}))),o&&!a&&(window.MutationObserver?new MutationObserver((function(e){h.call(e,(function(e){var t=e.target,s=e.attributeName;"DETAILS"==t.tagName&&"open"==s&&m(t)}))})).observe(document.documentElement,{attributes:!0,subtree:!0}):g((function(e){var t=e.getAttribute("open");setTimeout((function(){var s=e.getAttribute("open");t!=s&&m(e)}),1)})))}();const q=["http://","https://","data:"];class z{constructor(e,t={}){this._dom=e,this._fullPageScreenshot=t.fullPageScreenshot,this._templateContext}setTemplateContext(e){this._templateContext=e}render(e){switch(e.type){case"filmstrip":return this._renderFilmstrip(e);case"list":return this._renderList(e);case"table":return this._renderTable(e);case"criticalrequestchain":return J.render(this._dom,this._templateContext,e,this);case"opportunity":return this._renderTable(e);case"screenshot":case"debugdata":case"full-page-screenshot":return null;default:return this._renderUnknown(e.type,e)}}_renderBytes(e){const t=V.i18n.formatBytesToKiB(e.value,e.granularity),s=this._renderText(t);return s.title=V.i18n.formatBytes(e.value),s}_renderMilliseconds(e){let t=V.i18n.formatMilliseconds(e.value,e.granularity);return"duration"===e.displayUnit&&(t=V.i18n.formatDuration(e.value)),this._renderText(t)}renderTextURL(e){const t=e;let s,i,n;try{const e=V.parseURL(t);s="/"===e.file?e.origin:e.file,i="/"===e.file||""===e.hostname?"":`(${e.hostname})`,n=t}catch(e){s=t}const r=this._dom.createElement("div","lh-text__url");if(r.appendChild(this._renderLink({text:s,url:t})),i){const e=this._renderText(i);e.classList.add("lh-text__url-host"),r.appendChild(e)}return n&&(r.title=t,r.dataset.url=t),r}_renderLink(e){let t;try{t=new URL(e.url)}catch(e){}if(!t||!["https:","http:"].includes(t.protocol)){const t=this._renderText(e.text);return t.classList.add("lh-link"),t}const s=this._dom.createElement("a");return s.rel="noopener",s.target="_blank",s.textContent=e.text,s.href=t.href,s.classList.add("lh-link"),s}_renderText(e){const t=this._dom.createElement("div","lh-text");return t.textContent=e,t}_renderNumeric(e){const t=V.i18n.formatNumber(e.value,e.granularity),s=this._dom.createElement("div","lh-numeric");return s.textContent=t,s}_renderThumbnail(e){const t=this._dom.createElement("img","lh-thumbnail"),s=e;return t.src=s,t.title=s,t.alt="",t}_renderUnknown(e,t){console.error("Unknown details type: "+e,t);const s=this._dom.createElement("details","lh-unknown");return this._dom.createChildOf(s,"summary").textContent=`We don't know how to render audit details of type \`${e}\`. The Lighthouse version that collected this data is likely newer than the Lighthouse version of the report renderer. Expand for the raw JSON.`,this._dom.createChildOf(s,"pre").textContent=JSON.stringify(t,null,2),s}_renderTableValue(e,t){if(null==e)return null;if("object"==typeof e)switch(e.type){case"code":return this._renderCode(e.value);case"link":return this._renderLink(e);case"node":return this.renderNode(e);case"numeric":return this._renderNumeric(e);case"source-location":return this.renderSourceLocation(e);case"url":return this.renderTextURL(e.value);default:return this._renderUnknown(e.type,e)}switch(t.valueType){case"bytes":{const s=Number(e);return this._renderBytes({value:s,granularity:t.granularity})}case"code":{const t=String(e);return this._renderCode(t)}case"ms":{const s={value:Number(e),granularity:t.granularity,displayUnit:t.displayUnit};return this._renderMilliseconds(s)}case"numeric":{const s=Number(e);return this._renderNumeric({value:s,granularity:t.granularity})}case"text":{const t=String(e);return this._renderText(t)}case"thumbnail":{const t=String(e);return this._renderThumbnail(t)}case"timespanMs":{const t=Number(e);return this._renderMilliseconds({value:t})}case"url":{const t=String(e);return q.some((e=>t.startsWith(e)))?this.renderTextURL(t):this._renderCode(t)}default:return this._renderUnknown(t.valueType,e)}}_getCanonicalizedHeadingsFromTable(e){return"opportunity"===e.type?e.headings:e.headings.map((e=>this._getCanonicalizedHeading(e)))}_getCanonicalizedHeading(e){let t;return e.subItemsHeading&&(t=this._getCanonicalizedsubItemsHeading(e.subItemsHeading,e)),{key:e.key,valueType:e.itemType,subItemsHeading:t,label:e.text,displayUnit:e.displayUnit,granularity:e.granularity}}_getCanonicalizedsubItemsHeading(e,t){return e.key||console.warn("key should not be null"),{key:e.key||"",valueType:e.itemType||t.itemType,granularity:e.granularity||t.granularity,displayUnit:e.displayUnit||t.displayUnit}}_getDerivedsubItemsHeading(e){return e.subItemsHeading?{key:e.subItemsHeading.key||"",valueType:e.subItemsHeading.valueType||e.valueType,granularity:e.subItemsHeading.granularity||e.granularity,displayUnit:e.subItemsHeading.displayUnit||e.displayUnit,label:""}:null}_renderTableRow(e,t){const s=this._dom.createElement("tr");for(const i of t){if(!i||!i.key){this._dom.createChildOf(s,"td","lh-table-column--empty");continue}const t=e[i.key];let n;if(null!=t&&(n=this._renderTableValue(t,i)),n){const e="lh-table-column--"+i.valueType;this._dom.createChildOf(s,"td",e).appendChild(n)}else this._dom.createChildOf(s,"td","lh-table-column--empty")}return s}_renderTableRowsFromItem(e,t){const s=this._dom.createFragment();if(s.append(this._renderTableRow(e,t)),!e.subItems)return s;const i=t.map(this._getDerivedsubItemsHeading);if(!i.some(Boolean))return s;for(const t of e.subItems.items){const e=this._renderTableRow(t,i);e.classList.add("lh-sub-item-row"),s.append(e)}return s}_renderTable(e){if(!e.items.length)return this._dom.createElement("span");const t=this._dom.createElement("table","lh-table"),s=this._dom.createChildOf(t,"thead"),i=this._dom.createChildOf(s,"tr"),n=this._getCanonicalizedHeadingsFromTable(e);for(const e of n){const t="lh-table-column--"+(e.valueType||"text"),s=this._dom.createElement("div","lh-text");s.textContent=e.label,this._dom.createChildOf(i,"th",t).appendChild(s)}const r=this._dom.createChildOf(t,"tbody");let o=!0;for(const t of e.items){const e=this._renderTableRowsFromItem(t,n);for(const t of this._dom.findAll("tr",e))t.classList.add(o?"lh-row--even":"lh-row--odd");o=!o,r.append(e)}return t}_renderList(e){const t=this._dom.createElement("div","lh-list");return e.items.forEach((e=>{const s=ae.render(this._dom,this._templateContext,e,this);t.appendChild(s)})),t}renderNode(e){const t=this._dom.createElement("span","lh-node");if(e.nodeLabel){const s=this._dom.createElement("div");s.textContent=e.nodeLabel,t.appendChild(s)}if(e.snippet){const s=this._dom.createElement("div");s.classList.add("lh-node__snippet"),s.textContent=e.snippet,t.appendChild(s)}if(e.selector&&(t.title=e.selector),e.path&&t.setAttribute("data-path",e.path),e.selector&&t.setAttribute("data-selector",e.selector),e.snippet&&t.setAttribute("data-snippet",e.snippet),!this._fullPageScreenshot)return t;const s=(e.lhId?this._fullPageScreenshot.nodes[e.lhId]:null)||e.boundingRect;if(!s)return t;const i=de.render(this._dom,this._templateContext,this._fullPageScreenshot.screenshot,s,{width:147,height:100});return i&&t.prepend(i),t}renderSourceLocation(e){if(!e.url)return null;const t=e.line+1,s=e.column;let i;return"network"===e.urlProvider?(i=this.renderTextURL(e.url),this._dom.find(".lh-link",i).textContent+=`:${t}:${s}`):i=this._renderText(`${e.url}:${t}:${s} (from sourceURL)`),i.classList.add("lh-source-location"),i.setAttribute("data-source-url",e.url),i.setAttribute("data-source-line",String(e.line)),i.setAttribute("data-source-column",String(e.column)),i}_renderFilmstrip(e){const t=this._dom.createElement("div","lh-filmstrip");for(const s of e.items){const e=this._dom.createChildOf(t,"div","lh-filmstrip__frame");this._dom.createChildOf(e,"img","lh-filmstrip__thumbnail",{src:s.data,alt:"Screenshot"})}return t}_renderCode(e){const t=this._dom.createElement("pre","lh-code");return t.textContent=e,t}}"undefined"!=typeof module&&module.exports?module.exports=z:self.DetailsRenderer=z;class J{static initTree(e){let t=0;const s=Object.keys(e);if(s.length>0){t=e[s[0]].request.startTime}return{tree:e,startTime:t,transferSize:0}}static createSegment(e,t,s,i,n,r){const o=e[t],a=Object.keys(e),l=a.indexOf(t)===a.length-1,d=!!o.children&&Object.keys(o.children).length>0,h=Array.isArray(n)?n.slice(0):[];return void 0!==r&&h.push(!r),{node:o,isLastChild:l,hasChildren:d,startTime:s,transferSize:i+o.request.transferSize,treeMarkers:h}}static createChainNode(e,t,s,i){const n=e.cloneTemplate("#tmpl-lh-crc__chains",t);e.find(".crc-node",n).setAttribute("title",s.node.request.url);const r=e.find(".crc-node__tree-marker",n);s.treeMarkers.forEach((t=>{t?(r.appendChild(e.createElement("span","tree-marker vert")),r.appendChild(e.createElement("span","tree-marker"))):(r.appendChild(e.createElement("span","tree-marker")),r.appendChild(e.createElement("span","tree-marker")))})),s.isLastChild?(r.appendChild(e.createElement("span","tree-marker up-right")),r.appendChild(e.createElement("span","tree-marker right"))):(r.appendChild(e.createElement("span","tree-marker vert-right")),r.appendChild(e.createElement("span","tree-marker right"))),s.hasChildren?r.appendChild(e.createElement("span","tree-marker horiz-down")):r.appendChild(e.createElement("span","tree-marker right"));const o=s.node.request.url,a=i.renderTextURL(o),l=e.find(".crc-node__tree-value",n);if(l.appendChild(a),!s.hasChildren){const{startTime:t,endTime:i,transferSize:n}=s.node.request,r=e.createElement("span","crc-node__chain-duration");r.textContent=" - "+V.i18n.formatMilliseconds(1e3*(i-t))+", ";const o=e.createElement("span","crc-node__chain-duration");o.textContent=V.i18n.formatBytesToKiB(n,.01),l.appendChild(r),l.appendChild(o)}return n}static buildTree(e,t,s,i,n,r){if(i.appendChild(K.createChainNode(e,t,s,r)),s.node.children)for(const o of Object.keys(s.node.children)){const a=K.createSegment(s.node.children,o,s.startTime,s.transferSize,s.treeMarkers,s.isLastChild);K.buildTree(e,t,a,i,n,r)}}static render(e,t,s,i){const n=e.cloneTemplate("#tmpl-lh-crc",t),r=e.find(".lh-crc",n);e.find(".crc-initial-nav",n).textContent=V.i18n.strings.crcInitialNavigation,e.find(".lh-crc__longest_duration_label",n).textContent=V.i18n.strings.crcLongestDurationLabel,e.find(".lh-crc__longest_duration",n).textContent=V.i18n.formatMilliseconds(s.longestChain.duration);const o=K.initTree(s.chains);for(const t of Object.keys(o.tree)){const a=K.createSegment(o.tree,t,o.startTime,o.transferSize);K.buildTree(e,n,a,r,s,i)}return e.find(".lh-crc-container",n)}}const K=J;"undefined"!=typeof module&&module.exports?module.exports=J:self.CriticalRequestChainRenderer=J;const Y=0,Q=1,Z=2,X=0,ee=1,te=2,se=3,ie={[X]:["lh-snippet__line--content"],[ee]:["lh-snippet__line--content","lh-snippet__line--content-highlighted"],[te]:["lh-snippet__line--placeholder"],[se]:["lh-snippet__line--message"]};function ne(e,t){return{line:e.find((e=>e.lineNumber===t)),previousLine:e.find((e=>e.lineNumber===t-1))}}function re(e,t){return e.filter((e=>e.lineNumber===t))}function oe(e){return V.filterRelevantLines(e.lines,e.lineMessages,2)}class ae{static renderHeader(e,t,s,i,n){const r=oe(s).length<s.lines.length,o=e.cloneTemplate("#tmpl-lh-snippet__header",t);e.find(".lh-snippet__title",o).textContent=s.title;const{snippetCollapseButtonLabel:a,snippetExpandButtonLabel:l}=V.i18n.strings;e.find(".lh-snippet__btn-label-collapse",o).textContent=a,e.find(".lh-snippet__btn-label-expand",o).textContent=l;const d=e.find(".lh-snippet__toggle-expand",o);if(r?d.addEventListener("click",(()=>n())):d.remove(),s.node&&e.isDevTools()){e.find(".lh-snippet__node",o).appendChild(i.renderNode(s.node))}return o}static renderSnippetLine(e,t,{content:s,lineNumber:i,truncated:n,contentType:r,visibility:o}){const a=e.cloneTemplate("#tmpl-lh-snippet__line",t),l=e.find(".lh-snippet__line",a),{classList:d}=l;ie[r].forEach((e=>d.add(e))),o===Q?d.add("lh-snippet__show-if-collapsed"):o===Z&&d.add("lh-snippet__show-if-expanded");const h=s+(n?"…":""),c=e.find(".lh-snippet__line code",l);return r===se?c.appendChild(e.convertMarkdownLinkSnippets(h)):c.textContent=h,e.find(".lh-snippet__line-number",l).textContent=i.toString(),l}static renderMessage(e,t,s){return ae.renderSnippetLine(e,t,{lineNumber:" ",content:s.message,contentType:se})}static renderOmittedLinesPlaceholder(e,t,s){return ae.renderSnippetLine(e,t,{lineNumber:"…",content:"",visibility:s,contentType:te})}static renderSnippetContent(e,t,s){const i=e.cloneTemplate("#tmpl-lh-snippet__content",t),n=e.find(".lh-snippet__snippet-inner",i);return s.generalMessages.forEach((s=>n.append(ae.renderMessage(e,t,s)))),n.append(ae.renderSnippetLines(e,t,s)),i}static renderSnippetLines(e,t,s){const{lineMessages:i,generalMessages:n,lineCount:r,lines:o}=s,a=oe(s),l=n.length>0&&0===i.length,d=e.createFragment();let h=!1;for(let s=1;s<=r;s++){const{line:n,previousLine:r}=ne(o,s),{line:c,previousLine:u}=ne(a,s),p=!!c;!!u&&!p&&(h=!0),p&&h&&(d.append(ae.renderOmittedLinesPlaceholder(e,t,Q)),h=!1);const g=!n&&1===s;if(!n&&!!r||g){const i=!a.some((e=>e.lineNumber>s))||1===s;d.append(ae.renderOmittedLinesPlaceholder(e,t,i?Z:Y)),h=!1}if(!n)continue;const m=re(i,s),_=m.length>0||l,f=Object.assign({},n,{contentType:_?ee:X,visibility:c?Y:Z});d.append(ae.renderSnippetLine(e,t,f)),m.forEach((s=>{d.append(ae.renderMessage(e,t,s))}))}return d}static render(e,t,s,i){const n=e.cloneTemplate("#tmpl-lh-snippet",t),r=e.find(".lh-snippet",n),o=ae.renderHeader(e,n,s,i,(()=>r.classList.toggle("lh-snippet--expanded"))),a=ae.renderSnippetContent(e,n,s);return r.append(o,a),r}}function le(e,t,s){return e<t?t:e>s?s:e}"undefined"!=typeof module&&module.exports?module.exports=ae:self.SnippetRenderer=ae;class de{static getScreenshotPositions(e,t,s){const i={x:(n=e).left+n.width/2,y:n.top+n.height/2};var n;const r=le(i.x-t.width/2,0,s.width-t.width),o=le(i.y-t.height/2,0,s.height-t.height);return{screenshot:{left:r,top:o},clip:{left:e.left-r,top:e.top-o}}}static renderClipPathInScreenshot(e,t,s,i,n){const r=e.find("clipPath",t),o="clip-"+V.getUniqueSuffix();r.id=o,t.style.clipPath=`url(#${o})`;const a=s.top/n.height,l=a+i.height/n.height,d=s.left/n.width,h=d+i.width/n.width,c=[`0,0             1,0            1,${a}          0,${a}`,`0,${l}     1,${l}    1,1               0,1`,`0,${a}        ${d},${a} ${d},${l} 0,${l}`,`${h},${a} 1,${a}       1,${l}       ${h},${l}`];for(const t of c)r.append(e.createElementNS("http://www.w3.org/2000/svg","polygon",void 0,{points:t}))}static createBackgroundImageStyle(e,t){const s=e.createElement("style");return s.id="full-page-screenshot-style",s.textContent=`\n      .lh-element-screenshot__image {\n        background-image: url(${t.data})\n      }`,s}static installOverlayFeature(e,t,s){const i=e.find(".lh-root",e.document());if(!i)return void console.warn("No lh-root. Overlay install failed.");const n="lh-screenshot-overlay--enabled";i.classList.contains(n)||(i.classList.add(n),i.addEventListener("click",(n=>{const r=n.target;if(!r)return;const o=r.closest(".lh-node > .lh-element-screenshot");if(!o)return;const a=e.createElement("div","lh-element-screenshot__overlay");i.append(a);const l={width:.95*a.clientWidth,height:.8*a.clientHeight},d={width:Number(o.dataset.rectWidth),height:Number(o.dataset.rectHeight),left:Number(o.dataset.rectLeft),right:Number(o.dataset.rectLeft)+Number(o.dataset.rectWidth),top:Number(o.dataset.rectTop),bottom:Number(o.dataset.rectTop)+Number(o.dataset.rectHeight)},h=de.render(e,t,s.screenshot,d,l);h?(a.appendChild(h),a.addEventListener("click",(()=>a.remove()))):a.remove()})))}static _computeZoomFactor(e,t){const s={x:t.width/e.width,y:t.height/e.height},i=.75*Math.min(s.x,s.y);return Math.min(1,i)}static render(e,t,s,i,n){if(!function(e,t){return t.left<=e.width&&0<=t.right&&t.top<=e.height&&0<=t.bottom}(s,i))return null;const r=e.cloneTemplate("#tmpl-lh-element-screenshot",t),o=e.find(".lh-element-screenshot",r);o.dataset.rectWidth=i.width.toString(),o.dataset.rectHeight=i.height.toString(),o.dataset.rectLeft=i.left.toString(),o.dataset.rectTop=i.top.toString();const a=this._computeZoomFactor(i,n),l={width:n.width/a,height:n.height/a};l.width=Math.min(s.width,l.width);const d=l.width*a,h=l.height*a,c=de.getScreenshotPositions(i,l,{width:s.width,height:s.height});e.find(".lh-element-screenshot__content",o).style.top=`-${h}px`;const u=e.find(".lh-element-screenshot__image",o);u.style.width=d+"px",u.style.height=h+"px",u.style.backgroundPositionY=-c.screenshot.top*a+"px",u.style.backgroundPositionX=-c.screenshot.left*a+"px",u.style.backgroundSize=`${s.width*a}px ${s.height*a}px`;const p=e.find(".lh-element-screenshot__element-marker",o);p.style.width=i.width*a+"px",p.style.height=i.height*a+"px",p.style.left=c.clip.left*a+"px",p.style.top=c.clip.top*a+"px";const g=e.find(".lh-element-screenshot__mask",o);return g.style.width=d+"px",g.style.height=h+"px",de.renderClipPathInScreenshot(e,g,c.clip,i,l),o}}function he(e){const t=new URL(e.finalUrl).hostname,s=e.fetchTime&&new Date(e.fetchTime)||new Date,i=s.toLocaleTimeString("en-US",{hour12:!1}),n=s.toLocaleDateString("en-US",{year:"numeric",month:"2-digit",day:"2-digit"}).split("/");n.unshift(n.pop());return`${t}_${n.join("-")}_${i}`.replace(/[/?<>\\:*|"]/g,"-")}"undefined"!=typeof module&&module.exports?module.exports=de:self.ElementScreenshotRenderer=de,"undefined"!=typeof module&&module.exports&&(module.exports={getFilenamePrefix:he});class ce{constructor(e){this.el=e,this._id=void 0}log(e,t=!0){this._id&&clearTimeout(this._id),this.el.textContent=e,this.el.classList.add("show"),t&&(this._id=setTimeout((e=>{this.el.classList.remove("show")}),7e3))}warn(e){this.log("Warning: "+e)}error(e){this.log(e),setTimeout((t=>{throw new Error(e)}),0)}hide(){this._id&&clearTimeout(this._id),this.el.classList.remove("show")}}function ue(){const e=window.location.host.endsWith(".vercel.app"),t=new URLSearchParams(window.location.search).has("dev");return e?`https://${window.location.host}/gh-pages`:t?"http://localhost:8000":"https://googlechrome.github.io/lighthouse"}"undefined"!=typeof module&&module.exports&&(module.exports=ce);class pe{constructor(e){this.json,this._dom=e,this._document=this._dom.document(),this._templateContext=this._dom.document(),this._dropDown=new ge(this._dom),this._copyAttempt=!1,this.topbarEl,this.scoreScaleEl,this.stickyHeaderEl,this.highlightEl,this.onMediaQueryChange=this.onMediaQueryChange.bind(this),this.onCopy=this.onCopy.bind(this),this.onDropDownMenuClick=this.onDropDownMenuClick.bind(this),this.onKeyUp=this.onKeyUp.bind(this),this.collapseAllDetails=this.collapseAllDetails.bind(this),this.expandAllDetails=this.expandAllDetails.bind(this),this._toggleDarkTheme=this._toggleDarkTheme.bind(this),this._updateStickyHeaderOnScroll=this._updateStickyHeaderOnScroll.bind(this)}initFeatures(e){this.json=e,this._setupMediaQueryListeners(),this._dropDown.setup(this.onDropDownMenuClick),this._setupThirdPartyFilter(),this._setupElementScreenshotOverlay(),this._setUpCollapseDetailsAfterPrinting(),this._resetUIState(),this._document.addEventListener("keyup",this.onKeyUp),this._document.addEventListener("copy",this.onCopy);this._dom.find(".lh-topbar__logo",this._document).addEventListener("click",(()=>this._toggleDarkTheme()));let t=!1;!this._dom.isDevTools()&&window.matchMedia("(prefers-color-scheme: dark)").matches&&(t=!0);if(["performance","accessibility","best-practices","seo"].every((t=>{const s=e.categories[t];return s&&1===s.score}))&&(t=!0,this._enableFireworks()),t&&this._toggleDarkTheme(!0),Object.keys(this.json.categories).length>=2){this._setupStickyHeaderElements();const e=this._dom.find(".lh-container",this._document);if(this._getScrollParent(e).addEventListener("scroll",this._updateStickyHeaderOnScroll),this._dom.isDevTools()){new window.ResizeObserver(this._updateStickyHeaderOnScroll).observe(e)}else window.addEventListener("resize",this._updateStickyHeaderOnScroll)}if(e.categories.performance&&e.categories.performance.auditRefs.some((t=>Boolean("metrics"===t.group&&e.audits[t.id].errorMessage)))){this._dom.find(".lh-metrics-toggle__input",this._document).checked=!0}for(const e of this._dom.findAll("[data-i18n]",this._dom.document())){const t=e.getAttribute("data-i18n");e.textContent=V.i18n.strings[t]}}setTemplateContext(e){this._templateContext=e}_getScrollParent(e){const{overflowY:t}=window.getComputedStyle(e);return"visible"!==t&&"hidden"!==t?e:e.parentElement?this._getScrollParent(e.parentElement):document}_enableFireworks(){const e=this._dom.find(".lh-scores-container",this._document);e.classList.add("score100"),e.addEventListener("click",(t=>{e.classList.toggle("fireworks-paused")}))}_fireEventOn(e,t=this._document,s){const i=new CustomEvent(e,s?{detail:s}:void 0);t.dispatchEvent(i)}_setupMediaQueryListeners(){const e=self.matchMedia("(max-width: 500px)");e.addListener(this.onMediaQueryChange),this.onMediaQueryChange(e)}onMediaQueryChange(e){this._dom.find(".lh-root",this._document).classList.toggle("lh-narrow",e.matches)}_setupThirdPartyFilter(){const e=["uses-rel-preconnect","third-party-facades"],t=["legacy-javascript"];Array.from(this._document.querySelectorAll(".lh-table")).filter((e=>e.querySelector("td.lh-table-column--url, td.lh-table-column--source-location"))).filter((t=>{const s=t.closest(".lh-audit");if(!s)throw new Error(".lh-table not within audit");return!e.includes(s.id)})).forEach(((e,s)=>{const i=function(e){return Array.from(e.tBodies[0].rows)}(e),n=this._getThirdPartyRows(i,this.json.finalUrl),r=this._dom.cloneTemplate("#tmpl-lh-3p-filter",this._templateContext),o=this._dom.find("input",r),a="lh-3p-filter-label--"+s;o.id=a,o.addEventListener("change",(e=>{const t=e.target instanceof HTMLInputElement&&!e.target.checked;let s=!0,r=i[0];for(;r;){const e=t&&n.includes(r);do{r.classList.toggle("lh-row--hidden",e),r.classList.toggle("lh-row--even",!e&&s),r.classList.toggle("lh-row--odd",!e&&!s),r=r.nextElementSibling}while(r&&r.classList.contains("lh-sub-item-row"));e||(s=!s)}})),this._dom.find("label",r).setAttribute("for",a),this._dom.find(".lh-3p-filter-count",r).textContent=""+n.length,this._dom.find(".lh-3p-ui-string",r).textContent=V.i18n.strings.thirdPartyResourcesLabel;const l=n.length===i.length,d=!n.length;if((l||d)&&(o.disabled=!0,o.checked=l),!e.parentNode)return;e.parentNode.insertBefore(r,e);const h=e.closest(".lh-audit");if(!h)throw new Error(".lh-table not within audit");t.includes(h.id)&&!l&&o.click()}))}_setupElementScreenshotOverlay(){const e=this.json.audits["full-page-screenshot"]&&this.json.audits["full-page-screenshot"].details&&"full-page-screenshot"===this.json.audits["full-page-screenshot"].details.type&&this.json.audits["full-page-screenshot"].details;e&&de.installOverlayFeature(this._dom,this._templateContext,e)}_getThirdPartyRows(e,t){const s=[],i=V.getRootDomain(t);for(const t of e){if(t.classList.contains("lh-sub-item-row"))continue;const e=t.querySelector(".lh-text__url");if(!e)continue;const n=e.dataset.url;if(!n)continue;V.getRootDomain(n)!==i&&s.push(t)}return s}_getUrlItems(e){return this._dom.findAll(".lh-text__url",e)}_setupStickyHeaderElements(){this.topbarEl=this._dom.find(".lh-topbar",this._document),this.scoreScaleEl=this._dom.find(".lh-scorescale",this._document),this.stickyHeaderEl=this._dom.find(".lh-sticky-header",this._document),this.highlightEl=this._dom.createChildOf(this.stickyHeaderEl,"div","lh-highlighter")}onCopy(e){this._copyAttempt&&e.clipboardData&&(e.preventDefault(),e.clipboardData.setData("text/plain",JSON.stringify(this.json,null,2)),this._fireEventOn("lh-log",this._document,{cmd:"log",msg:"Report JSON copied to clipboard"})),this._copyAttempt=!1}onCopyButtonClick(){this._fireEventOn("lh-analytics",this._document,{cmd:"send",fields:{hitType:"event",eventCategory:"report",eventAction:"copy"}});try{this._document.queryCommandSupported("copy")&&(this._copyAttempt=!0,this._document.execCommand("copy")||(this._copyAttempt=!1,this._fireEventOn("lh-log",this._document,{cmd:"warn",msg:"Your browser does not support copy to clipboard."})))}catch(e){this._copyAttempt=!1,this._fireEventOn("lh-log",this._document,{cmd:"log",msg:e.message})}}_resetUIState(){this._dropDown.close(),this._dom.resetTemplates()}onDropDownMenuClick(e){e.preventDefault();const t=e.target;if(t&&t.hasAttribute("data-action")){switch(t.getAttribute("data-action")){case"copy":this.onCopyButtonClick();break;case"print-summary":this.collapseAllDetails(),this._print();break;case"print-expanded":this.expandAllDetails(),this._print();break;case"save-json":{const e=JSON.stringify(this.json,null,2);this._saveFile(new Blob([e],{type:"application/json"}));break}case"save-html":{const t=this.getReportHtml();try{this._saveFile(new Blob([t],{type:"text/html"}))}catch(e){this._fireEventOn("lh-log",this._document,{cmd:"error",msg:"Could not export as HTML. "+e.message})}break}case"open-viewer":pe.openTabAndSendJsonReportToViewer(this.json);break;case"save-gist":this.saveAsGist();break;case"toggle-dark":this._toggleDarkTheme()}this._dropDown.close()}}_print(){self.print()}onKeyUp(e){(e.ctrlKey||e.metaKey)&&80===e.keyCode&&this._dropDown.close()}static openTabAndSendJsonReportToViewer(e){const t=e.generatedTime,s=e.fetchTime||t,i=`${e.lighthouseVersion}-${e.requestedUrl}-${s}`,n=ue()+"/viewer/";pe.openTabAndSendData({lhr:e},n,i)}static openTreemap(e){if(!e.audits["script-treemap-data"].details)throw new Error("no script treemap data found");const t="treemap-"+e.requestedUrl,s={lhr:e},i=ue()+"/treemap/";pe.openTabAndSendData(s,i,t)}static openTabAndSendData(e,t,s){const i=new URL(t).origin;window.addEventListener("message",(function t(s){s.origin===i&&n&&s.data.opened&&(n.postMessage(e,i),window.removeEventListener("message",t))}));const n=window.open(t,s)}expandAllDetails(){this._dom.findAll(".lh-categories details",this._document).map((e=>e.open=!0))}collapseAllDetails(){this._dom.findAll(".lh-categories details",this._document).map((e=>e.open=!1))}_setUpCollapseDetailsAfterPrinting(){"onbeforeprint"in self?self.addEventListener("afterprint",this.collapseAllDetails):self.matchMedia("print").addListener((e=>{e.matches?this.expandAllDetails():this.collapseAllDetails()}))}getReportHtml(){return this._resetUIState(),this._document.documentElement.outerHTML}saveAsGist(){throw new Error("Cannot save as gist from base report")}_saveFile(e){const t=he({finalUrl:this.json.finalUrl,fetchTime:this.json.fetchTime}),s=e.type.match("json")?".json":".html",i=URL.createObjectURL(e),n=this._dom.createElement("a");n.download=`${t}${s}`,n.href=i,this._document.body.appendChild(n),n.click(),this._document.body.removeChild(n),setTimeout((e=>URL.revokeObjectURL(i)),500)}_toggleDarkTheme(e){const t=this._dom.find(".lh-vars",this._document);void 0===e?t.classList.toggle("dark"):t.classList.toggle("dark",e)}_updateStickyHeaderOnScroll(){const e=this.topbarEl.getBoundingClientRect().bottom>=this.scoreScaleEl.getBoundingClientRect().top,t=Array.from(this._document.querySelectorAll(".lh-category")).filter((e=>e.getBoundingClientRect().top-window.innerHeight/2<0)),s=t.length>0?t.length-1:0,i=this.stickyHeaderEl.querySelectorAll(".lh-gauge__wrapper"),n=i[s],r=i[0].getBoundingClientRect().left,o=n.getBoundingClientRect().left-r;this.highlightEl.style.transform=`translate(${o}px)`,this.stickyHeaderEl.classList.toggle("lh-sticky-header--visible",e)}}class ge{constructor(e){this._dom=e,this._toggleEl,this._menuEl,this.onDocumentKeyDown=this.onDocumentKeyDown.bind(this),this.onToggleClick=this.onToggleClick.bind(this),this.onToggleKeydown=this.onToggleKeydown.bind(this),this.onMenuFocusOut=this.onMenuFocusOut.bind(this),this.onMenuKeydown=this.onMenuKeydown.bind(this),this._getNextMenuItem=this._getNextMenuItem.bind(this),this._getNextSelectableNode=this._getNextSelectableNode.bind(this),this._getPreviousMenuItem=this._getPreviousMenuItem.bind(this)}setup(e){this._toggleEl=this._dom.find(".lh-tools__button",this._dom.document()),this._toggleEl.addEventListener("click",this.onToggleClick),this._toggleEl.addEventListener("keydown",this.onToggleKeydown),this._menuEl=this._dom.find(".lh-tools__dropdown",this._dom.document()),this._menuEl.addEventListener("keydown",this.onMenuKeydown),this._menuEl.addEventListener("click",e)}close(){this._toggleEl.classList.remove("active"),this._toggleEl.setAttribute("aria-expanded","false"),this._menuEl.contains(this._dom.document().activeElement)&&this._toggleEl.focus(),this._menuEl.removeEventListener("focusout",this.onMenuFocusOut),this._dom.document().removeEventListener("keydown",this.onDocumentKeyDown)}open(e){this._toggleEl.classList.contains("active")?e.focus():this._menuEl.addEventListener("transitionend",(()=>{e.focus()}),{once:!0}),this._toggleEl.classList.add("active"),this._toggleEl.setAttribute("aria-expanded","true"),this._menuEl.addEventListener("focusout",this.onMenuFocusOut),this._dom.document().addEventListener("keydown",this.onDocumentKeyDown)}onToggleClick(e){e.preventDefault(),e.stopImmediatePropagation(),this._toggleEl.classList.contains("active")?this.close():this.open(this._getNextMenuItem())}onToggleKeydown(e){switch(e.code){case"ArrowUp":e.preventDefault(),this.open(this._getPreviousMenuItem());break;case"ArrowDown":case"Enter":case" ":e.preventDefault(),this.open(this._getNextMenuItem())}}onMenuKeydown(e){const t=e.target;switch(e.code){case"ArrowUp":e.preventDefault(),this._getPreviousMenuItem(t).focus();break;case"ArrowDown":e.preventDefault(),this._getNextMenuItem(t).focus();break;case"Home":e.preventDefault(),this._getNextMenuItem().focus();break;case"End":e.preventDefault(),this._getPreviousMenuItem().focus()}}onDocumentKeyDown(e){27===e.keyCode&&this.close()}onMenuFocusOut(e){const t=e.relatedTarget;this._menuEl.contains(t)||this.close()}_getNextSelectableNode(e,t){const s=e.filter((e=>e instanceof HTMLElement&&(!e.hasAttribute("disabled")&&"none"!==window.getComputedStyle(e).display)));let i=t?s.indexOf(t)+1:0;return i>=s.length&&(i=0),s[i]}_getNextMenuItem(e){const t=Array.from(this._menuEl.childNodes);return this._getNextSelectableNode(t,e)}_getPreviousMenuItem(e){const t=Array.from(this._menuEl.childNodes).reverse();return this._getNextSelectableNode(t,e)}}"undefined"!=typeof module&&module.exports?module.exports=pe:self.ReportUIFeatures=pe;class me{constructor(e,t){this.dom=e,this.detailsRenderer=t,this.templateContext=this.dom.document(),this.detailsRenderer.setTemplateContext(this.templateContext)}get _clumpTitles(){return{warning:V.i18n.strings.warningAuditsGroupTitle,manual:V.i18n.strings.manualAuditsGroupTitle,passed:V.i18n.strings.passedAuditsGroupTitle,notApplicable:V.i18n.strings.notApplicableAuditsGroupTitle}}renderAudit(e){const t=this.dom.cloneTemplate("#tmpl-lh-audit",this.templateContext);return this.populateAuditValues(e,t)}populateAuditValues(e,t){const s=V.i18n.strings,i=this.dom.find(".lh-audit",t);i.id=e.result.id;const n=e.result.scoreDisplayMode;e.result.displayValue&&(this.dom.find(".lh-audit__display-text",i).textContent=e.result.displayValue);const r=this.dom.find(".lh-audit__title",i);r.appendChild(this.dom.convertMarkdownCodeSnippets(e.result.title)),this.dom.find(".lh-audit__description",i).appendChild(this.dom.convertMarkdownLinkSnippets(e.result.description)),e.stackPacks&&e.stackPacks.forEach((e=>{const t=this.dom.createElement("div");t.classList.add("lh-audit__stackpack");const s=this.dom.createElement("img");s.classList.add("lh-audit__stackpack__img"),s.src=e.iconDataURL,s.alt=e.title,t.appendChild(s),t.appendChild(this.dom.convertMarkdownLinkSnippets(e.description)),this.dom.find(".lh-audit__stackpacks",i).appendChild(t)}));const o=this.dom.find("details",i);if(e.result.details){const t=this.detailsRenderer.render(e.result.details);t&&(t.classList.add("lh-details"),o.appendChild(t))}if(this.dom.find(".lh-chevron-container",i).appendChild(this._createChevron()),this._setRatingClass(i,e.result.score,n),"error"===e.result.scoreDisplayMode){i.classList.add("lh-audit--error");const t=this.dom.find(".lh-audit__display-text",i);t.textContent=s.errorLabel,t.classList.add("tooltip-boundary");this.dom.createChildOf(t,"div","tooltip tooltip--error").textContent=e.result.errorMessage||s.errorMissingAuditInfo}else if(e.result.explanation){this.dom.createChildOf(r,"div","lh-audit-explanation").textContent=e.result.explanation}const a=e.result.warnings;if(!a||0===a.length)return i;const l=this.dom.find("summary",o),d=this.dom.createChildOf(l,"div","lh-warnings");if(this.dom.createChildOf(d,"span").textContent=s.warningHeader,1===a.length)d.appendChild(this.dom.document().createTextNode(a.join("")));else{const e=this.dom.createChildOf(d,"ul");for(const t of a){this.dom.createChildOf(e,"li").textContent=t}}return i}_createChevron(){const e=this.dom.cloneTemplate("#tmpl-lh-chevron",this.templateContext);return this.dom.find(".lh-chevron",e)}_setRatingClass(e,t,s){const i=V.calculateRating(t,s);return e.classList.add("lh-audit--"+s.toLowerCase()),"informative"!==s&&e.classList.add("lh-audit--"+i),e}renderCategoryHeader(e,t){const s=this.dom.cloneTemplate("#tmpl-lh-category-header",this.templateContext),i=this.dom.find(".lh-score__gauge",s),n=this.renderScoreGauge(e,t);if(i.appendChild(n),e.description){const t=this.dom.convertMarkdownLinkSnippets(e.description);this.dom.find(".lh-category-header__description",s).appendChild(t)}return s.firstElementChild}renderAuditGroup(e){const t=this.dom.createElement("div","lh-audit-group"),s=this.dom.createElement("div","lh-audit-group__header");if(this.dom.createChildOf(s,"span","lh-audit-group__title").textContent=e.title,e.description){const t=this.dom.convertMarkdownLinkSnippets(e.description);t.classList.add("lh-audit-group__description"),s.appendChild(t)}return t.appendChild(s),t}_renderGroupedAudits(e,t){const s=new Map,i="NotAGroup";s.set(i,[]);for(const t of e){const e=t.group||i,n=s.get(e)||[];n.push(t),s.set(e,n)}const n=[];for(const[e,r]of s){if(e===i){for(const e of r)n.push(this.renderAudit(e));continue}const s=t[e],o=this.renderAuditGroup(s);for(const e of r)o.appendChild(this.renderAudit(e));o.classList.add("lh-audit-group--"+e),n.push(o)}return n}renderUnexpandableClump(e,t){const s=this.dom.createElement("div");return this._renderGroupedAudits(e,t).forEach((e=>s.appendChild(e))),s}renderClump(e,{auditRefs:t,description:s}){const i=this.dom.cloneTemplate("#tmpl-lh-clump",this.templateContext),n=this.dom.find(".lh-clump",i);"warning"===e&&n.setAttribute("open","");this.dom.find(".lh-audit-group__summary",n).appendChild(this._createChevron()).title=V.i18n.strings.auditGroupExpandTooltip;const r=this.dom.find(".lh-audit-group__header",n),o=this._clumpTitles[e];if(this.dom.find(".lh-audit-group__title",r).textContent=o,s){const e=this.dom.convertMarkdownLinkSnippets(s);e.classList.add("lh-audit-group__description"),r.appendChild(e)}this.dom.find(".lh-audit-group__itemcount",n).textContent=`(${t.length})`;const a=t.map(this.renderAudit.bind(this));return n.append(...a),n.classList.add("lh-clump--"+e.toLowerCase()),n}setTemplateContext(e){this.templateContext=e,this.detailsRenderer.setTemplateContext(e)}renderScoreGauge(e,t){const s=this.dom.cloneTemplate("#tmpl-lh-gauge",this.templateContext),i=this.dom.find(".lh-gauge__wrapper",s);i.href="#"+e.id,V.isPluginCategory(e.id)&&i.classList.add("lh-gauge__wrapper--plugin");const n=Number(e.score),r=this.dom.find(".lh-gauge",s).querySelector(".lh-gauge-arc");r&&this._setGaugeArc(r,n);const o=Math.round(100*n),a=this.dom.find(".lh-gauge__percentage",s);return a.textContent=o.toString(),null===e.score&&(a.textContent="?",a.title=V.i18n.strings.errorLabel),0===e.auditRefs.length||this.hasApplicableAudits(e)?i.classList.add("lh-gauge__wrapper--"+V.calculateRating(e.score)):(i.classList.add("lh-gauge__wrapper--not-applicable"),a.textContent="-",a.title=V.i18n.strings.notApplicableAuditsGroupTitle),this.dom.find(".lh-gauge__label",s).textContent=e.title,s}hasApplicableAudits(e){return e.auditRefs.some((e=>"notApplicable"!==e.result.scoreDisplayMode))}_setGaugeArc(e,t){const s=2*Math.PI*Number(e.getAttribute("r")),i=Number(e.getAttribute("stroke-width")),n=.25*i/s;e.style.transform=`rotate(${360*n-90}deg)`;let r=t*s-i/2;0===t&&(e.style.opacity="0"),1===t&&(r=s),e.style.strokeDasharray=`${Math.max(r,0)} ${s}`}_auditHasWarning(e){return Boolean(e.result.warnings&&e.result.warnings.length)}_getClumpIdForAuditRef(e){const t=e.result.scoreDisplayMode;return"manual"===t||"notApplicable"===t?t:V.showAsPassed(e.result)?this._auditHasWarning(e)?"warning":"passed":"failed"}render(e,t={}){const s=this.dom.createElement("div","lh-category");this.createPermalinkSpan(s,e.id),s.appendChild(this.renderCategoryHeader(e,t));const i=new Map;i.set("failed",[]),i.set("warning",[]),i.set("manual",[]),i.set("passed",[]),i.set("notApplicable",[]);for(const t of e.auditRefs){const e=this._getClumpIdForAuditRef(t),s=i.get(e);s.push(t),i.set(e,s)}for(const[n,r]of i){if(0===r.length)continue;if("failed"===n){const e=this.renderUnexpandableClump(r,t);e.classList.add("lh-clump--failed"),s.appendChild(e);continue}const i="manual"===n?e.manualDescription:void 0,o=this.renderClump(n,{auditRefs:r,description:i});s.appendChild(o)}return s}createPermalinkSpan(e,t){this.dom.createChildOf(e,"span","lh-permalink").id=t}}"undefined"!=typeof module&&module.exports?module.exports=me:self.CategoryRenderer=me;class _e extends me{_renderMetric(e){const t=this.dom.cloneTemplate("#tmpl-lh-metric",this.templateContext),s=this.dom.find(".lh-metric",t);s.id=e.result.id;const i=V.calculateRating(e.result.score,e.result.scoreDisplayMode);s.classList.add("lh-metric--"+i);this.dom.find(".lh-metric__title",t).textContent=e.result.title;const n=this.dom.find(".lh-metric__value",t);n.textContent=e.result.displayValue||"";const r=this.dom.find(".lh-metric__description",t);if(r.appendChild(this.dom.convertMarkdownLinkSnippets(e.result.description)),"error"===e.result.scoreDisplayMode){r.textContent="",n.textContent="Error!";this.dom.createChildOf(r,"span").textContent=e.result.errorMessage||"Report error: no metric information"}return s}_renderOpportunity(e,t){const s=this.dom.cloneTemplate("#tmpl-lh-opportunity",this.templateContext),i=this.populateAuditValues(e,s);if(i.id=e.result.id,!e.result.details||"error"===e.result.scoreDisplayMode)return i;const n=e.result.details;if("opportunity"!==n.type)return i;const r=this.dom.find(".lh-audit__display-text",i),o=n.overallSavingsMs/t*100+"%";if(this.dom.find(".lh-sparkline__bar",i).style.width=o,r.textContent=V.i18n.formatSeconds(n.overallSavingsMs,.01),e.result.displayValue){const t=e.result.displayValue;this.dom.find(".lh-load-opportunity__sparkline",i).title=t,r.title=t}return i}_getWastedMs(e){if(e.result.details&&"opportunity"===e.result.details.type){const t=e.result.details;if("number"!=typeof t.overallSavingsMs)throw new Error("non-opportunity details passed to _getWastedMs");return t.overallSavingsMs}return Number.MIN_VALUE}_getScoringCalculatorHref(e){const t=e.filter((e=>"metrics"===e.group)),s=e.find((e=>"first-cpu-idle"===e.id)),i=e.find((e=>"first-meaningful-paint"===e.id));s&&t.push(s),i&&t.push(i);const n={"cumulative-layout-shift":"CLS","first-contentful-paint":"FCP","first-cpu-idle":"FCI","first-meaningful-paint":"FMP",interactive:"TTI","largest-contentful-paint":"LCP","speed-index":"SI","total-blocking-time":"TBT"},r=[...t.map((e=>{let t;var s;return"number"==typeof e.result.numericValue?(t="cumulative-layout-shift"===e.id?(s=e.result.numericValue,Math.round(100*s)/100):Math.round(e.result.numericValue),t=t.toString()):t="null",[n[e.id]||e.id,t]}))];V.reportJson&&(r.push(["device",V.reportJson.configSettings.formFactor]),r.push(["version",V.reportJson.lighthouseVersion]));const o=new URLSearchParams(r),a=new URL("https://googlechrome.github.io/lighthouse/scorecalc/");return a.hash=o.toString(),a.href}render(e,t,s){const i=V.i18n.strings,n=this.dom.createElement("div","lh-category");if("PSI"===s){const s=this.dom.createElement("div","lh-score__gauge");s.appendChild(this.renderScoreGauge(e,t)),n.appendChild(s)}else this.createPermalinkSpan(n,e.id),n.appendChild(this.renderCategoryHeader(e,t));const r=this.renderAuditGroup(t.metrics),o=this.dom.cloneTemplate("#tmpl-lh-metrics-toggle",this.templateContext),a=this.dom.find(".lh-metrics-toggle",o);r.append(...a.childNodes);const l=e.auditRefs.filter((e=>"metrics"===e.group)),d=this.dom.createChildOf(r,"div","lh-metrics-container");l.forEach((e=>{d.appendChild(this._renderMetric(e))}));const h=this.dom.createChildOf(r,"div","lh-metrics__disclaimer"),c=this.dom.convertMarkdownLinkSnippets(i.varianceDisclaimer);h.appendChild(c);const u=this.dom.createChildOf(h,"a","lh-calclink");u.target="_blank",u.textContent=i.calculatorLink,u.href=this._getScoringCalculatorHref(e.auditRefs),r.classList.add("lh-audit-group--metrics"),n.appendChild(r);const p=this.dom.createChildOf(n,"div","lh-filmstrip-container"),g=e.auditRefs.find((e=>"screenshot-thumbnails"===e.id)),m=g&&g.result;if(m&&m.details){p.id=m.id;const e=this.detailsRenderer.render(m.details);e&&p.appendChild(e)}const _=[];if(["performance-budget","timing-budget"].forEach((t=>{const s=e.auditRefs.find((e=>e.id===t));if(s&&s.result.details){const e=this.detailsRenderer.render(s.result.details);e&&(e.id=t,e.classList.add("lh-audit"),_.push(e))}})),_.length>0){const e=this.renderAuditGroup(t.budgets);_.forEach((t=>e.appendChild(t))),e.classList.add("lh-audit-group--budgets"),n.appendChild(e)}const f=e.auditRefs.filter((e=>"load-opportunities"===e.group&&!V.showAsPassed(e.result))).sort(((e,t)=>this._getWastedMs(t)-this._getWastedMs(e)));if(f.length){const e=2e3,s=f.map((e=>this._getWastedMs(e))),r=Math.max(...s),o=Math.max(1e3*Math.ceil(r/1e3),e),a=this.renderAuditGroup(t["load-opportunities"]),l=this.dom.cloneTemplate("#tmpl-lh-opportunity-header",this.templateContext);this.dom.find(".lh-load-opportunity__col--one",l).textContent=i.opportunityResourceColumnLabel,this.dom.find(".lh-load-opportunity__col--two",l).textContent=i.opportunitySavingsColumnLabel;const d=this.dom.find(".lh-load-opportunity__header",l);a.appendChild(d),f.forEach((e=>a.appendChild(this._renderOpportunity(e,o)))),a.classList.add("lh-audit-group--load-opportunities"),n.appendChild(a)}const b=e.auditRefs.filter((e=>"diagnostics"===e.group&&!V.showAsPassed(e.result))).sort(((e,t)=>("informative"===e.result.scoreDisplayMode?100:Number(e.result.score))-("informative"===t.result.scoreDisplayMode?100:Number(t.result.score))));if(b.length){const e=this.renderAuditGroup(t.diagnostics);b.forEach((t=>e.appendChild(this.renderAudit(t)))),e.classList.add("lh-audit-group--diagnostics"),n.appendChild(e)}const y=e.auditRefs.filter((e=>("load-opportunities"===e.group||"diagnostics"===e.group)&&V.showAsPassed(e.result)));if(!y.length)return n;const v={auditRefs:y,groupDefinitions:t},w=this.renderClump("passed",v);return n.appendChild(w),n}}"undefined"!=typeof module&&module.exports?module.exports=_e:self.PerformanceCategoryRenderer=_e;class fe extends me{render(e,t={}){const s=this.dom.createElement("div","lh-category");this.createPermalinkSpan(s,e.id),s.appendChild(this.renderCategoryHeader(e,t));const i=e.auditRefs,n=i.filter((e=>"manual"!==e.result.scoreDisplayMode)),r=this._renderAudits(n,t);s.appendChild(r);const o=i.filter((e=>"manual"===e.result.scoreDisplayMode)),a=this.renderClump("manual",{auditRefs:o,description:e.manualDescription});return s.appendChild(a),s}renderScoreGauge(e,t){if(null===e.score)return super.renderScoreGauge(e,t);const s=this.dom.cloneTemplate("#tmpl-lh-gauge--pwa",this.templateContext),i=this.dom.find(".lh-gauge--pwa__wrapper",s);i.href="#"+e.id;const n=s.querySelector("svg");if(!n)throw new Error("no SVG element found in PWA score gauge template");fe._makeSvgReferencesUnique(n);const r=this._getGroupIds(e.auditRefs),o=this._getPassingGroupIds(e.auditRefs);if(o.size===r.size)i.classList.add("lh-badged--all");else for(const e of o)i.classList.add("lh-badged--"+e);return this.dom.find(".lh-gauge__label",s).textContent=e.title,i.title=this._getGaugeTooltip(e.auditRefs,t),s}_getGroupIds(e){const t=e.map((e=>e.group)).filter((e=>!!e));return new Set(t)}_getPassingGroupIds(e){const t=this._getGroupIds(e);for(const s of e)!V.showAsPassed(s.result)&&s.group&&t.delete(s.group);return t}_getGaugeTooltip(e,t){const s=this._getGroupIds(e),i=[];for(const n of s){const s=e.filter((e=>e.group===n)),r=s.length,o=s.filter((e=>V.showAsPassed(e.result))).length,a=t[n].title;i.push(`${a}: ${o}/${r}`)}return i.join(", ")}_renderAudits(e,t){const s=this.renderUnexpandableClump(e,t),i=this._getPassingGroupIds(e);for(const e of i){this.dom.find(".lh-audit-group--"+e,s).classList.add("lh-badged")}return s}static _makeSvgReferencesUnique(e){const t=e.querySelector("defs");if(!t)return;const s=V.getUniqueSuffix(),i=t.querySelectorAll("[id]");for(const t of i){const i=t.id,n=`${i}-${s}`;t.id=n;const r=e.querySelectorAll(`use[href="#${i}"]`);for(const e of r)e.setAttribute("href","#"+n);const o=e.querySelectorAll(`[fill="url(#${i})"]`);for(const e of o)e.setAttribute("fill",`url(#${n})`)}}}"undefined"!=typeof module&&module.exports?module.exports=fe:self.PwaCategoryRenderer=fe;class be{constructor(e){this._dom=e,this._templateContext=this._dom.document()}renderReport(e,t){this._dom.setLighthouseChannel(e.configSettings.channel||"unknown");const s=V.prepareReportResult(e);return t.textContent="",t.appendChild(this._renderReport(s)),t}setTemplateContext(e){this._templateContext=e}_renderReportTopbar(e){const t=this._dom.cloneTemplate("#tmpl-lh-topbar",this._templateContext),s=this._dom.find(".lh-topbar__url",t);return s.href=s.textContent=e.finalUrl,s.title=e.finalUrl,t}_renderReportHeader(){const e=this._dom.cloneTemplate("#tmpl-lh-heading",this._templateContext),t=this._dom.cloneTemplate("#tmpl-lh-scores-wrapper",this._templateContext),s=this._dom.find(".lh-scores-wrapper-placeholder",e);return s.parentNode.replaceChild(t,s),e}_renderReportFooter(e){const t=this._dom.cloneTemplate("#tmpl-lh-footer",this._templateContext),s=this._dom.find(".lh-env__items",t);s.id="runtime-settings",this._dom.find(".lh-env__title",t).textContent=V.i18n.strings.runtimeSettingsTitle;const i=V.getEnvironmentDisplayValues(e.configSettings||{}),n=[{name:V.i18n.strings.runtimeSettingsUrl,description:e.finalUrl},{name:V.i18n.strings.runtimeSettingsFetchTime,description:V.i18n.formatDateTime(e.fetchTime)},...i,{name:V.i18n.strings.runtimeSettingsChannel,description:e.configSettings.channel},{name:V.i18n.strings.runtimeSettingsUA,description:e.userAgent},{name:V.i18n.strings.runtimeSettingsUANetwork,description:e.environment&&e.environment.networkUserAgent},{name:V.i18n.strings.runtimeSettingsBenchmark,description:e.environment&&e.environment.benchmarkIndex.toFixed(0)}];e.environment.credits&&e.environment.credits["axe-core"]&&n.push({name:V.i18n.strings.runtimeSettingsAxeVersion,description:e.environment.credits["axe-core"]});for(const e of n){if(!e.description)continue;const t=this._dom.cloneTemplate("#tmpl-lh-env__items",s);this._dom.find(".lh-env__name",t).textContent=e.name,this._dom.find(".lh-env__description",t).textContent=e.description,s.appendChild(t)}return this._dom.find(".lh-footer__version_issue",t).textContent=V.i18n.strings.footerIssue,this._dom.find(".lh-footer__version",t).textContent=e.lighthouseVersion,t}_renderReportWarnings(e){if(!e.runWarnings||0===e.runWarnings.length)return this._dom.createElement("div");const t=this._dom.cloneTemplate("#tmpl-lh-warnings--toplevel",this._templateContext);this._dom.find(".lh-warnings__msg",t).textContent=V.i18n.strings.toplevelWarningsMessage;const s=this._dom.find("ul",t);for(const t of e.runWarnings){s.appendChild(this._dom.createElement("li")).appendChild(this._dom.convertMarkdownLinkSnippets(t))}return t}_renderScoreGauges(e,t,s){const i=[],n=[],r=[];for(const o of Object.values(e.categories)){const a=s[o.id]||t,l=a.renderScoreGauge(o,e.categoryGroups||{});V.isPluginCategory(o.id)?r.push(l):a.renderScoreGauge===t.renderScoreGauge?i.push(l):n.push(l)}return[...i,...n,...r]}_renderReport(e){const t=new ye(e.configSettings.locale,{...V.UIStrings,...e.i18n.rendererFormattedStrings});V.i18n=t,V.reportJson=e;const s=e.audits["full-page-screenshot"]&&e.audits["full-page-screenshot"].details&&"full-page-screenshot"===e.audits["full-page-screenshot"].details.type?e.audits["full-page-screenshot"].details:void 0,i=new z(this._dom,{fullPageScreenshot:s}),n=s&&de.createBackgroundImageStyle(this._dom,s.screenshot),r=new me(this._dom,i);r.setTemplateContext(this._templateContext);const o={performance:new _e(this._dom,i),pwa:new fe(this._dom,i)};Object.values(o).forEach((e=>{e.setTemplateContext(this._templateContext)}));const a=this._dom.createElement("div");a.appendChild(this._renderReportHeader());const l=this._dom.createElement("div","lh-container"),d=this._dom.createElement("div","lh-report");let h;d.appendChild(this._renderReportWarnings(e));if(1===Object.keys(e.categories).length?a.classList.add("lh-header--solo-category"):h=this._dom.createElement("div","lh-scores-header"),h){const t=this._dom.cloneTemplate("#tmpl-lh-scorescale",this._templateContext),s=this._dom.find(".lh-scores-container",a);h.append(...this._renderScoreGauges(e,r,o)),s.appendChild(h),s.appendChild(t);const i=this._dom.createElement("div","lh-sticky-header");i.append(...this._renderScoreGauges(e,r,o)),l.appendChild(i)}const c=d.appendChild(this._dom.createElement("div","lh-categories"));for(const t of Object.values(e.categories)){const s=o[t.id]||r;s.dom.createChildOf(c,"div","lh-category-wrapper").appendChild(s.render(t,e.categoryGroups))}const u=this._dom.createFragment(),p=this._renderReportTopbar(e);return u.appendChild(p),u.appendChild(l),l.appendChild(a),l.appendChild(d),n&&l.appendChild(n),d.appendChild(this._renderReportFooter(e)),u}}"undefined"!=typeof module&&module.exports?module.exports=be:self.ReportRenderer=be;class ye{constructor(e,t){"en-XA"===e&&(e="de"),this._numberDateLocale=e,this._numberFormatter=new Intl.NumberFormat(e),this._strings=t||{}}get strings(){return this._strings}formatNumber(e,t=.1){const s=Math.round(e/t)*t;return this._numberFormatter.format(s)}formatBytesToKiB(e,t=.1){return this._byteFormatterForGranularity(t).format(Math.round(e/1024/t)*t)+" KiB"}formatBytes(e,t=1){return this._byteFormatterForGranularity(t).format(Math.round(e/t)*t)+" bytes"}_byteFormatterForGranularity(e){let t=0;return e<1&&(t=-Math.floor(Math.log10(e))),new Intl.NumberFormat(this._numberDateLocale,{...this._numberFormatter.resolvedOptions(),maximumFractionDigits:t,minimumFractionDigits:t})}formatMilliseconds(e,t=10){const s=Math.round(e/t)*t;return 0===s?this._numberFormatter.format(0)+" ms":this._numberFormatter.format(s)+" ms"}formatSeconds(e,t=.1){const s=Math.round(e/1e3/t)*t;return this._numberFormatter.format(s)+" s"}formatDateTime(e){const t={month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"numeric",timeZoneName:"short"};let s;try{s=new Intl.DateTimeFormat(this._numberDateLocale,t)}catch(e){t.timeZone="UTC",s=new Intl.DateTimeFormat(this._numberDateLocale,t)}return s.format(new Date(e))}formatDuration(e){let t=e/1e3;if(0===Math.round(t))return"None";const s=[],i={d:86400,h:3600,m:60,s:1};return Object.keys(i).forEach((e=>{const n=i[e],r=Math.floor(t/n);r>0&&(t-=r*n,s.push(`${r} ${e}`))})),s.join(" ")}}"undefined"!=typeof module&&module.exports?module.exports=ye:self.I18n=ye,function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;((t="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).Lighthouse||(t.Lighthouse={})).ReportGenerator=e()}}((function(){return function e(t,s,i){function n(o,a){if(!s[o]){if(!t[o]){var l="function"==typeof require&&require;if(!a&&l)return l(o,!0);if(r)return r(o,!0);var d=new Error("Cannot find module '"+o+"'");throw d.code="MODULE_NOT_FOUND",d}var h=s[o]={exports:{}};t[o][0].call(h.exports,(function(e){return n(t[o][1][e]||e)}),h,h.exports,e,t,s,i)}return s[o].exports}for(var r="function"==typeof require&&require,o=0;o<i.length;o++)n(i[o]);return n}({"./html/html-report-assets.js":[function(e,t,s){const i=globalThis.EXPORTED_CACHED_RESOURCES_ONLY_FOR_LIGHTHOUSE;t.exports={get REPORT_CSS(){return i.get("third_party/lighthouse/report-assets/report.css")},get REPORT_JAVASCRIPT(){return i.get("third_party/lighthouse/report-assets/report.js")},get REPORT_TEMPLATE(){return i.get("third_party/lighthouse/report-assets/template.html")},get REPORT_TEMPLATES(){return i.get("third_party/lighthouse/report-assets/templates.html")}}},{}],1:[function(e,t,s){const i=e("./html/html-report-assets.js");class n{static replaceStrings(e,t){if(0===t.length)return e;const s=t[0],i=t.slice(1);return e.split(s.search).map((e=>n.replaceStrings(e,i))).join(s.replacement)}static generateReportHtml(e){const t=JSON.stringify(e).replace(/</g,"\\u003c").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029"),s=i.REPORT_JAVASCRIPT.replace(/<\//g,"\\u003c/");return n.replaceStrings(i.REPORT_TEMPLATE,[{search:"%%LIGHTHOUSE_JSON%%",replacement:t},{search:"%%LIGHTHOUSE_JAVASCRIPT%%",replacement:s},{search:"/*%%LIGHTHOUSE_CSS%%*/",replacement:i.REPORT_CSS},{search:"%%LIGHTHOUSE_TEMPLATES%%",replacement:i.REPORT_TEMPLATES}])}static generateReportCSV(e){const t=e=>`"${e.replace(/"/g,'""')}"`,s=e=>e.map((e=>e.toString())).map(t),i=Object.keys(e.categories).map((t=>{const i=[],n=e.categories[t],r=null===n.score?-1:n.score;return i.push(s([e.requestedUrl,e.finalUrl,n.title,t+"-score",`Overall ${n.title} Category Score`,"numeric",r])),i.concat(n.auditRefs.map((t=>{const i=e.audits[t.id],r=null===i.score?-1:i.score;return s([e.requestedUrl,e.finalUrl,n.title,i.id,i.title,i.scoreDisplayMode,r])})))}));return[["requestedUrl","finalUrl","category","name","title","type","score"]].concat(...i).map((e=>e.join(","))).join("\r\n")}static generateReport(e,t){const s=Array.isArray(t);"string"==typeof t&&(t=[t]);const i=t.map((t=>{if("html"===t)return n.generateReportHtml(e);if("csv"===t)return n.generateReportCSV(e);if("json"===t)return JSON.stringify(e,null,2);throw new Error("Invalid output mode: "+t)}));return s?i:i[0]}}t.exports=n},{"./html/html-report-assets.js":"./html/html-report-assets.js"}]},{},[1])(1)}));const ve={canOnlyAuditHttphttpsPagesAnd:"Can only audit HTTP/HTTPS pages and `Chrome` extensions. Navigate to a different page to start an audit.",thereMayBeStoredDataAffectingSingular:"There may be stored data affecting loading performance in this location: {PH1}. Audit this page in an incognito window to prevent those resources from affecting your scores.",thereMayBeStoredDataAffectingLoadingPlural:"There may be stored data affecting loading performance in these locations: {PH1}. Audit this page in an incognito window to prevent those resources from affecting your scores.",multipleTabsAreBeingControlledBy:"Multiple tabs are being controlled by the same `service worker`. Close your other tabs on the same origin to audit this page.",atLeastOneCategoryMustBeSelected:"At least one category must be selected.",localStorage:"Local Storage",indexeddb:"IndexedDB",webSql:"Web SQL",performance:"Performance",howLongDoesThisAppTakeToShow:"How long does this app take to show content and become usable",progressiveWebApp:"Progressive Web App",doesThisPageMeetTheStandardOfA:"Does this page meet the standard of a Progressive Web App",bestPractices:"Best practices",doesThisPageFollowBestPractices:"Does this page follow best practices for modern web development",accessibility:"Accessibility",isThisPageUsableByPeopleWith:"Is this page usable by people with disabilities or impairments",seo:"SEO",isThisPageOptimizedForSearch:"Is this page optimized for search engine results ranking",publisherAds:"Publisher Ads",isThisPageOptimizedForAdSpeedAnd:"Is this page optimized for ad speed and quality",applyMobileEmulation:"Apply mobile emulation",applyMobileEmulationDuring:"Apply mobile emulation during auditing",mobile:"Mobile",desktop:"Desktop",simulatedThrottling:"Simulated throttling",simulateASlowerPageLoadBasedOn:"Simulate a slower page load, based on data from an initial unthrottled load. If disabled, the page is actually slowed with applied throttling.",clearStorage:"Clear storage",resetStorageLocalstorage:"Reset storage (localStorage, IndexedDB, etc) before auditing. (Good for performance & PWA testing)"},we=r.registerUIStrings("lighthouse/LighthouseController.js",ve),Se=r.getLocalizedString.bind(void 0,we);class Ce extends e.ObjectWrapper{constructor(e){super(),e.registerStatusCallback((e=>this.dispatchEventToListeners(Ee.AuditProgressChanged,{message:e})));for(const e of xe)e.setting.addChangeListener(this.recomputePageAuditability.bind(this));for(const e of Le)e.setting.addChangeListener(this.recomputePageAuditability.bind(this));o.TargetManager.instance().observeModels(a.ServiceWorkerManager,this),o.TargetManager.instance().addEventListener(o.Events.InspectedURLChanged,this.recomputePageAuditability,this)}modelAdded(e){this._manager||(this._manager=e,this._serviceWorkerListeners=[this._manager.addEventListener(a.Events.RegistrationUpdated,this.recomputePageAuditability,this),this._manager.addEventListener(a.Events.RegistrationDeleted,this.recomputePageAuditability,this)],this.recomputePageAuditability())}modelRemoved(e){this._manager===e&&(this._serviceWorkerListeners&&t.EventTarget.removeEventListeners(this._serviceWorkerListeners),this._manager=null,this.recomputePageAuditability())}_hasActiveServiceWorker(){if(!this._manager)return!1;const e=this._manager.target();if(!e)return!1;const t=s.ParsedURL.fromString(e.inspectedURL()),i=t&&t.securityOrigin();for(const e of this._manager.registrations().values())if(e.securityOrigin===i)for(const t of e.versions.values())if(t.controlledClients.length>1)return!0;return!1}_hasAtLeastOneCategory(){return xe.some((e=>e.setting.get()))}_unauditablePageMessage(){if(!this._manager)return null;const e=this._manager.target(),t=e&&e.inspectedURL();return t&&!/^(http|chrome-extension)/.test(t)?Se(ve.canOnlyAuditHttphttpsPagesAnd):null}async _hasImportantResourcesNotCleared(){const e=Le.find((e=>"lighthouse.clear_storage"===e.setting.name));if(e&&!e.setting.get())return"";if(!this._manager)return"";const t=this._manager.target(),s=(await t.storageAgent().invoke_getUsageAndQuota({origin:t.inspectedURL()})).usageBreakdown.filter((e=>e.usage)).map((e=>Te.get(e.storageType))).filter(Boolean);return 1===s.length?Se(ve.thereMayBeStoredDataAffectingSingular,{PH1:s[0]}):s.length>1?Se(ve.thereMayBeStoredDataAffectingLoadingPlural,{PH1:s.join(", ")}):""}async _evaluateInspectedURL(){if(!this._manager)return"";const e=this._manager.target(),t=e.model(l.RuntimeModel),s=t&&t.defaultExecutionContext();let i=e.inspectedURL();if(!s)return i;try{const e=await s.evaluate({expression:"window.location.href",objectGroup:"lighthouse",includeCommandLineAPI:!1,silent:!1,returnByValue:!0,generatePreview:!1,allowUnsafeEvalBlockedByCSP:void 0,disableBreaks:void 0,replMode:void 0,throwOnSideEffect:void 0,timeout:void 0},!1,!1);"exceptionDetails"in e&&e.exceptionDetails||!("object"in e)||!e.object||(i=e.object.value,e.object.release())}catch(e){console.error(e)}return i}getFlags(){const e={internalDisableDeviceScreenEmulation:!0};for(const t of Le)t.setFlags(e,t.setting.get());return e}getCategoryIDs(){const e=[];for(const t of xe)t.setting.get()&&e.push(t.configID);return e}async getInspectedURL(e){return(e&&e.force||!this._inspectedURL)&&(this._inspectedURL=await this._evaluateInspectedURL()),this._inspectedURL}recomputePageAuditability(){const e=this._hasActiveServiceWorker(),t=this._hasAtLeastOneCategory(),s=this._unauditablePageMessage();let i="";e?i=Se(ve.multipleTabsAreBeingControlledBy):t?s&&(i=s):i=Se(ve.atLeastOneCategoryMustBeSelected),this.dispatchEventToListeners(Ee.PageAuditabilityChanged,{helpText:i}),this._hasImportantResourcesNotCleared().then((e=>{this.dispatchEventToListeners(Ee.PageWarningsChanged,{warning:e})}))}}const Te=new Map([[Protocol.Storage.StorageType.Local_storage,Se(ve.localStorage)],[Protocol.Storage.StorageType.Indexeddb,Se(ve.indexeddb)],[Protocol.Storage.StorageType.Websql,Se(ve.webSql)]]),xe=[{setting:i.Settings.instance().createSetting("lighthouse.cat_perf",!0),configID:"performance",title:Se(ve.performance),description:Se(ve.howLongDoesThisAppTakeToShow),plugin:!1},{setting:i.Settings.instance().createSetting("lighthouse.cat_pwa",!0),configID:"pwa",title:Se(ve.progressiveWebApp),description:Se(ve.doesThisPageMeetTheStandardOfA),plugin:!1},{setting:i.Settings.instance().createSetting("lighthouse.cat_best_practices",!0),configID:"best-practices",title:Se(ve.bestPractices),description:Se(ve.doesThisPageFollowBestPractices),plugin:!1},{setting:i.Settings.instance().createSetting("lighthouse.cat_a11y",!0),configID:"accessibility",title:Se(ve.accessibility),description:Se(ve.isThisPageUsableByPeopleWith),plugin:!1},{setting:i.Settings.instance().createSetting("lighthouse.cat_seo",!0),configID:"seo",title:Se(ve.seo),description:Se(ve.isThisPageOptimizedForSearch),plugin:!1},{setting:i.Settings.instance().createSetting("lighthouse.cat_pubads",!1),plugin:!0,configID:"lighthouse-plugin-publisher-ads",title:Se(ve.publisherAds),description:Se(ve.isThisPageOptimizedForAdSpeedAnd)}],Le=[{setting:i.Settings.instance().createSetting("lighthouse.device_type","mobile"),title:Se(ve.applyMobileEmulation),description:Se(ve.applyMobileEmulationDuring),setFlags:(e,t)=>{e.emulatedFormFactor=t},options:[{label:Se(ve.mobile),value:"mobile"},{label:Se(ve.desktop),value:"desktop"}],learnMore:void 0},{setting:i.Settings.instance().createSetting("lighthouse.throttling",!0),title:Se(ve.simulatedThrottling),learnMore:"https://github.com/GoogleChrome/lighthouse/blob/master/docs/throttling.md#devtools-lighthouse-panel-throttling",description:Se(ve.simulateASlowerPageLoadBasedOn),setFlags:(e,t)=>{e.throttlingMethod=t?"simulate":"devtools"},options:void 0},{setting:i.Settings.instance().createSetting("lighthouse.clear_storage",!0),title:Se(ve.clearStorage),description:Se(ve.resetStorageLocalstorage),setFlags:(e,t)=>{e.disableStorageReset=!t},options:void 0,learnMore:void 0}],Ee={PageAuditabilityChanged:Symbol("PageAuditabilityChanged"),PageWarningsChanged:Symbol("PageWarningsChanged"),AuditProgressChanged:Symbol("AuditProgressChanged"),RequestLighthouseStart:Symbol("RequestLighthouseStart"),RequestLighthouseCancel:Symbol("RequestLighthouseCancel")};var Ae=Object.freeze({__proto__:null,UIStrings:ve,LighthouseController:Ce,Presets:xe,RuntimeSettings:Le,Events:Ee,Preset:undefined,RuntimeSetting:undefined});class ke extends e.ObjectWrapper{constructor(){super(),this._rawConnection=null,this._backend=null,this._backendPromise=null,this._status=null}async attach(){await o.TargetManager.instance().suspendAllTargets();const e=o.TargetManager.instance().mainTarget();if(!e)throw new Error("Unable to find main target required for LightHouse");const t=e.model(d.ChildTargetManager);if(!t)throw new Error("Unable to find child target manager required for LightHouse");this._rawConnection=await t.createParallelConnection((e=>{"string"==typeof e&&(e=JSON.parse(e)),this._dispatchProtocolMessage(e)}))}getLocales(){return navigator.languages}startLighthouse(e,t,s){const i=this.getLocales();return this._send("start",{url:e,categoryIDs:t,flags:s,locales:i})}async detach(){await this._send("stop"),this._backend&&(await this._backend.dispose(),this._backend=null),this._backendPromise=null,this._rawConnection&&await this._rawConnection.disconnect(),await o.TargetManager.instance().resumeAllTargets()}registerStatusCallback(e){this._status=e}_dispatchProtocolMessage(e){const t=e;(t.sessionId||t.method&&t.method.startsWith("Target"))&&this._send("dispatchProtocolMessage",{message:JSON.stringify(e)})}_initWorker(){const e=I.createAppService("lighthouse_worker","LighthouseService").then((e=>{this._backend||(this._backend=e,e&&(e.on("statusUpdate",(e=>{this._status&&e&&"message"in e&&this._status(e.message)})),e.on("sendProtocolMessage",(e=>{e&&"message"in e&&this._sendProtocolMessage(e.message)}))))}));return this._backendPromise=e,e}_sendProtocolMessage(e){this._rawConnection&&this._rawConnection.sendRawMessage(e)}async _send(e,t){let s=this._backendPromise;if(s||(s=this._initWorker()),await s,!this._backend)throw new Error("Backend is missing to send LightHouse message to");return this._backend.send(e,t)}}var Pe=Object.freeze({__proto__:null,ProtocolService:ke});self.ReportRenderer;self.ReportUIFeatures;var Re=Object.freeze({__proto__:null,ReportRenderer:class{constructor(e){}renderReport(e,t){throw new Error("Not implemented yet!")}setTemplateContext(e){}},ReportUIFeatures:class{constructor(e){this.json,this._document}setTemplateContext(e){}initFeatures(e){}_resetUIState(){}setBeforePrint(e){}setAfterPrint(e){}},CategoryRenderer:class{constructor(e,t){}},DetailsRenderer:class{constructor(e){}renderNode(e){throw new Error("Not implemented yet!")}},LighthouseReportGenerator:class{generateReportHtml(e){return""}},AuditResultJSON:undefined,AuditJSON:undefined,CategoryJSON:undefined,GroupJSON:undefined,ReportJSON:undefined,DetailsJSON:undefined,RunnerResultArtifacts:undefined,RunnerResult:undefined,NodeDetailsJSON:undefined,SourceLocationDetailsJSON:undefined,OpportunitySummary:undefined});const Me={viewOriginalTrace:"View Original Trace",viewTrace:"View Trace",thePerformanceMetricsAboveAre:'The performance metrics above are simulated and won\'t match the timings found in this trace. Disable simulated throttling in "Lighthouse Settings" if you want the timings to match.'},Ie=r.registerUIStrings("lighthouse/LighthouseReportRenderer.js",Me),De=r.getLocalizedString.bind(void 0,Ie);class Oe extends self.ReportRenderer{constructor(e){super(e)}static addViewTraceButton(e,t){if(!t||!t.traces||!t.traces.defaultPass)return;const s="simulate"===t.settings.throttlingMethod,i=e.querySelector(".lh-audit-group");if(!i)return;const n=i.querySelector(".lh-metrics__disclaimer");if(!n)return;const r=t.traces.defaultPass,o=De(s?Me.viewOriginalTrace:Me.viewTrace),a=y.createTextButton(o,(async function(){_.actionTaken(f.Action.LighthouseViewTrace),await w.InspectorView.instance().showPanel("timeline"),N.TimelinePanel.instance().loadFromEvents(r.traceEvents)}),"view-trace");s&&v.Tooltip.install(a,De(Me.thePerformanceMetricsAboveAre)),i.insertBefore(a,n.nextSibling)}static async linkifyNodeDetails(e){const t=o.TargetManager.instance().mainTarget();if(!t)return;const s=t.model(h.DOMModel);if(s)for(const t of e.getElementsByClassName("lh-node")){const e=t,i=e.dataset;if(!i.path)continue;const r=await s.pushNodeByPathToFrontend(i.path);if(!r)continue;const o=s.nodeForId(r);if(!o)continue;const a=await n.Linkifier.linkify(o,{tooltip:i.snippet,preventKeyboardFocus:void 0});v.Tooltip.install(e,"");const l=e.querySelector(".lh-element-screenshot");e.textContent="",l&&e.append(l),e.appendChild(a)}}static async linkifySourceLocationDetails(e){for(const t of e.getElementsByClassName("lh-source-location")){const e=t,s=e.dataset;if(!s.sourceUrl||!s.sourceLine||!s.sourceColumn)continue;const i=s.sourceUrl,n=Number(s.sourceLine),r=Number(s.sourceColumn),o=await D.Linkifier.linkifyURL(i,{lineNumber:n,columnNumber:r,maxLength:40,bypassURLTrimming:void 0,className:void 0,preventClick:void 0,tabStop:void 0,text:void 0});v.Tooltip.install(e,""),e.textContent="",e.appendChild(o)}}static handleDarkMode(e){"dark"===U.instance().themeName()&&e.classList.add("dark")}}class Ue extends self.ReportUIFeatures{constructor(e){super(e),this._beforePrint=null,this._afterPrint=null}setBeforePrint(e){this._beforePrint=e}setAfterPrint(e){this._afterPrint=e}getReportHtml(){return this.resetUIState(),Lighthouse.ReportGenerator.generateReportHtml(this.json)}async _saveFile(e){const t=`${new s.ParsedURL(this.json.finalUrl).domain().replace(/[^a-z0-9.-]+/gi,"_")}-${O.toISO8601Compact(new Date(this.json.fetchTime))}${e.type.match("json")?".json":".html"}`,i=await e.text();B.FileManager.instance().save(t,i,!0)}async _print(){const e=this.getDocument().querySelector(".lh-root").cloneNode(!0),t=window.open("","_blank","channelmode=1,status=1,resizable=1");if(!t)return;const s=t.document.createElement("style");s.textContent=b.cachedResources.get("third_party/lighthouse/report-assets/report.css")||"",t.document.head.appendChild(s),t.document.body.replaceWith(e),await Oe.linkifyNodeDetails(e),this._beforePrint&&this._beforePrint(),t.focus(),t.print(),t.close(),this._afterPrint&&this._afterPrint()}getDocument(){return this._document}resetUIState(){this._resetUIState()}}var Ne=Object.freeze({__proto__:null,UIStrings:Me,LighthouseReportRenderer:Oe,LighthouseReportUIFeatures:Ue});const Be={reports:"Reports",newReport:"(new report)"},Fe=r.registerUIStrings("lighthouse/LighthouseReportSelector.js",Be),He=r.getLocalizedString.bind(void 0,Fe);class $e{constructor(e){this._renderNewLighthouseView=e,this._newLighthouseItem=document.createElement("option"),this._comboBox=new S.ToolbarComboBox(this._handleChange.bind(this),He(Be.reports),"lighthouse-report"),this._comboBox.setMaxWidth(180),this._comboBox.setMinWidth(140),this._itemByOptionElement=new Map,this._setEmptyState()}_setEmptyState(){this._comboBox.selectElement().removeChildren(),this._comboBox.setEnabled(!1),this._newLighthouseItem=document.createElement("option"),this._newLighthouseItem.label=He(Be.newReport),this._comboBox.selectElement().appendChild(this._newLighthouseItem),this._comboBox.select(this._newLighthouseItem)}_handleChange(e){const t=this._selectedItem();t?t.select():this._renderNewLighthouseView()}_selectedItem(){const e=this._comboBox.selectedOption();return this._itemByOptionElement.get(e)}hasCurrentSelection(){return Boolean(this._selectedItem())}hasItems(){return this._itemByOptionElement.size>0}comboBox(){return this._comboBox}prepend(e){const t=e.optionElement(),s=this._comboBox.selectElement();this._itemByOptionElement.set(t,e),s.insertBefore(t,s.firstElementChild),this._comboBox.setEnabled(!0),this._comboBox.select(t),e.select()}clearAll(){for(const e of this._comboBox.options())e!==this._newLighthouseItem&&(this._itemByOptionElement.get(e).delete(),this._itemByOptionElement.delete(e));this._setEmptyState()}selectNewReport(){this._comboBox.select(this._newLighthouseItem)}}class je{constructor(e,t,i){this._lighthouseResult=e,this._renderReport=t,this._showLandingCallback=i;const n=new s.ParsedURL(e.finalUrl),r=e.fetchTime;this._element=document.createElement("option"),this._element.label=`${new Date(r).toLocaleTimeString()} - ${n.domain()}`}select(){this._renderReport()}optionElement(){return this._element}delete(){this._element&&this._element.remove(),this._showLandingCallback()}}var Ge=Object.freeze({__proto__:null,UIStrings:Be,ReportSelector:$e,Item:je});class Ve{constructor(e,t,s){this._setting=t,this._options=e,this.element=document.createElement("div"),C.setDescription(this.element,s),C.markAsRadioGroup(this.element),this._radioElements=[];for(const e of this._options){const i=T.Fragment.build`
        <label $="label" class="lighthouse-radio">
          <input $="input" type="radio" value=${e.value} name=${t.name}>
          <span $="span" class="lighthouse-radio-text">${e.label}</span>
        </label>
      `;this.element.appendChild(i.element()),s&&(v.Tooltip.install(i.$("input"),s),v.Tooltip.install(i.$("span"),s));const n=i.$("input");n.addEventListener("change",this._valueChanged.bind(this)),this._radioElements.push(n)}this._ignoreChangeEvents=!1,this._selectedIndex=-1,t.addChangeListener(this._settingChanged,this),this._settingChanged()}_updateUI(){this._ignoreChangeEvents=!0,this._radioElements[this._selectedIndex].checked=!0,this._ignoreChangeEvents=!1}_settingChanged(){const e=this._setting.get();this._selectedIndex=this._options.findIndex((t=>t.value===e)),this._updateUI()}_valueChanged(e){if(this._ignoreChangeEvents)return;const t=this._radioElements.find((e=>e.checked));t&&this._setting.set(t.value)}}var We=Object.freeze({__proto__:null,RadioSetting:Ve});const qe={learnMore:"Learn more",device:"Device",categories:"Categories",communityPluginsBeta:"Community Plugins (beta)",generateReport:"Generate report",identifyAndFixCommonProblemsThat:"Identify and fix common problems that affect your site's performance, accessibility, and user experience."},ze=r.registerUIStrings("lighthouse/LighthouseStartView.js",qe),Je=r.getLocalizedString.bind(void 0,ze);class Ke extends x.Widget{constructor(e){super(),this.registerRequiredCSS("lighthouse/lighthouseStartView.css",{enableLegacyPatching:!1}),this._controller=e,this._settingsToolbar=new S.Toolbar(""),this._render()}settingsToolbar(){return this._settingsToolbar}_populateRuntimeSettingAsRadio(e,t,s){const i=Le.find((t=>t.setting.name===e));if(!i||!i.options)throw new Error(e+" is not a setting with options");const n=new Ve(i.options,i.setting,i.description);s.appendChild(n.element),C.setAccessibleName(n.element,t)}_populateRuntimeSettingAsToolbarCheckbox(e,t){const s=Le.find((t=>t.setting.name===e));if(!s||!s.title)throw new Error(e+" is not a setting with a title");s.setting.setTitle(s.title);const i=new S.ToolbarSettingCheckbox(s.setting,s.description);if(t.appendToolbarItem(i),s.learnMore){const e=L.XLink.create(s.learnMore,Je(qe.learnMore),"lighthouse-learn-more");e.style.padding="5px",i.element.appendChild(e)}}_populateFormControls(e){const t=e.$("device-type-form-elements");this._populateRuntimeSettingAsRadio("lighthouse.device_type",Je(qe.device),t);const s=e.$("categories-form-elements"),i=e.$("plugins-form-elements");for(const e of xe){const t=e.plugin?i:s;e.setting.setTitle(e.title);const n=new S.ToolbarSettingCheckbox(e.setting,e.description);t.createChild("div","vbox lighthouse-launcher-row").appendChild(n.element)}C.markAsGroup(s),C.setAccessibleName(s,Je(qe.categories)),C.markAsGroup(i),C.setAccessibleName(i,Je(qe.communityPluginsBeta))}_render(){this._populateRuntimeSettingAsToolbarCheckbox("lighthouse.clear_storage",this._settingsToolbar),this._populateRuntimeSettingAsToolbarCheckbox("lighthouse.throttling",this._settingsToolbar),this._startButton=y.createTextButton(Je(qe.generateReport),(()=>this._controller.dispatchEventToListeners(Ee.RequestLighthouseStart,this._startButton.matches(":focus-visible"))),"",!0),this.setDefaultFocusedElement(this._startButton);const e=Je(qe.identifyAndFixCommonProblemsThat),t=T.Fragment.build`
      <div class="vbox lighthouse-start-view">
        <header>
          <div class="lighthouse-logo"></div>
          <div class="lighthouse-start-button-container hbox">
            ${this._startButton}
            </div>
          <div $="help-text" class="lighthouse-help-text hidden"></div>
          <div class="lighthouse-start-view-text">
            <span>${e}</span>
            ${L.XLink.create("https://developers.google.com/web/tools/lighthouse/",Je(qe.learnMore))}
          </div>
          <div $="warning-text" class="lighthouse-warning-text hidden"></div>
        </header>
        <form>
          <div class="lighthouse-form-categories">
            <div class="lighthouse-form-section">
              <div class="lighthouse-form-section-label">
                ${Je(qe.categories)}
              </div>
              <div class="lighthouse-form-elements" $="categories-form-elements"></div>
            </div>
            <div class="lighthouse-form-section">
              <div class="lighthouse-form-section-label">
                <div class="lighthouse-icon-label">${Je(qe.communityPluginsBeta)}</div>
              </div>
              <div class="lighthouse-form-elements" $="plugins-form-elements"></div>
            </div>
          </div>
          <div class="lighthouse-form-section">
            <div class="lighthouse-form-section-label">
              ${Je(qe.device)}
            </div>
            <div class="lighthouse-form-elements" $="device-type-form-elements"></div>
          </div>
        </form>
      </div>
    `;this._helpText=t.$("help-text"),this._warningText=t.$("warning-text"),this._populateFormControls(t),this.contentElement.appendChild(t.element()),this.contentElement.style.overflow="auto"}onResize(){const e=this.contentElement.offsetWidth<560,t=this.contentElement.querySelector(".lighthouse-start-view");t&&(t.classList.toggle("hbox",!e),t.classList.toggle("vbox",e))}focusStartButton(){this._startButton.focus()}setStartButtonEnabled(e){this._helpText&&this._helpText.classList.toggle("hidden",e),this._startButton&&(this._startButton.disabled=!e)}setUnauditableExplanation(e){this._helpText&&(this._helpText.textContent=e)}setWarningText(e){this._warningText&&(this._warningText.textContent=e,this._warningText.classList.toggle("hidden",!e),this._shouldConfirm=Boolean(e))}}var Ye=Object.freeze({__proto__:null,UIStrings:qe,StartView:Ke});const Qe={cancel:"Cancel",loading:"Loading…",auditingS:"Auditing {PH1}",auditingYourWebPage:"Auditing your web page",cancelling:"Cancelling…",lighthouseIsWarmingUp:"`Lighthouse` is warming up…",lighthouseIsLoadingYourPage:"`Lighthouse` is loading your page",fastFactMessageWithPlaceholder:"💡 {PH1}",ahSorryWeRanIntoAnError:"Ah, sorry! We ran into an error.",tryToNavigateToTheUrlInAFresh:"Try to navigate to the URL in a fresh `Chrome` profile without any other tabs or extensions open and try again.",ifThisIssueIsReproduciblePlease:"If this issue is reproducible, please report it at the `Lighthouse` `GitHub` repo.",lighthouseIsLoadingThePage:"Lighthouse is loading the page.",lighthouseIsGatheringInformation:"`Lighthouse` is gathering information about the page to compute your score.",almostThereLighthouseIsNow:"Almost there! `Lighthouse` is now generating your report.",lighthouseIsLoadingYourPageWith:"`Lighthouse` is loading your page with throttling to measure performance on a mobile device on 3G.",lighthouseIsLoadingYourPageWithThrottling:"`Lighthouse` is loading your page with throttling to measure performance on a slow desktop on 3G.",lighthouseIsLoadingYourPageWithMobile:"`Lighthouse` is loading your page with mobile emulation.",mbTakesAMinimumOfSecondsTo:"1MB takes a minimum of 5 seconds to download on a typical 3G connection [Source: `WebPageTest` and `DevTools` 3G definition].",rebuildingPinterestPagesFor:"Rebuilding Pinterest pages for performance increased conversion rates by 15% [Source: `WPO Stats`]",byReducingTheResponseSizeOfJson:"By reducing the response size of JSON needed for displaying comments, Instagram saw increased impressions [Source: `WPO Stats`]",walmartSawAIncreaseInRevenueFor:"Walmart saw a 1% increase in revenue for every 100ms improvement in page load [Source: `WPO Stats`]",ifASiteTakesSecondToBecome:"If a site takes >1 second to become interactive, users lose attention, and their perception of completing the page task is broken [Source: `Google Developers Blog`]",OfGlobalMobileUsersInWereOnGOrG:"75% of global mobile users in 2016 were on 2G or 3G [Source: `GSMA Mobile`]",theAverageUserDeviceCostsLess:"The average user device costs less than 200 USD. [Source: `International Data Corporation`]",SecondsIsTheAverageTimeAMobile:"19 seconds is the average time a mobile web page takes to load on a 3G connection [Source: `Google DoubleClick blog`]",OfMobilePagesTakeNearlySeconds:"70% of mobile pages take nearly 7 seconds for the visual content above the fold to display on the screen. [Source: `Think with Google`]",asPageLoadTimeIncreasesFromOne:"As page load time increases from one second to seven seconds, the probability of a mobile site visitor bouncing increases 113%. [Source: `Think with Google`]",asTheNumberOfElementsOnAPage:"As the number of elements on a page increases from 400 to 6,000, the probability of conversion drops 95%. [Source: `Think with Google`]",lighthouseOnlySimulatesMobile:"`Lighthouse` only simulates mobile performance; to measure performance on a real device, try WebPageTest.org [Source: `Lighthouse` team]"},Ze=r.registerUIStrings("lighthouse/LighthouseStatusView.js",Qe),Xe=r.getLocalizedString.bind(void 0,Ze);class et{constructor(e){this._controller=e,this._statusView=null,this._statusHeader=null,this._progressWrapper=null,this._progressBar=null,this._statusText=null,this._cancelButton=null,this._inspectedURL="",this._textChangedAt=0,this._fastFactsQueued=ot.slice(),this._currentPhase=null,this._scheduledTextChangeTimeout=null,this._scheduledFastFactTimeout=null,this._dialog=new E.Dialog,this._dialog.setDimmed(!0),this._dialog.setCloseOnEscape(!1),this._dialog.setOutsideClickCallback((e=>e.consume(!0))),this._render()}_render(){const e=A.createShadowRootWithCoreStyles(this._dialog.contentElement,{cssFile:"lighthouse/lighthouseDialog.css",enableLegacyPatching:!1,delegatesFocus:void 0}).createChild("div","lighthouse-view vbox"),t=y.createTextButton(Xe(Qe.cancel),this._cancel.bind(this)),s=T.Fragment.build`
      <div class="lighthouse-view vbox">
        <h2 $="status-header">Auditing your web page…</h2>
        <div class="lighthouse-status vbox" $="status-view">
          <div class="lighthouse-progress-wrapper" $="progress-wrapper">
            <div class="lighthouse-progress-bar" $="progress-bar"></div>
          </div>
          <div class="lighthouse-status-text" $="status-text"></div>
        </div>
        ${t}
      </div>
    `;e.appendChild(s.element()),this._statusView=s.$("status-view"),this._statusHeader=s.$("status-header"),this._progressWrapper=s.$("progress-wrapper"),this._progressBar=s.$("progress-bar"),this._statusText=s.$("status-text"),C.markAsProgressBar(this._progressBar,0,nt.length-1),this._cancelButton=t,C.markAsStatus(this._statusText),this._dialog.setDefaultFocusedElement(t),this._dialog.setSizeBehavior(k.SizeBehavior.SetExactWidthMaxHeight),this._dialog.setMaxContentSize(new P.Size(500,400))}_reset(){this._resetProgressBarClasses(),clearTimeout(this._scheduledFastFactTimeout),this._textChangedAt=0,this._fastFactsQueued=ot.slice(),this._currentPhase=null,this._scheduledTextChangeTimeout=null,this._scheduledFastFactTimeout=null}show(e){this._reset(),this.updateStatus(Xe(Qe.loading));const t=s.ParsedURL.fromString(this._inspectedURL),i=t&&t.host,n=i?Xe(Qe.auditingS,{PH1:i}):Xe(Qe.auditingYourWebPage);this._renderStatusHeader(n),this._dialog.show(e)}_renderStatusHeader(e){this._statusHeader&&(this._statusHeader.textContent=e+"…")}hide(){this._dialog.isShowing()&&this._dialog.hide()}setInspectedURL(e=""){this._inspectedURL=e}updateStatus(e){if(!e||!this._statusText)return;if(e.startsWith("Cancel"))return this._commitTextChange(Xe(Qe.cancelling)),void clearTimeout(this._scheduledFastFactTimeout);const t=this._getPhaseForMessage(e),s=nt.indexOf(t),i=nt.indexOf(this._currentPhase);if(t||this._currentPhase){if(t&&(!this._currentPhase||i<s)){this._currentPhase=t;const e=this._getMessageForPhase(t);this._scheduleTextChange(e),this._scheduleFastFactCheck(),this._resetProgressBarClasses(),this._progressBar&&(this._progressBar.classList.add(t.progressBarClass),C.setProgressBarValue(this._progressBar,s,e))}}else this._commitTextChange(Xe(Qe.lighthouseIsWarmingUp)),clearTimeout(this._scheduledFastFactTimeout)}_cancel(){this._controller.dispatchEventToListeners(Ee.RequestLighthouseCancel)}_getMessageForPhase(e){if(e.message)return e.message;const t=Le.find((e=>"lighthouse.device_type"===e.setting.name)),s=Le.find((e=>"lighthouse.throttling"===e.setting.name)),i=t?t.setting.get():"",n=s?s.setting.get():"",r=rt.find((e=>e.deviceType===i&&e.throttling===n));return r?r.message:Xe(Qe.lighthouseIsLoadingYourPage)}_getPhaseForMessage(e){return nt.find((t=>e.startsWith(t.statusMessagePrefix)))||null}_resetProgressBarClasses(){this._progressBar&&(this._progressBar.className="lighthouse-progress-bar")}_scheduleFastFactCheck(){this._currentPhase&&!this._scheduledFastFactTimeout&&(this._scheduledFastFactTimeout=setTimeout((()=>{this._updateFastFactIfNecessary(),this._scheduledFastFactTimeout=null,this._scheduleFastFactCheck()}),100))}_updateFastFactIfNecessary(){if(performance.now()-this._textChangedAt<tt)return;if(!this._fastFactsQueued.length)return;const e=Math.floor(Math.random()*this._fastFactsQueued.length);this._scheduleTextChange(Xe(Qe.fastFactMessageWithPlaceholder,{PH1:this._fastFactsQueued[e]})),this._fastFactsQueued.splice(e,1)}_commitTextChange(e){this._statusText&&(this._textChangedAt=performance.now(),this._statusText.textContent=e)}_scheduleTextChange(e){this._scheduledTextChangeTimeout&&clearTimeout(this._scheduledTextChangeTimeout);const t=performance.now()-this._textChangedAt,s=st-t;this._scheduledTextChangeTimeout=setTimeout((()=>{this._commitTextChange(e)}),Math.max(s,0))}renderBugReport(e){if(console.error(e),this._scheduledFastFactTimeout&&window.clearTimeout(this._scheduledFastFactTimeout),this._scheduledTextChangeTimeout&&window.clearTimeout(this._scheduledTextChangeTimeout),this._resetProgressBarClasses(),this._progressBar&&this._progressBar.classList.add("errored"),this._statusText)if(this._commitTextChange(""),y.createTextChild(this._statusText.createChild("p"),Xe(Qe.ahSorryWeRanIntoAnError)),it.some((t=>t.test(e.message)))){const e=Xe(Qe.tryToNavigateToTheUrlInAFresh);y.createTextChild(this._statusText.createChild("p"),e)}else this._renderBugReportBody(e,this._inspectedURL)}renderText(e,t){this._renderStatusHeader(e),this._commitTextChange(t)}toggleCancelButton(e){this._cancelButton&&(this._cancelButton.style.visibility=e?"visible":"hidden")}_renderBugReportBody(e,t){const s=navigator.userAgent.match(/Chrome\/(\S+)/)||["","Unknown"],i=`\n${e.friendlyMessage||e.message}\n\`\`\`\nChannel: DevTools\nInitial URL: ${t}\nChrome Version: ${s[1]}\nStack Trace: ${e.stack}\n\`\`\`\n`;this._statusText&&(y.createTextChild(this._statusText.createChild("p"),Xe(Qe.ifThisIssueIsReproduciblePlease)),y.createTextChild(this._statusText.createChild("code","monospace"),i.trim()))}}const tt=6e3,st=3e3,it=[/PARSING_PROBLEM/,/DOCUMENT_REQUEST/,/READ_FAILED/,/TRACING_ALREADY_STARTED/,/^You must provide a url to the runner/,/^You probably have multiple tabs open/],nt=[{id:"loading",progressBarClass:"loading",message:Xe(Qe.lighthouseIsLoadingThePage),statusMessagePrefix:"Loading page"},{id:"gathering",progressBarClass:"gathering",message:Xe(Qe.lighthouseIsGatheringInformation),statusMessagePrefix:"Gathering"},{id:"auditing",progressBarClass:"auditing",message:Xe(Qe.almostThereLighthouseIsNow),statusMessagePrefix:"Auditing"}],rt=[{deviceType:"mobile",throttling:"on",message:Xe(Qe.lighthouseIsLoadingYourPageWith)},{deviceType:"desktop",throttling:"on",message:Xe(Qe.lighthouseIsLoadingYourPageWithThrottling)},{deviceType:"mobile",throttling:"off",message:Xe(Qe.lighthouseIsLoadingYourPageWithMobile)},{deviceType:"desktop",throttling:"off",message:Xe(Qe.lighthouseIsLoadingThePage)}],ot=[Xe(Qe.mbTakesAMinimumOfSecondsTo),Xe(Qe.rebuildingPinterestPagesFor),Xe(Qe.byReducingTheResponseSizeOfJson),Xe(Qe.walmartSawAIncreaseInRevenueFor),Xe(Qe.ifASiteTakesSecondToBecome),Xe(Qe.OfGlobalMobileUsersInWereOnGOrG),Xe(Qe.theAverageUserDeviceCostsLess),Xe(Qe.SecondsIsTheAverageTimeAMobile),Xe(Qe.OfMobilePagesTakeNearlySeconds),Xe(Qe.asPageLoadTimeIncreasesFromOne),Xe(Qe.asTheNumberOfElementsOnAPage),Xe(Qe.OfMobilePagesTakeNearlySeconds),Xe(Qe.lighthouseOnlySimulatesMobile)];var at=Object.freeze({__proto__:null,UIStrings:Qe,StatusView:et,fastFactRotationInterval:tt,minimumTextVisibilityDuration:st,StatusPhases:nt});const lt={dropLighthouseJsonHere:"Drop `Lighthouse` JSON here",performAnAudit:"Perform an audit…",clearAll:"Clear all",lighthouseSettings:"`Lighthouse` settings",printing:"Printing",thePrintPopupWindowIsOpenPlease:"The print popup window is open. Please close it to continue.",cancelling:"Cancelling"},dt=r.registerUIStrings("lighthouse/LighthousePanel.js",lt),ht=r.getLocalizedString.bind(void 0,dt);let ct;class ut extends R.Panel{constructor(){super("lighthouse"),this.registerRequiredCSS("third_party/lighthouse/report-assets/report.css",{enableLegacyPatching:!1}),this.registerRequiredCSS("lighthouse/lighthousePanel.css",{enableLegacyPatching:!1}),this._protocolService=new ke,this._controller=new Ce(this._protocolService),this._startView=new Ke(this._controller),this._statusView=new et(this._controller),this._warningText=null,this._unauditableExplanation=null,this._cachedRenderedReports=new Map,this._dropTarget=new M.DropTarget(this.contentElement,[M.Type.File],ht(lt.dropLighthouseJsonHere),this._handleDrop.bind(this)),this._controller.addEventListener(Ee.PageAuditabilityChanged,this._refreshStartAuditUI.bind(this)),this._controller.addEventListener(Ee.PageWarningsChanged,this._refreshWarningsUI.bind(this)),this._controller.addEventListener(Ee.AuditProgressChanged,this._refreshStatusUI.bind(this)),this._controller.addEventListener(Ee.RequestLighthouseStart,(e=>{this._startLighthouse(e)})),this._controller.addEventListener(Ee.RequestLighthouseCancel,(e=>{this._cancelLighthouse()})),this._renderToolbar(),this._auditResultsElement=this.contentElement.createChild("div","lighthouse-results-container"),this._renderStartView(),this._controller.recomputePageAuditability(),this._clearButton,this._newButton,this._reportSelector,this._settingsPane,this._rightToolbar,this._showSettingsPaneSetting}static instance(e={forceNew:null}){const{forceNew:t}=e;return ct&&!t||(ct=new ut),ct}static getEvents(){return Ee}_refreshWarningsUI(e){this._isLHAttached||(this._warningText=e.data.warning,this._startView.setWarningText(e.data.warning))}_refreshStartAuditUI(e){this._isLHAttached||(this._unauditableExplanation=e.data.helpText,this._startView.setUnauditableExplanation(e.data.helpText),this._startView.setStartButtonEnabled(!e.data.helpText))}_refreshStatusUI(e){this._statusView.updateStatus(e.data.message)}_refreshToolbarUI(){this._clearButton.setEnabled(this._reportSelector.hasItems())}_clearAll(){this._reportSelector.clearAll(),this._renderStartView(),this._refreshToolbarUI()}_renderToolbar(){const e=this.element.createChild("div","lighthouse-toolbar-container"),t=new S.Toolbar("",e);this._newButton=new S.ToolbarButton(ht(lt.performAnAudit),"largeicon-add"),t.appendToolbarItem(this._newButton),this._newButton.addEventListener(S.ToolbarButton.Events.Click,this._renderStartView.bind(this)),t.appendSeparator(),this._reportSelector=new $e((()=>this._renderStartView())),t.appendToolbarItem(this._reportSelector.comboBox()),this._clearButton=new S.ToolbarButton(ht(lt.clearAll),"largeicon-clear"),t.appendToolbarItem(this._clearButton),this._clearButton.addEventListener(S.ToolbarButton.Events.Click,this._clearAll.bind(this)),this._settingsPane=new x.HBox,this._settingsPane.show(this.contentElement),this._settingsPane.element.classList.add("lighthouse-settings-pane"),this._settingsPane.element.appendChild(this._startView.settingsToolbar().element),this._showSettingsPaneSetting=i.Settings.instance().createSetting("lighthouseShowSettingsToolbar",!1),this._rightToolbar=new S.Toolbar("",e),this._rightToolbar.appendSeparator(),this._rightToolbar.appendToolbarItem(new S.ToolbarSettingToggle(this._showSettingsPaneSetting,"largeicon-settings-gear",ht(lt.lighthouseSettings))),this._showSettingsPaneSetting.addChangeListener(this._updateSettingsPaneVisibility.bind(this)),this._updateSettingsPaneVisibility(),this._refreshToolbarUI()}_updateSettingsPaneVisibility(){this._settingsPane.element.classList.toggle("hidden",!this._showSettingsPaneSetting.get())}_toggleSettingsDisplay(e){this._rightToolbar.element.classList.toggle("hidden",!e),this._settingsPane.element.classList.toggle("hidden",!e),this._updateSettingsPaneVisibility()}_renderStartView(){this._auditResultsElement.removeChildren(),this._statusView.hide(),this._reportSelector.selectNewReport(),this.contentElement.classList.toggle("in-progress",!1),this._startView.show(this.contentElement),this._toggleSettingsDisplay(!0),this._startView.setUnauditableExplanation(this._unauditableExplanation),this._startView.setStartButtonEnabled(!this._unauditableExplanation),this._unauditableExplanation||this._startView.focusStartButton(),this._startView.setWarningText(this._warningText),this._newButton.setEnabled(!1),this._refreshToolbarUI(),this.setDefaultFocusedChild(this._startView)}_renderStatusView(e){this.contentElement.classList.toggle("in-progress",!0),this._statusView.setInspectedURL(e),this._statusView.show(this.contentElement)}_beforePrint(){this._statusView.show(this.contentElement),this._statusView.toggleCancelButton(!1),this._statusView.renderText(ht(lt.printing),ht(lt.thePrintPopupWindowIsOpenPlease))}_afterPrint(){this._statusView.hide(),this._statusView.toggleCancelButton(!0)}_renderReport(e,t){this._toggleSettingsDisplay(!1),this.contentElement.classList.toggle("in-progress",!1),this._startView.hideWidget(),this._statusView.hide(),this._auditResultsElement.removeChildren(),this._newButton.setEnabled(!0),this._refreshToolbarUI();const s=this._cachedRenderedReports.get(e);if(s)return void this._auditResultsElement.appendChild(s);const i=this._auditResultsElement.createChild("div","lh-vars lh-root lh-devtools"),n=new DOM(this._auditResultsElement.ownerDocument),r=new Oe(n),o=b.cachedResources.get("third_party/lighthouse/report-assets/templates.html");if(!o)return;const a=(new DOMParser).parseFromString(o,"text/html");if(!a)return;r.setTemplateContext(a);const l=r.renderReport(e,i);Oe.addViewTraceButton(l,t),this._waitForMainTargetLoad().then((()=>{Oe.linkifyNodeDetails(l),Oe.linkifySourceLocationDetails(l)})),Oe.handleDarkMode(l);const d=new Ue(n);d.setBeforePrint(this._beforePrint.bind(this)),d.setAfterPrint(this._afterPrint.bind(this)),d.setTemplateContext(a),d.initFeatures(e),this._cachedRenderedReports.set(e,i)}async _waitForMainTargetLoad(){const e=o.TargetManager.instance().mainTarget();if(!e)return;const t=e.model(c.ResourceTreeModel);return t?t.once(c.Events.Load):void 0}_buildReportUI(e,t){if(null===e)return;const s=new je(e,(()=>this._renderReport(e,t)),this._renderStartView.bind(this));this._reportSelector.prepend(s),this._refreshToolbarUI(),this._renderReport(e)}_handleDrop(e){const t=e.items;if(!t.length)return;if("file"===t[0].kind){const e=t[0].webkitGetAsEntry();if(!e.isFile)return;e.file((e=>{const t=new FileReader;t.onload=()=>this._loadedFromFile(t.result),t.readAsText(e)}))}}_loadedFromFile(e){const t=JSON.parse(e);t.lighthouseVersion&&this._buildReportUI(t)}async _startLighthouse(e){_.actionTaken(f.Action.LighthouseStarted);try{const e=await this._controller.getInspectedURL({force:!0}),t=this._controller.getCategoryIDs(),s=this._controller.getFlags();await this._setupEmulationAndProtocolConnection(),this._renderStatusView(e);const i=await this._protocolService.startLighthouse(e,t,s);if(i&&i.fatal){const e=new Error(i.message);throw e.stack=i.stack,e}if(!i)throw new Error("Auditing failed to produce a result");_.actionTaken(f.Action.LighthouseFinished),await this._resetEmulationAndProtocolConnection(),this._buildReportUI(i.lhr,i.artifacts),this._newButton.element.focus()}catch(e){await this._resetEmulationAndProtocolConnection(),e instanceof Error&&this._statusView.renderBugReport(e)}}async _cancelLighthouse(){this._statusView.updateStatus(ht(lt.cancelling)),await this._resetEmulationAndProtocolConnection(),this._renderStartView()}async _setupEmulationAndProtocolConnection(){const e=this._controller.getFlags(),t=p.DeviceModeModel.instance();if(this._stateBefore={emulation:{enabled:t.enabledSetting().get(),outlineEnabled:t.deviceOutlineSetting().get(),toolbarControlsEnabled:t.toolbarControlsEnabledSetting().get()},network:{conditions:u.MultitargetNetworkManager.instance().networkConditions()}},t.toolbarControlsEnabledSetting().set(!1),"emulatedFormFactor"in e&&"desktop"===e.emulatedFormFactor)t.enabledSetting().set(!1),t.emulate(p.Type.None,null,null);else if("mobile"===e.emulatedFormFactor){t.enabledSetting().set(!0),t.deviceOutlineSetting().set(!0);for(const e of g.EmulatedDevicesList.instance().standard())"Moto G4"===e.title&&t.emulate(p.Type.Device,e,e.modes[0],1)}await this._protocolService.attach(),this._isLHAttached=!0}async _resetEmulationAndProtocolConnection(){if(!this._isLHAttached)return;if(this._isLHAttached=!1,await this._protocolService.detach(),this._stateBefore){const e=p.DeviceModeModel.instance();e.enabledSetting().set(this._stateBefore.emulation.enabled),e.deviceOutlineSetting().set(this._stateBefore.emulation.outlineEnabled),e.toolbarControlsEnabledSetting().set(this._stateBefore.emulation.toolbarControlsEnabled),u.MultitargetNetworkManager.instance().setNetworkConditions(this._stateBefore.network.conditions),delete this._stateBefore}m.InspectedPagePlaceholder.instance().update(!0);const e=o.TargetManager.instance().mainTarget();if(!e)return;const t=e.model(c.ResourceTreeModel);if(!t)return;const s=await this._controller.getInspectedURL();await t.navigate(s)}}var pt=Object.freeze({__proto__:null,UIStrings:lt,LighthousePanel:ut});export{Ae as LighthouseController,pt as LighthousePanel,Pe as LighthouseProtocolService,Ne as LighthouseReportRenderer,Ge as LighthouseReportSelector,Re as LighthouseReporterTypes,Ye as LighthouseStartView,at as LighthouseStatusView,We as RadioSetting};
