require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({"../audits/accessibility/aria-allowed-attr":[function(require,module,exports){'use strict';const AxeAudit=require('./axe-audit');class ARIAAllowedAttr extends AxeAudit{static get meta(){return{category:'Accessibility',name:'aria-allowed-attr',description:'Element aria-* attributes are allowed for this role',requiredArtifacts:['Accessibility']};}}
module.exports=ARIAAllowedAttr;},{"./axe-audit":2}],"../audits/accessibility/aria-required-attr":[function(require,module,exports){'use strict';const AxeAudit=require('./axe-audit');class ARIARequiredAttr extends AxeAudit{static get meta(){return{category:'Accessibility',name:'aria-required-attr',description:'Elements with ARIA roles have the required aria-* attributes',requiredArtifacts:['Accessibility']};}}
module.exports=ARIARequiredAttr;},{"./axe-audit":2}],"../audits/accessibility/aria-valid-attr-value":[function(require,module,exports){'use strict';const AxeAudit=require('./axe-audit');class ARIAValidAttr extends AxeAudit{static get meta(){return{category:'Accessibility',name:'aria-valid-attr-value',description:'Element aria-* attributes have valid values',requiredArtifacts:['Accessibility']};}}
module.exports=ARIAValidAttr;},{"./axe-audit":2}],"../audits/accessibility/aria-valid-attr":[function(require,module,exports){'use strict';const AxeAudit=require('./axe-audit');class ARIAValidAttr extends AxeAudit{static get meta(){return{category:'Accessibility',name:'aria-valid-attr',description:'Element aria-* attributes are valid and not misspelled or non-existent.',requiredArtifacts:['Accessibility']};}}
module.exports=ARIAValidAttr;},{"./axe-audit":2}],"../audits/accessibility/color-contrast":[function(require,module,exports){'use strict';const AxeAudit=require('./axe-audit');class ColorContrast extends AxeAudit{static get meta(){return{category:'Accessibility',name:'color-contrast',description:'Background and foreground colors have a sufficient contrast ratio',requiredArtifacts:['Accessibility']};}}
module.exports=ColorContrast;},{"./axe-audit":2}],"../audits/accessibility/image-alt":[function(require,module,exports){'use strict';const AxeAudit=require('./axe-audit');class ImageAlt extends AxeAudit{static get meta(){return{category:'Accessibility',name:'image-alt',description:'Every image element has an alt attribute',requiredArtifacts:['Accessibility']};}}
module.exports=ImageAlt;},{"./axe-audit":2}],"../audits/accessibility/label":[function(require,module,exports){'use strict';const AxeAudit=require('./axe-audit');class Label extends AxeAudit{static get meta(){return{category:'Accessibility',name:'label',description:'Every form element has a label',requiredArtifacts:['Accessibility']};}}
module.exports=Label;},{"./axe-audit":2}],"../audits/accessibility/tabindex":[function(require,module,exports){'use strict';const AxeAudit=require('./axe-audit');class TabIndex extends AxeAudit{static get meta(){return{category:'Accessibility',name:'tabindex',description:'No element has a `tabindex` attribute greater than 0',requiredArtifacts:['Accessibility']};}}
module.exports=TabIndex;},{"./axe-audit":2}],"../audits/cache-start-url":[function(require,module,exports){'use strict';const Audit=require('./audit');class CacheStartUrl extends Audit{static get meta(){return{category:'Manifest',name:'cache-start-url',description:'Cache contains start_url from manifest (alpha)',requiredArtifacts:['CacheContents','Manifest','URL']};}
static audit(artifacts){let cacheHasStartUrl=false;const manifest=artifacts.Manifest.value;const cacheContents=artifacts.CacheContents;if(!(manifest&&manifest.start_url&&manifest.start_url.value)){return CacheStartUrl.generateAuditResult({rawValue:false,debugString:'start_url not present in Manifest'});}
if(!Array.isArray(cacheContents)){return CacheStartUrl.generateAuditResult({rawValue:false,debugString:cacheContents.debugString||'No cache detected'});}
const startURL=manifest.start_url.value;const altStartURL=startURL.replace(/\?utm_([^=]*)=([^&]|$)*/,'').replace(/\?$/,'');cacheHasStartUrl=cacheContents.find(req=>{return(startURL===req||altStartURL===req);});return CacheStartUrl.generateAuditResult({rawValue:(cacheHasStartUrl!==undefined)});}}
module.exports=CacheStartUrl;},{"./audit":3}],"../audits/content-width":[function(require,module,exports){'use strict';const Audit=require('./audit');class ContentWidth extends Audit{static get meta(){return{category:'Mobile Friendly',name:'content-width',description:'Content is sized correctly for the viewport',helpText:'If the width of your app\'s content doesn\'t match the width '+'of the viewport, your app might not be optimized for mobile screens. '+'[Learn more](https://developers.google.com/web/tools/lighthouse/audits/content-sized-correctly-for-viewport).',requiredArtifacts:['ContentWidth']};}
static audit(artifacts){const scrollWidth=artifacts.ContentWidth.scrollWidth;const viewportWidth=artifacts.ContentWidth.viewportWidth;const widthsMatch=scrollWidth===viewportWidth&&scrollWidth!==-1;return ContentWidth.generateAuditResult({rawValue:widthsMatch,debugString:this.createDebugString(widthsMatch,artifacts.ContentWidth)});}
static createDebugString(match,artifact){if(match){return'';}
return'The content scroll size is '+artifact.scrollWidth+'px, '+'whereas the viewport size is '+artifact.viewportWidth+'px.';}}
module.exports=ContentWidth;},{"./audit":3}],"../audits/critical-request-chains":[function(require,module,exports){'use strict';const Audit=require('./audit');const Formatter=require('../formatters/formatter');class CriticalRequestChains extends Audit{static get meta(){return{category:'Performance',name:'critical-request-chains',description:'Critical Request Chains',optimalValue:0,helpText:'The Critical Request Chains below show you what resources are '+'required for first render of this page. Improve page load by reducing '+'the length of chains, reducing the download size of resources, or '+'deferring the download of unnecessary resources. '+'[Learn more](https://developers.google.com/web/tools/lighthouse/audits/critical-request-chains).',requiredArtifacts:['networkRecords']};}
static audit(artifacts){const networkRecords=artifacts.networkRecords[Audit.DEFAULT_PASS];return artifacts.requestCriticalRequestChains(networkRecords).then(chains=>{let chainCount=0;function walk(node,depth){const children=Object.keys(node);if(children.length===0){chainCount++;}
children.forEach(id=>{const child=node[id];walk(child.children,depth+1);},'');}
const initialNavigationKey=Object.keys(chains)[0];const initialNavChildren=chains[initialNavigationKey].children;if(initialNavChildren&&Object.keys(initialNavChildren).length>0){walk(initialNavChildren,0);}
return CriticalRequestChains.generateAuditResult({rawValue:chainCount<=this.meta.optimalValue,displayValue:chainCount,optimalValue:this.meta.optimalValue,extendedInfo:{formatter:Formatter.SUPPORTED_FORMATS.CRITICAL_REQUEST_CHAINS,value:chains}});});}}
module.exports=CriticalRequestChains;},{"../formatters/formatter":8,"./audit":3}],"../audits/dobetterweb/appcache-manifest":[function(require,module,exports){'use strict';const Audit=require('../audit');class AppCacheManifestAttr extends Audit{static get meta(){return{category:'Offline',name:'appcache-manifest',description:'Site does not use Application Cache',helpText:'Application Cache has been [deprecated](https://html.spec.whatwg.org/multipage/browsers.html#offline) by [Service Workers](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers). Consider implementing an offline solution using the [Cache Storage API](https://developer.mozilla.org/en-US/docs/Web/API/Cache).',requiredArtifacts:['AppCacheManifest']};}
static audit(artifacts){if(artifacts.AppCacheManifest===-1){return AppCacheManifestAttr.generateAuditResult({rawValue:false,debugString:'Unable to determine if you\'re using AppCache.'});}
const usingAppcache=artifacts.AppCacheManifest!==null;const displayValue=usingAppcache?`<html manifest="${artifacts.AppCacheManifest}">`:'';return AppCacheManifestAttr.generateAuditResult({rawValue:!usingAppcache,displayValue:displayValue});}}
module.exports=AppCacheManifestAttr;},{"../audit":3}],"../audits/dobetterweb/external-anchors-use-rel-noopener":[function(require,module,exports){'use strict';const URL=require('../../lib/url-shim');const Audit=require('../audit');const Formatter=require('../../formatters/formatter');class ExternalAnchorsUseRelNoopenerAudit extends Audit{static get meta(){return{category:'Performance',name:'external-anchors-use-rel-noopener',description:'Site opens external anchors using rel="noopener"',helpText:'Open new tabs using `rel="noopener"` to improve performance and '+'prevent security vulnerabilities. '+'[Learn more](https://developers.google.com/web/tools/lighthouse/audits/noopener).',requiredArtifacts:['URL','AnchorsWithNoRelNoopener']};}
static audit(artifacts){if(artifacts.AnchorsWithNoRelNoopener===-1){return ExternalAnchorsUseRelNoopenerAudit.generateAuditResult({rawValue:-1,debugString:'Unknown error with the AnchorsWithNoRelNoopener gatherer.'});}
let debugString;const pageHost=new URL(artifacts.URL.finalUrl).host;const failingAnchors=artifacts.AnchorsWithNoRelNoopener.usages.filter(anchor=>{try{return anchor.href===''||new URL(anchor.href).host!==pageHost;}catch(err){debugString='Lighthouse was unable to determine the destination '+'of some anchor tags. If they are not used as hyperlinks, '+'consider removing the _blank target.';return true;}}).map(anchor=>{return{url:'<a'+
(anchor.href?` href="${anchor.href}"`:'')+
(anchor.target?` target="${anchor.target}"`:'')+
(anchor.rel?` rel="${anchor.rel}"`:'')+'>'};});return ExternalAnchorsUseRelNoopenerAudit.generateAuditResult({rawValue:failingAnchors.length===0,extendedInfo:{formatter:Formatter.SUPPORTED_FORMATS.URLLIST,value:failingAnchors},debugString});}}
module.exports=ExternalAnchorsUseRelNoopenerAudit;},{"../../formatters/formatter":8,"../../lib/url-shim":30,"../audit":3}],"../audits/dobetterweb/geolocation-on-start":[function(require,module,exports){'use strict';const Audit=require('../audit');const Formatter=require('../../formatters/formatter');class GeolocationOnStart extends Audit{static get meta(){return{category:'UX',name:'geolocation-on-start',description:'Page does not automatically request geolocation on page load',helpText:'Users are mistrustful of or confused by sites that request their '+'location without context. Consider tying the request to user gestures instead. '+'[Learn more](https://developers.google.com/web/tools/lighthouse/audits/geolocation-on-load).',requiredArtifacts:['GeolocationOnStart']};}
static audit(artifacts){if(artifacts.GeolocationOnStart.value===-1){let debugString='Unknown error with the GeolocationOnStart gatherer';if(artifacts.GeolocationOnStart.debugString){debugString=artifacts.GeolocationOnStart.debugString;}
return GeolocationOnStart.generateAuditResult({rawValue:-1,debugString});}
const results=artifacts.GeolocationOnStart.usage.map(err=>{return Object.assign({label:`line: ${err.line}, col: ${err.col}`},err);});return GeolocationOnStart.generateAuditResult({rawValue:results.length===0,extendedInfo:{formatter:Formatter.SUPPORTED_FORMATS.URLLIST,value:results}});}}
module.exports=GeolocationOnStart;},{"../../formatters/formatter":8,"../audit":3}],"../audits/dobetterweb/link-blocking-first-paint":[function(require,module,exports){'use strict';const Audit=require('../audit');const Formatter=require('../../formatters/formatter');class LinkBlockingFirstPaintAudit extends Audit{static get meta(){return{category:'Performance',name:'link-blocking-first-paint',description:'Site does not use <link> that delay first paint',helpText:'Link elements are blocking the first paint of your page. Consider '+'inlining critical links and deferring non-critical ones. '+'[Learn more](https://developers.google.com/web/tools/lighthouse/audits/blocking-resources).',requiredArtifacts:['TagsBlockingFirstPaint']};}
static computeAuditResultForTags(artifacts,tagFilter){const artifact=artifacts.TagsBlockingFirstPaint;if(artifact.value===-1){return{rawValue:-1,debugString:artifact.debugString};}
let totalSpendTime=0;const results=artifact.items.filter(item=>item.tag.tagName===tagFilter).map(item=>{totalSpendTime+=item.spendTime;return{url:item.tag.url,label:`delayed first paint by ${item.spendTime}ms`};});let displayValue='';if(results.length>1){displayValue=`${results.length} resources delayed first paint by ${totalSpendTime}ms`;}else if(results.length===1){displayValue=`${results.length} resource delayed first paint by ${totalSpendTime}ms`;}
return{displayValue,rawValue:results.length===0,extendedInfo:{formatter:Formatter.SUPPORTED_FORMATS.URLLIST,value:results}};}
static audit(artifacts){const result=LinkBlockingFirstPaintAudit.computeAuditResultForTags(artifacts,'LINK');return LinkBlockingFirstPaintAudit.generateAuditResult(result);}}
module.exports=LinkBlockingFirstPaintAudit;},{"../../formatters/formatter":8,"../audit":3}],"../audits/dobetterweb/no-console-time":[function(require,module,exports){'use strict';const URL=require('../../lib/url-shim');const Audit=require('../audit');const Formatter=require('../../formatters/formatter');class NoConsoleTimeAudit extends Audit{static get meta(){return{category:'JavaScript',name:'no-console-time',description:'Site does not use `console.time()` in its own scripts',helpText:'Consider using `performance.mark()` and `performance.measure()` '+'from the User Timing API instead. They provide high-precision timestamps, '+'independent of the system clock, and are integrated in the Chrome DevTools Timeline. '+'[Learn more](https://developers.google.com/web/tools/lighthouse/audits/console-time).',requiredArtifacts:['URL','ConsoleTimeUsage']};}
static audit(artifacts){if(artifacts.ConsoleTimeUsage.value===-1){let debugString='Unknown error with the ConsoleTimeUsage gatherer';if(artifacts.ConsoleTimeUsage.debugString){debugString=artifacts.ConsoleTimeUsage.debugString;}
return NoConsoleTimeAudit.generateAuditResult({rawValue:-1,debugString});}
let debugString;const results=artifacts.ConsoleTimeUsage.usage.filter(err=>{if(err.isEval){return!!err.url;}
if(URL.isValid(err.url)){return URL.hostsMatch(artifacts.URL.finalUrl,err.url);}
debugString=URL.INVALID_URL_DEBUG_STRING;return true;}).map(err=>{return Object.assign({label:`line: ${err.line}, col: ${err.col}`},err);});return NoConsoleTimeAudit.generateAuditResult({rawValue:results.length===0,extendedInfo:{formatter:Formatter.SUPPORTED_FORMATS.URLLIST,value:results},debugString});}}
module.exports=NoConsoleTimeAudit;},{"../../formatters/formatter":8,"../../lib/url-shim":30,"../audit":3}],"../audits/dobetterweb/no-datenow":[function(require,module,exports){'use strict';const URL=require('../../lib/url-shim');const Audit=require('../audit');const Formatter=require('../../formatters/formatter');class NoDateNowAudit extends Audit{static get meta(){return{category:'JavaScript',name:'no-datenow',description:'Site does not use `Date.now()` in its own scripts',helpText:'Consider using `performance.now()` from the User Timing API '+'instead. It provides high-precision timestamps, independent of the system '+'clock. [Learn more](https://developers.google.com/web/tools/lighthouse/audits/date-now).',requiredArtifacts:['URL','DateNowUse']};}
static audit(artifacts){if(artifacts.DateNowUse.value===-1){let debugString='Unknown error with the DateNowUse gatherer';if(artifacts.DateNowUse.debugString){debugString=artifacts.DateNowUse.debugString;}
return NoDateNowAudit.generateAuditResult({rawValue:-1,debugString});}
let debugString;const results=artifacts.DateNowUse.usage.filter(err=>{if(err.isEval){return!!err.url;}
if(URL.isValid(err.url)){return URL.hostsMatch(artifacts.URL.finalUrl,err.url);}
debugString=URL.INVALID_URL_DEBUG_STRING;return true;}).map(err=>{return Object.assign({label:`line: ${err.line}, col: ${err.col}`,url:err.url},err);});return NoDateNowAudit.generateAuditResult({rawValue:results.length===0,extendedInfo:{formatter:Formatter.SUPPORTED_FORMATS.URLLIST,value:results},debugString});}}
module.exports=NoDateNowAudit;},{"../../formatters/formatter":8,"../../lib/url-shim":30,"../audit":3}],"../audits/dobetterweb/no-document-write":[function(require,module,exports){'use strict';const Audit=require('../audit');const Formatter=require('../../formatters/formatter');class NoDocWriteAudit extends Audit{static get meta(){return{category:'Performance',name:'no-document-write',description:'Site does not use document.write()',helpText:'For users on slow connections, external scripts dynamically injected via '+'`document.write()` can delay page load by tens of seconds. '+'[Learn more](https://developers.google.com/web/tools/lighthouse/audits/document-write).',requiredArtifacts:['DocWriteUse']};}
static audit(artifacts){if(artifacts.DocWriteUse.value===-1){let debugString='Unknown error with the DocWriteUse gatherer';if(artifacts.DocWriteUse.debugString){debugString=artifacts.DocWriteUse.debugString;}
return NoDocWriteAudit.generateAuditResult({rawValue:-1,debugString});}
const results=artifacts.DocWriteUse.usage.map(err=>{return Object.assign({label:`line: ${err.line}, col: ${err.col}`},err);});return NoDocWriteAudit.generateAuditResult({rawValue:results.length===0,extendedInfo:{formatter:Formatter.SUPPORTED_FORMATS.URLLIST,value:results}});}}
module.exports=NoDocWriteAudit;},{"../../formatters/formatter":8,"../audit":3}],"../audits/dobetterweb/no-mutation-events":[function(require,module,exports){'use strict';const URL=require('../../lib/url-shim');const Audit=require('../audit');const EventHelpers=require('../../lib/event-helpers');const Formatter=require('../../formatters/formatter');class NoMutationEventsAudit extends Audit{static get MUTATION_EVENTS(){return['DOMAttrModified','DOMAttributeNameChanged','DOMCharacterDataModified','DOMElementNameChanged','DOMNodeInserted','DOMNodeInsertedIntoDocument','DOMNodeRemoved','DOMNodeRemovedFromDocument','DOMSubtreeModified'];}
static get meta(){return{category:'JavaScript',name:'no-mutation-events',description:'Site does not use Mutation Events in its own scripts',helpText:'Mutation Events are deprecated and harm performance. Consider using Mutation '+'Observers instead. [Learn more](https://developers.google.com/web/tools/lighthouse/audits/mutation-events).',requiredArtifacts:['URL','EventListeners']};}
static audit(artifacts){if(artifacts.EventListeners.rawValue===-1){return NoMutationEventsAudit.generateAuditResult(artifacts.EventListeners);}
let debugString;const listeners=artifacts.EventListeners;const results=listeners.filter(loc=>{const isMutationEvent=this.MUTATION_EVENTS.indexOf(loc.type)!==-1;let sameHost=URL.hostsMatch(artifacts.URL.finalUrl,loc.url);if(!URL.isValid(loc.url)){sameHost=true;debugString=URL.INVALID_URL_DEBUG_STRING;}
return sameHost&&isMutationEvent;}).map(EventHelpers.addFormattedCodeSnippet);const groupedResults=EventHelpers.groupCodeSnippetsByLocation(results);return NoMutationEventsAudit.generateAuditResult({rawValue:groupedResults.length===0,extendedInfo:{formatter:Formatter.SUPPORTED_FORMATS.URLLIST,value:groupedResults},debugString});}}
module.exports=NoMutationEventsAudit;},{"../../formatters/formatter":8,"../../lib/event-helpers":22,"../../lib/url-shim":30,"../audit":3}],"../audits/dobetterweb/no-old-flexbox":[function(require,module,exports){'use strict';const Audit=require('../audit');const StyleHelpers=require('../../lib/styles-helpers');const Formatter=require('../../formatters/formatter');class NoOldFlexboxAudit extends Audit{static get meta(){return{category:'CSS',name:'no-old-flexbox',description:'Site does not use the old CSS flexbox',helpText:'The 2009 spec of Flexbox is deprecated and is 2.3x slower than the latest '+'spec. [Learn more](https://developers.google.com/web/tools/lighthouse/audits/old-flexbox).',requiredArtifacts:['Styles']};}
static audit(artifacts){if(artifacts.Styles.rawValue===-1){return NoOldFlexboxAudit.generateAuditResult(artifacts.Styles);}
const propsNames=['box-flex','box-orient','box-flex-group','display'];const propsNamesWithPrefixes=StyleHelpers.addVendorPrefixes(propsNames);const propsValues=['box','flexbox'];const sheetsUsingDisplayBox=StyleHelpers.filterStylesheetsByUsage(artifacts.Styles,propsNamesWithPrefixes,propsValues);const urlList=[];sheetsUsingDisplayBox.forEach(sheet=>{sheet.parsedContent.forEach(props=>{const formattedStyleRule=StyleHelpers.getFormattedStyleRule(sheet.content,props);urlList.push({url:sheet.header.sourceURL,label:formattedStyleRule.location,code:formattedStyleRule.styleRule});});});return NoOldFlexboxAudit.generateAuditResult({rawValue:sheetsUsingDisplayBox.length===0,extendedInfo:{formatter:Formatter.SUPPORTED_FORMATS.URLLIST,value:urlList}});}}
module.exports=NoOldFlexboxAudit;},{"../../formatters/formatter":8,"../../lib/styles-helpers":27,"../audit":3}],"../audits/dobetterweb/no-websql":[function(require,module,exports){'use strict';const Audit=require('../audit');class NoWebSQLAudit extends Audit{static get meta(){return{category:'Offline',name:'no-websql',description:'Site does not use WebSQL DB.',helpText:'Web SQL is deprecated. Consider using IndexedDB instead. '+'[Learn more](https://developers.google.com/web/tools/lighthouse/audits/web-sql).',requiredArtifacts:['WebSQL']};}
static audit(artifacts){if(artifacts.WebSQL.database===-1){return NoWebSQLAudit.generateAuditResult({rawValue:-1,debugString:artifacts.WebSQL.debugString});}
const db=artifacts.WebSQL.database;const displayValue=(db&&db.database?`db name: ${db.database.name}, version: ${db.database.version}`:'');return NoWebSQLAudit.generateAuditResult({rawValue:!db,displayValue:displayValue});}}
module.exports=NoWebSQLAudit;},{"../audit":3}],"../audits/dobetterweb/notification-on-start":[function(require,module,exports){'use strict';const Audit=require('../audit');const Formatter=require('../../formatters/formatter');class NotificationOnStart extends Audit{static get meta(){return{category:'UX',name:'notification-on-start',description:'Page does not automatically request notification permissions on page load',helpText:'Users are mistrustful of or confused by sites that request to send '+'notifications without context. Consider tying the request to user gestures '+'instead. [Learn more](https://developers.google.com/web/tools/lighthouse/audits/notifications-on-load).',requiredArtifacts:['NotificationOnStart']};}
static audit(artifacts){if(artifacts.NotificationOnStart.value===-1){let debugString='Unknown error with the NotificationOnStart gatherer';if(artifacts.NotificationOnStart.debugString){debugString=artifacts.NotificationOnStart.debugString;}
return NotificationOnStart.generateAuditResult({rawValue:-1,debugString});}
const results=artifacts.NotificationOnStart.usage.map(err=>{return Object.assign({label:`line: ${err.line}, col: ${err.col}`},err);});return NotificationOnStart.generateAuditResult({rawValue:results.length===0,extendedInfo:{formatter:Formatter.SUPPORTED_FORMATS.URLLIST,value:results}});}}
module.exports=NotificationOnStart;},{"../../formatters/formatter":8,"../audit":3}],"../audits/dobetterweb/script-blocking-first-paint":[function(require,module,exports){'use strict';const Audit=require('../audit');const LinkBlockingFirstPaintAudit=require('./link-blocking-first-paint');class ScriptBlockingFirstPaint extends Audit{static get meta(){return{category:'Performance',name:'script-blocking-first-paint',description:'Site does not use <script> in head that delays first paint',helpText:'Script elements are blocking the first paint of your page. Consider inlining '+'critical scripts and deferring non-critical ones. '+'[Learn more](https://developers.google.com/web/tools/lighthouse/audits/blocking-resources).',requiredArtifacts:['TagsBlockingFirstPaint']};}
static audit(artifacts){const result=LinkBlockingFirstPaintAudit.computeAuditResultForTags(artifacts,'SCRIPT');return ScriptBlockingFirstPaint.generateAuditResult(result);}}
module.exports=ScriptBlockingFirstPaint;},{"../audit":3,"./link-blocking-first-paint":"../audits/dobetterweb/link-blocking-first-paint"}],"../audits/dobetterweb/uses-http2":[function(require,module,exports){'use strict';const URL=require('../../lib/url-shim');const Audit=require('../audit');const Formatter=require('../../formatters/formatter');class UsesHTTP2Audit extends Audit{static get meta(){return{category:'Performance',name:'uses-http2',description:'Site uses HTTP/2 for its own resources',helpText:'HTTP/2 offers many benefits over HTTP/1.1, including binary headers, '+'multiplexing, and server push. [Learn more](https://developers.google.com/web/tools/lighthouse/audits/http2).',requiredArtifacts:['URL','networkRecords']};}
static audit(artifacts){const networkRecords=artifacts.networkRecords[Audit.DEFAULT_PASS];const finalHost=new URL(artifacts.URL.finalUrl).host;const resources=networkRecords.filter(record=>{const requestHost=new URL(record._url).host;const sameHost=requestHost===finalHost;const notH2=/HTTP\/[01][\.\d]?/i.test(record.protocol);return sameHost&&notH2;}).map(record=>{return{label:record.protocol,url:record.url};});let displayValue='';if(resources.length>1){displayValue=`${resources.length} requests were not handled over h2`;}else if(resources.length===1){displayValue=`${resources.length} request was not handled over h2`;}
return UsesHTTP2Audit.generateAuditResult({rawValue:resources.length===0,displayValue:displayValue,extendedInfo:{formatter:Formatter.SUPPORTED_FORMATS.URLLIST,value:resources}});}}
module.exports=UsesHTTP2Audit;},{"../../formatters/formatter":8,"../../lib/url-shim":30,"../audit":3}],"../audits/dobetterweb/uses-passive-event-listeners":[function(require,module,exports){'use strict';const URL=require('../../lib/url-shim');const Audit=require('../audit');const EventHelpers=require('../../lib/event-helpers');const Formatter=require('../../formatters/formatter');class PassiveEventsAudit extends Audit{static get SCROLL_BLOCKING_EVENTS(){return['wheel','mousewheel','touchstart','touchmove'];}
static get meta(){return{category:'JavaScript',name:'uses-passive-event-listeners',description:'Site uses passive listeners to improve scrolling performance',helpText:'Consider marking your touch and wheel event listeners as `passive` '+'to improve your page\'s scroll performance. '+'[Learn more](https://developers.google.com/web/tools/lighthouse/audits/passive-event-listeners).',requiredArtifacts:['URL','EventListeners']};}
static audit(artifacts){if(artifacts.EventListeners.rawValue===-1){return PassiveEventsAudit.generateAuditResult(artifacts.EventListeners);}
let debugString;const listeners=artifacts.EventListeners;const results=listeners.filter(loc=>{const isScrollBlocking=this.SCROLL_BLOCKING_EVENTS.indexOf(loc.type)!==-1;const mentionsPreventDefault=loc.handler.description.match(/\.preventDefault\(\s*\)/g);let sameHost=URL.hostsMatch(artifacts.URL.finalUrl,loc.url);if(!URL.isValid(loc.url)){sameHost=true;debugString=URL.INVALID_URL_DEBUG_STRING;}
return sameHost&&isScrollBlocking&&!loc.passive&&!mentionsPreventDefault;}).map(EventHelpers.addFormattedCodeSnippet);const groupedResults=EventHelpers.groupCodeSnippetsByLocation(results);return PassiveEventsAudit.generateAuditResult({rawValue:groupedResults.length===0,extendedInfo:{formatter:Formatter.SUPPORTED_FORMATS.URLLIST,value:groupedResults},debugString});}}
module.exports=PassiveEventsAudit;},{"../../formatters/formatter":8,"../../lib/event-helpers":22,"../../lib/url-shim":30,"../audit":3}],"../audits/estimated-input-latency":[function(require,module,exports){'use strict';const Audit=require('./audit');const TracingProcessor=require('../lib/traces/tracing-processor');const Formatter=require('../formatters/formatter');const SCORING_POINT_OF_DIMINISHING_RETURNS=50;const SCORING_MEDIAN=100;class EstimatedInputLatency extends Audit{static get meta(){return{category:'Performance',name:'estimated-input-latency',description:'Estimated Input Latency',optimalValue:SCORING_POINT_OF_DIMINISHING_RETURNS.toLocaleString()+'ms',helpText:'The score above is an estimate of how long your app takes to respond to user '+'input, in milliseconds. There is a 90% probability that a user encounters this amount '+'of latency, or less. 10% of the time a user can expect additional latency. If your '+'score is higher than Lighthouse\'s target score, users may perceive your app as '+'laggy. [Learn more](https://developers.google.com/web/tools/lighthouse/audits/estimated-input-latency).',requiredArtifacts:['traces']};}
static calculate(speedline,trace){const startTime=speedline.first;const tracingProcessor=new TracingProcessor();const model=tracingProcessor.init(trace);const latencyPercentiles=TracingProcessor.getRiskToResponsiveness(model,trace,startTime);const ninetieth=latencyPercentiles.find(result=>result.percentile===0.9);const rawValue=parseFloat(ninetieth.time.toFixed(1));const distribution=TracingProcessor.getLogNormalDistribution(SCORING_MEDIAN,SCORING_POINT_OF_DIMINISHING_RETURNS);const score=100*distribution.computeComplementaryPercentile(ninetieth.time);return EstimatedInputLatency.generateAuditResult({score:Math.round(score),optimalValue:this.meta.optimalValue,rawValue,displayValue:`${rawValue}ms`,extendedInfo:{value:latencyPercentiles,formatter:Formatter.SUPPORTED_FORMATS.NULL}});}
static audit(artifacts){const trace=artifacts.traces[this.DEFAULT_PASS];return artifacts.requestSpeedline(trace).then(speedline=>EstimatedInputLatency.calculate(speedline,trace)).catch(err=>{return EstimatedInputLatency.generateAuditResult({rawValue:-1,debugString:'Speedline unable to parse trace contents: '+err.message});});}}
module.exports=EstimatedInputLatency;},{"../formatters/formatter":8,"../lib/traces/tracing-processor":29,"./audit":3}],"../audits/first-meaningful-paint":[function(require,module,exports){'use strict';const Audit=require('./audit');const TracingProcessor=require('../lib/traces/tracing-processor');const Formatter=require('../formatters/formatter');const SCORING_POINT_OF_DIMINISHING_RETURNS=1600;const SCORING_MEDIAN=4000;const FCPFMP_TOLERANCE=32*1000;class FirstMeaningfulPaint extends Audit{static get meta(){return{category:'Performance',name:'first-meaningful-paint',description:'First meaningful paint',optimalValue:SCORING_POINT_OF_DIMINISHING_RETURNS.toLocaleString()+'ms',helpText:'First meaningful paint measures when the primary content of a page is visible. '+'[Learn more](https://developers.google.com/web/tools/lighthouse/audits/first-meaningful-paint).',requiredArtifacts:['traces']};}
static audit(artifacts){return new Promise((resolve,reject)=>{const traceContents=artifacts.traces[this.DEFAULT_PASS].traceEvents;const evts=this.collectEvents(traceContents);const result=this.calculateScore(evts);resolve(FirstMeaningfulPaint.generateAuditResult({score:result.score,rawValue:parseFloat(result.duration),displayValue:`${result.duration}ms`,debugString:result.debugString,optimalValue:this.meta.optimalValue,extendedInfo:{value:result.extendedInfo,formatter:Formatter.SUPPORTED_FORMATS.NULL}}));}).catch(err=>{return FirstMeaningfulPaint.generateAuditResult({rawValue:-1,debugString:err.message});});}
static calculateScore(evts){const firstMeaningfulPaint=(evts.firstMeaningfulPaint.ts-evts.navigationStart.ts)/1000;const firstContentfulPaint=(evts.firstContentfulPaint.ts-evts.navigationStart.ts)/1000;const extendedInfo={timestamps:{navStart:evts.navigationStart.ts,fCP:evts.firstContentfulPaint.ts,fMP:evts.firstMeaningfulPaint.ts},timings:{navStart:0,fCP:parseFloat(firstContentfulPaint.toFixed(3)),fMP:parseFloat(firstMeaningfulPaint.toFixed(3))}};const distribution=TracingProcessor.getLogNormalDistribution(SCORING_MEDIAN,SCORING_POINT_OF_DIMINISHING_RETURNS);let score=100*distribution.computeComplementaryPercentile(firstMeaningfulPaint);score=Math.min(100,score);score=Math.max(0,score);return{duration:`${firstMeaningfulPaint.toFixed(1)}`,score:Math.round(score),rawValue:parseFloat(firstMeaningfulPaint.toFixed(1)),extendedInfo};}
static collectEvents(traceData){const events=traceData.filter(e=>{return e.cat.includes('blink.user_timing')||e.name==='TracingStartedInPage';}).sort((event0,event1)=>event0.ts-event1.ts);const startedInPageEvt=events.find(e=>e.name==='TracingStartedInPage');const frameEvents=events.filter(e=>e.args.frame===startedInPageEvt.args.data.page);const firstFCP=frameEvents.find(e=>e.name==='firstContentfulPaint');const navigationStart=frameEvents.filter(e=>e.name==='navigationStart'&&e.ts<firstFCP.ts).pop();const firstMeaningfulPaint=frameEvents.find(e=>e.name==='firstMeaningfulPaint'&&e.ts>=(firstFCP.ts-FCPFMP_TOLERANCE));if(!firstMeaningfulPaint){throw new Error('No usable `firstMeaningfulPaint` event found in trace');}
if(!navigationStart){throw new Error('No `navigationStart` event found in trace');}
return{navigationStart,firstMeaningfulPaint,firstContentfulPaint:firstFCP};}}
module.exports=FirstMeaningfulPaint;},{"../formatters/formatter":8,"../lib/traces/tracing-processor":29,"./audit":3}],"../audits/is-on-https":[function(require,module,exports){'use strict';const Audit=require('./audit');class HTTPS extends Audit{static get meta(){return{category:'Security',name:'is-on-https',description:'Site is on HTTPS',helpText:'All sites should be protected with HTTPS, even ones that don\'t handle '+'sensitive data. HTTPS prevents intruders from tampering with or passively listening '+'in on the communications between your app and your users, and is a prerequisite for '+'HTTP/2 and many new web platform APIs. '+'[Learn more](https://developers.google.com/web/tools/lighthouse/audits/https).',requiredArtifacts:['HTTPS']};}
static audit(artifacts){return HTTPS.generateAuditResult({rawValue:artifacts.HTTPS.value,debugString:artifacts.HTTPS.debugString});}}
module.exports=HTTPS;},{"./audit":3}],"../audits/manifest-background-color":[function(require,module,exports){'use strict';const Audit=require('./audit');const Formatter=require('../formatters/formatter');class ManifestBackgroundColor extends Audit{static get meta(){return{category:'Manifest',name:'manifest-background-color',description:'Manifest contains `background_color`',requiredArtifacts:['Manifest']};}
static getBackgroundColorValue(manifest){return manifest!==undefined&&manifest.background_color.value;}
static audit(artifacts){const bgColor=ManifestBackgroundColor.getBackgroundColorValue(artifacts.Manifest.value);return ManifestBackgroundColor.generateAuditResult({rawValue:!!bgColor,extendedInfo:{value:bgColor,formatter:Formatter.SUPPORTED_FORMATS.NULL}});}}
module.exports=ManifestBackgroundColor;},{"../formatters/formatter":8,"./audit":3}],"../audits/manifest-display":[function(require,module,exports){'use strict';const Audit=require('./audit');class ManifestDisplay extends Audit{static get meta(){return{category:'Manifest',name:'manifest-display',description:'Manifest\'s `display` property is set',requiredArtifacts:['Manifest']};}
static hasRecommendedValue(val){return['browser','fullscreen','minimal-ui','standalone'].indexOf(val)!==-1;}
static audit(artifacts){const manifest=artifacts.Manifest.value;const displayValue=manifest&&manifest.display.value;const hasRecommendedValue=ManifestDisplay.hasRecommendedValue(displayValue);const auditResult={rawValue:hasRecommendedValue,displayValue};if(!hasRecommendedValue){auditResult.debugString='Manifest display property should be set.';}
return ManifestDisplay.generateAuditResult(auditResult);}}
module.exports=ManifestDisplay;},{"./audit":3}],"../audits/manifest-exists":[function(require,module,exports){'use strict';const Audit=require('./audit');class ManifestExists extends Audit{static get meta(){return{category:'Manifest',name:'manifest-exists',description:'Manifest exists',requiredArtifacts:['Manifest']};}
static audit(artifacts){return ManifestExists.generateAuditResult({rawValue:typeof artifacts.Manifest.value!=='undefined',debugString:artifacts.Manifest.debugString});}}
module.exports=ManifestExists;},{"./audit":3}],"../audits/manifest-icons-min-144":[function(require,module,exports){'use strict';const Audit=require('./audit');const icons=require('../lib/icons');class ManifestIconsMin144 extends Audit{static get meta(){return{category:'Manifest',name:'manifest-icons-min-144',description:'Manifest contains icons at least 144px',requiredArtifacts:['Manifest']};}
static audit(artifacts){const manifest=artifacts.Manifest.value;if(icons.doExist(manifest)===false){return ManifestIconsMin144.generateAuditResult({rawValue:false,debugString:'WARNING: No icons found in the manifest'});}
const matchingIcons=icons.sizeAtLeast(144,(manifest));let displayValue;let debugString;if(matchingIcons.length){displayValue=`found sizes: ${matchingIcons.join(', ')}`;}else{debugString='WARNING: No icons are at least 144px';}
return ManifestIconsMin144.generateAuditResult({rawValue:!!matchingIcons.length,displayValue,debugString});}}
module.exports=ManifestIconsMin144;},{"../lib/icons":23,"./audit":3}],"../audits/manifest-icons-min-192":[function(require,module,exports){'use strict';const Audit=require('./audit');const icons=require('../lib/icons');class ManifestIconsMin192 extends Audit{static get meta(){return{category:'Manifest',name:'manifest-icons-min-192',description:'Manifest contains icons at least 192px',requiredArtifacts:['Manifest']};}
static audit(artifacts){const manifest=artifacts.Manifest.value;if(icons.doExist(manifest)===false){return ManifestIconsMin192.generateAuditResult({rawValue:false,debugString:'WARNING: No icons found in the manifest'});}
const matchingIcons=icons.sizeAtLeast(192,(manifest));let displayValue;let debugString;if(matchingIcons.length){displayValue=`found sizes: ${matchingIcons.join(', ')}`;}else{debugString='WARNING: No icons are at least 192px';}
return ManifestIconsMin192.generateAuditResult({rawValue:!!matchingIcons.length,displayValue,debugString});}}
module.exports=ManifestIconsMin192;},{"../lib/icons":23,"./audit":3}],"../audits/manifest-name":[function(require,module,exports){'use strict';const Audit=require('./audit');class ManifestName extends Audit{static get meta(){return{category:'Manifest',name:'manifest-name',description:'Manifest contains `name`',requiredArtifacts:['Manifest']};}
static audit(artifacts){let hasName=false;const manifest=artifacts.Manifest.value;if(manifest&&manifest.name){hasName=(!!manifest.name.value);}
return ManifestName.generateAuditResult({rawValue:hasName});}}
module.exports=ManifestName;},{"./audit":3}],"../audits/manifest-short-name-length":[function(require,module,exports){'use strict';const Audit=require('./audit');class ManifestShortNameLength extends Audit{static get meta(){return{category:'Manifest',name:'manifest-short-name-length',description:'Manifest\'s `short_name` won\'t be truncated when displayed on homescreen',requiredArtifacts:['Manifest']};}
static audit(artifacts){let isShortNameShortEnough=false;let debugString;const manifest=artifacts.Manifest.value;const suggestedLength=12;if(manifest){const manifestValue=manifest.short_name.value||manifest.name.value||'';isShortNameShortEnough=manifestValue&&manifestValue.length<=suggestedLength;if(!isShortNameShortEnough){debugString=`${suggestedLength} chars is the suggested maximum homescreen label length`;debugString+=` (Found: ${manifestValue.length} chars).`;}}
return ManifestShortNameLength.generateAuditResult({rawValue:isShortNameShortEnough,debugString});}}
module.exports=ManifestShortNameLength;},{"./audit":3}],"../audits/manifest-short-name":[function(require,module,exports){'use strict';const Audit=require('./audit');class ManifestShortName extends Audit{static get meta(){return{category:'Manifest',name:'manifest-short-name',description:'Manifest contains `short_name`',requiredArtifacts:['Manifest']};}
static audit(artifacts){let hasShortName=false;const manifest=artifacts.Manifest.value;if(manifest){hasShortName=!!(manifest.short_name.value||manifest.name.value);}
return ManifestShortName.generateAuditResult({rawValue:hasShortName});}}
module.exports=ManifestShortName;},{"./audit":3}],"../audits/manifest-start-url":[function(require,module,exports){'use strict';const Audit=require('./audit');class ManifestStartUrl extends Audit{static get meta(){return{category:'Manifest',name:'manifest-start-url',description:'Manifest contains `start_url`',requiredArtifacts:['Manifest']};}
static audit(artifacts){let hasStartUrl=false;const manifest=artifacts.Manifest.value;if(manifest&&manifest.start_url){hasStartUrl=(!!manifest.start_url.value);}
return ManifestStartUrl.generateAuditResult({rawValue:hasStartUrl});}}
module.exports=ManifestStartUrl;},{"./audit":3}],"../audits/manifest-theme-color":[function(require,module,exports){'use strict';const Audit=require('./audit');class ManifestThemeColor extends Audit{static get meta(){return{category:'Manifest',name:'manifest-theme-color',description:'Manifest contains `theme_color`',requiredArtifacts:['Manifest']};}
static audit(artifacts){let hasThemeColor=false;const manifest=artifacts.Manifest.value;if(manifest&&manifest.theme_color){hasThemeColor=(!!manifest.theme_color.value);}
return ManifestThemeColor.generateAuditResult({rawValue:hasThemeColor});}}
module.exports=ManifestThemeColor;},{"./audit":3}],"../audits/redirects-http":[function(require,module,exports){'use strict';const Audit=require('./audit');class RedirectsHTTP extends Audit{static get meta(){return{category:'Security',name:'redirects-http',description:'Site redirects HTTP traffic to HTTPS',helpText:'If you\'ve already set up HTTPS, make sure that you redirect all HTTP traffic '+'to HTTPS. [Learn more](https://developers.google.com/web/tools/lighthouse/audits/http-redirects-to-https).',requiredArtifacts:['HTTPRedirect']};}
static audit(artifacts){return RedirectsHTTP.generateAuditResult({rawValue:artifacts.HTTPRedirect.value,debugString:artifacts.HTTPRedirect.debugString});}}
module.exports=RedirectsHTTP;},{"./audit":3}],"../audits/screenshots":[function(require,module,exports){'use strict';const Audit=require('./audit');const Formatter=require('../formatters/formatter');class Screenshots extends Audit{static get meta(){return{category:'Performance',name:'screenshots',description:'Screenshots of all captured frames',requiredArtifacts:['traces']};}
static audit(artifacts){const trace=artifacts.traces[this.DEFAULT_PASS];return artifacts.requestScreenshots(trace).then(screenshots=>{if(typeof screenshots==='undefined'){return Screenshots.generateAuditResult({rawValue:-1,debugString:'No screenshot artifact'});}
return Screenshots.generateAuditResult({rawValue:screenshots.length||0,extendedInfo:{formatter:Formatter.SUPPORTED_FORMATS.NULL,value:screenshots}});});}}
module.exports=Screenshots;},{"../formatters/formatter":8,"./audit":3}],"../audits/service-worker":[function(require,module,exports){'use strict';const URL=require('../lib/url-shim');const Audit=require('./audit');function getActivatedServiceWorker(versions,url){const origin=new URL(url).origin;return versions.find(v=>v.status==='activated'&&new URL(v.scriptURL).origin===origin);}
class ServiceWorker extends Audit{static get meta(){return{category:'Offline',name:'service-worker',description:'Has a registered Service Worker',helpText:'The service worker is the technology that enables your app to use many '+'Progressive Web App features, such as offline, add to homescreen, and push '+'notifications. [Learn more](https://developers.google.com/web/tools/lighthouse/audits/registered-service-worker).',requiredArtifacts:['URL','ServiceWorker']};}
static audit(artifacts){if(!artifacts.ServiceWorker.versions){return ServiceWorker.generateAuditResult({rawValue:false,debugString:artifacts.ServiceWorker.debugString});}
const version=getActivatedServiceWorker(artifacts.ServiceWorker.versions,artifacts.URL.finalUrl);const debugString=version?undefined:'No active service worker found for this origin.';return ServiceWorker.generateAuditResult({rawValue:!!version,debugString:debugString});}}
module.exports=ServiceWorker;},{"../lib/url-shim":30,"./audit":3}],"../audits/speed-index-metric":[function(require,module,exports){'use strict';const Audit=require('./audit');const TracingProcessor=require('../lib/traces/tracing-processor');const Formatter=require('../formatters/formatter');const SCORING_POINT_OF_DIMINISHING_RETURNS=1250;const SCORING_MEDIAN=5500;class SpeedIndexMetric extends Audit{static get meta(){return{category:'Performance',name:'speed-index-metric',description:'Perceptual Speed Index',helpText:'Speed Index shows how quickly the contents of a page are visibly populated. '+'[Learn more](https://developers.google.com/web/tools/lighthouse/audits/speed-index).',optimalValue:SCORING_POINT_OF_DIMINISHING_RETURNS.toLocaleString(),requiredArtifacts:['traces']};}
static audit(artifacts){const trace=artifacts.traces[this.DEFAULT_PASS];return artifacts.requestSpeedline(trace).then(speedline=>{if(speedline.frames.length===0){return SpeedIndexMetric.generateAuditResult({rawValue:-1,debugString:'Trace unable to find visual progress frames.'});}
if(speedline.speedIndex===0){return SpeedIndexMetric.generateAuditResult({rawValue:-1,debugString:'Error in Speedline calculating Speed Index (speedIndex of 0).'});}
const distribution=TracingProcessor.getLogNormalDistribution(SCORING_MEDIAN,SCORING_POINT_OF_DIMINISHING_RETURNS);let score=100*distribution.computeComplementaryPercentile(speedline.perceptualSpeedIndex);score=Math.min(100,score);score=Math.max(0,score);const extendedInfo={timings:{firstVisualChange:speedline.first,visuallyComplete:speedline.complete,speedIndex:speedline.speedIndex,perceptualSpeedIndex:speedline.perceptualSpeedIndex},timestamps:{firstVisualChange:(speedline.first+speedline.beginning)*1000,visuallyComplete:(speedline.complete+speedline.beginning)*1000,speedIndex:(speedline.speedIndex+speedline.beginning)*1000,perceptualSpeedIndex:(speedline.perceptualSpeedIndex+speedline.beginning)*1000},frames:speedline.frames.map(frame=>{return{timestamp:frame.getTimeStamp(),progress:frame.getPerceptualProgress()};})};return SpeedIndexMetric.generateAuditResult({score:Math.round(score),rawValue:Math.round(speedline.perceptualSpeedIndex),optimalValue:this.meta.optimalValue,extendedInfo:{formatter:Formatter.SUPPORTED_FORMATS.SPEEDLINE,value:extendedInfo}});}).catch(err=>{return SpeedIndexMetric.generateAuditResult({rawValue:-1,debugString:err.message});});}}
module.exports=SpeedIndexMetric;},{"../formatters/formatter":8,"../lib/traces/tracing-processor":29,"./audit":3}],"../audits/theme-color-meta":[function(require,module,exports){'use strict';const validColor=require('../lib/web-inspector').Color.parse;const Audit=require('./audit');class ThemeColor extends Audit{static get meta(){return{category:'HTML',name:'theme-color-meta',description:'HTML has a `<meta name="theme-color">` tag',requiredArtifacts:['ThemeColor']};}
static audit(artifacts){const themeColorMeta=artifacts.ThemeColor;if(themeColorMeta===null||themeColorMeta===-1){return ThemeColor.generateAuditResult({rawValue:false,debugString:'No valid theme-color meta tag found.'});}
if(!validColor(themeColorMeta)){return ThemeColor.generateAuditResult({displayValue:themeColorMeta,rawValue:false,debugString:'The theme-color meta tag did not contain a valid CSS color.'});}
return ThemeColor.generateAuditResult({displayValue:themeColorMeta,rawValue:true});}}
module.exports=ThemeColor;},{"../lib/web-inspector":31,"./audit":3}],"../audits/time-to-interactive":[function(require,module,exports){'use strict';const Audit=require('./audit');const TracingProcessor=require('../lib/traces/tracing-processor');const FMPMetric=require('./first-meaningful-paint');const Formatter=require('../formatters/formatter');const SCORING_POINT_OF_DIMINISHING_RETURNS=1700;const SCORING_MEDIAN=5000;const SCORING_TARGET=5000;class TTIMetric extends Audit{static get meta(){return{category:'Performance',name:'time-to-interactive',description:'Time To Interactive (alpha)',helpText:'Time to Interactive identifies the time at which your app appears to be ready '+'enough to interact with. '+'[Learn more](https://developers.google.com/web/tools/lighthouse/audits/time-to-interactive).',optimalValue:SCORING_TARGET.toLocaleString()+'ms',requiredArtifacts:['traces']};}
static audit(artifacts){const trace=artifacts.traces[Audit.DEFAULT_PASS];const pendingSpeedline=artifacts.requestSpeedline(trace);const pendingFMP=FMPMetric.audit(artifacts);return Promise.all([pendingSpeedline,pendingFMP]).then(results=>{const speedline=results[0];const fmpResult=results[1];if(fmpResult.rawValue===-1){return generateError(fmpResult.debugString);}
const tracingProcessor=new TracingProcessor();const trace=artifacts.traces[Audit.DEFAULT_PASS];const model=tracingProcessor.init(trace);const endOfTraceTime=model.bounds.max;const fmpTiming=fmpResult.rawValue;const fmpResultExt=fmpResult.extendedInfo.value;const fMPtsInMS=fmpResultExt.timestamps.fMP/1000;const navStartTsInMS=fmpResultExt.timestamps.navStart/1000;let visuallyReadyTiming=0;if(speedline.frames){const eightyFivePctVC=speedline.frames.find(frame=>{return frame.getTimeStamp()>=fMPtsInMS&&frame.getProgress()>=85;});if(eightyFivePctVC){visuallyReadyTiming=eightyFivePctVC.getTimeStamp()-navStartTsInMS;}}
let startTime=Math.max(fmpTiming,visuallyReadyTiming)-50;let endTime;let currentLatency=Infinity;const percentiles=[0.9];const threshold=50;const foundLatencies=[];while(currentLatency>threshold){startTime+=50;endTime=startTime+500;if(endTime>endOfTraceTime){return generateError('Entire trace was found to be busy.');}
const latencies=TracingProcessor.getRiskToResponsiveness(model,trace,startTime,endTime,percentiles);const estLatency=latencies[0].time;foundLatencies.push({estLatency:estLatency,startTime:startTime.toFixed(1)});currentLatency=estLatency;}
const timeToInteractive=startTime;const distribution=TracingProcessor.getLogNormalDistribution(SCORING_MEDIAN,SCORING_POINT_OF_DIMINISHING_RETURNS);let score=100*distribution.computeComplementaryPercentile(startTime);score=Math.min(100,score);score=Math.max(0,score);score=Math.round(score);const extendedInfo={timings:{fMP:parseFloat(fmpTiming.toFixed(3)),visuallyReady:parseFloat(visuallyReadyTiming.toFixed(3)),timeToInteractive:parseFloat(startTime.toFixed(3))},timestamps:{fMP:fMPtsInMS*1000,visuallyReady:(visuallyReadyTiming+navStartTsInMS)*1000,timeToInteractive:(timeToInteractive+navStartTsInMS)*1000},expectedLatencyAtTTI:parseFloat(currentLatency.toFixed(3)),foundLatencies};return TTIMetric.generateAuditResult({score,rawValue:parseFloat(timeToInteractive.toFixed(1)),displayValue:`${parseFloat(timeToInteractive.toFixed(1))}ms`,optimalValue:this.meta.optimalValue,debugString:speedline.debugString,extendedInfo:{value:extendedInfo,formatter:Formatter.SUPPORTED_FORMATS.NULL}});}).catch(err=>{return generateError(err);});}}
module.exports=TTIMetric;function generateError(err){return TTIMetric.generateAuditResult({value:-1,rawValue:-1,optimalValue:TTIMetric.meta.optimalValue,debugString:err.message||err});}},{"../formatters/formatter":8,"../lib/traces/tracing-processor":29,"./audit":3,"./first-meaningful-paint":"../audits/first-meaningful-paint"}],"../audits/unused-css-rules":[function(require,module,exports){'use strict';const Audit=require('./audit');const Formatter=require('../formatters/formatter');const PREVIEW_LENGTH=100;const ALLOWABLE_UNUSED_RULES_RATIO=0.10;class UnusedCSSRules extends Audit{static get meta(){return{category:'Best Practices',name:'unused-css-rules',description:'Site does not have more than 10% unused CSS',helpText:'Remove unused rules from stylesheets to reduce unnecessary '+'bytes consumed by network activity. [Learn more](https://developers.google.com/speed/docs/insights/OptimizeCSSDelivery)',requiredArtifacts:['CSSUsage','Styles']};}
static indexStylesheetsById(styles){return styles.reduce((indexed,stylesheet)=>{indexed[stylesheet.header.styleSheetId]=Object.assign({used:[],unused:[],},stylesheet);return indexed;},{});}
static countUnusedRules(rules,indexedStylesheets){let unused=0;rules.forEach(rule=>{const stylesheetInfo=indexedStylesheets[rule.styleSheetId];if(rule.used){stylesheetInfo.used.push(rule);}else{unused++;stylesheetInfo.unused.push(rule);}});return unused;}
static mapSheetToResult(stylesheetInfo){const numUsed=stylesheetInfo.used.length;const numUnused=stylesheetInfo.unused.length;const percentUsed=Math.round(100*numUsed/(numUsed+numUnused))||0;let contentPreview=stylesheetInfo.content;if(contentPreview.length>PREVIEW_LENGTH){const firstRuleStart=contentPreview.indexOf('{');const firstRuleEnd=contentPreview.indexOf('}');if(firstRuleStart===-1||firstRuleEnd===-1||firstRuleStart>firstRuleEnd||firstRuleStart>PREVIEW_LENGTH){contentPreview=contentPreview.slice(0,PREVIEW_LENGTH)+'...';}else if(firstRuleEnd<PREVIEW_LENGTH){contentPreview=contentPreview.slice(0,firstRuleEnd+1)+' ...';}else{const lastSemicolonIndex=contentPreview.slice(0,PREVIEW_LENGTH).lastIndexOf(';');contentPreview=lastSemicolonIndex<firstRuleStart?contentPreview.slice(0,PREVIEW_LENGTH)+'... } ...':contentPreview.slice(0,lastSemicolonIndex+1)+' ... } ...';}}
return{url:stylesheetInfo.header.sourceURL||'inline',label:`${percentUsed}% rules used`,code:contentPreview.trim(),};}
static audit(artifacts){const styles=artifacts.Styles;const usage=artifacts.CSSUsage;if(styles.rawValue===-1){return UnusedCSSRules.generateAuditResult(styles);}else if(usage.rawValue===-1){return UnusedCSSRules.generateAuditResult(usage);}
const indexedSheets=UnusedCSSRules.indexStylesheetsById(styles);const unused=UnusedCSSRules.countUnusedRules(usage,indexedSheets);const unusedRatio=(unused/usage.length)||0;const results=Object.keys(indexedSheets).map(sheetId=>{return UnusedCSSRules.mapSheetToResult(indexedSheets[sheetId]);});let displayValue='';if(unused>1){displayValue=`${unused} CSS rules were unused`;}else if(unused===1){displayValue=`${unused} CSS rule was unused`;}
return UnusedCSSRules.generateAuditResult({displayValue,rawValue:unusedRatio<ALLOWABLE_UNUSED_RULES_RATIO,extendedInfo:{formatter:Formatter.SUPPORTED_FORMATS.URLLIST,value:results}});}}
module.exports=UnusedCSSRules;},{"../formatters/formatter":8,"./audit":3}],"../audits/user-timings":[function(require,module,exports){'use strict';const Audit=require('./audit');const Formatter=require('../formatters/formatter');const TimelineModel=require('../lib/traces/devtools-timeline-model');function filterTrace(traceData){const userTimings=[];const measuresStartTimes={};let traceStartFound=false;let navigationStartTime;const timelineModel=new TimelineModel(traceData);const modeledTraceData=timelineModel.timelineModel();modeledTraceData.mainThreadEvents().filter(ut=>{if(ut.name==='TracingStartedInPage'||ut.name==='navigationStart'){return true;}
if(ut.hasCategory('blink.user_timing')){return ut.name!=='requestStart'&&ut.name!=='paintNonDefaultBackgroundColor'&&ut.args.frame===undefined;}
return false;}).forEach(ut=>{if(ut.phase==='R'||ut.phase.toUpperCase()==='I'){if(ut.name==='TracingStartedInPage'&&!traceStartFound){traceStartFound=true;return;}
if(ut.name==='navigationStart'&&traceStartFound&&!navigationStartTime){navigationStartTime=ut.startTime;}
if(ut.name!=='navigationStart'){userTimings.push({name:ut.name,isMark:true,args:ut.args,startTime:ut.startTime});}}else if(ut.phase.toLowerCase()==='b'){measuresStartTimes[ut.name]=ut.startTime;}else if(ut.phase.toLowerCase()==='e'){userTimings.push({name:ut.name,isMark:false,args:ut.args,startTime:measuresStartTimes[ut.name],duration:ut.startTime-measuresStartTimes[ut.name],endTime:ut.startTime});}});userTimings.forEach(ut=>{ut.startTime-=navigationStartTime;if(!ut.isMark){ut.endTime-=navigationStartTime;ut.duration=ut.duration;}});return userTimings;}
class UserTimings extends Audit{static get meta(){return{category:'Performance',name:'user-timings',description:'User Timing marks and measures',helpText:'Consider instrumenting your app with the User Timing API to create custom, '+'real-world measurements of key user experiences. '+'[Learn more](https://developers.google.com/web/tools/lighthouse/audits/user-timing).',requiredArtifacts:['traces']};}
static audit(artifacts){const traceContents=artifacts.traces[Audit.DEFAULT_PASS].traceEvents;const userTimings=filterTrace(traceContents);return UserTimings.generateAuditResult({rawValue:true,displayValue:userTimings.length,extendedInfo:{formatter:Formatter.SUPPORTED_FORMATS.USER_TIMINGS,value:userTimings}});}}
module.exports=UserTimings;},{"../formatters/formatter":8,"../lib/traces/devtools-timeline-model":28,"./audit":3}],"../audits/viewport":[function(require,module,exports){'use strict';const Audit=require('./audit');class Viewport extends Audit{static get meta(){return{category:'Mobile Friendly',name:'viewport',description:'HTML has a `<meta name="viewport">` tag',helpText:'Add a viewport meta tag to optimize your app for mobile screens. '+'[Learn more](https://developers.google.com/web/tools/lighthouse/audits/has-viewport-meta-tag").',requiredArtifacts:['Viewport']};}
static audit(artifacts){const hasMobileViewport=typeof artifacts.Viewport==='string'&&artifacts.Viewport.includes('width=');return Viewport.generateAuditResult({rawValue:!!hasMobileViewport});}}
module.exports=Viewport;},{"./audit":3}],"../audits/without-javascript":[function(require,module,exports){'use strict';const Audit=require('./audit');class WithoutJavaScript extends Audit{static get meta(){return{category:'JavaScript',name:'without-javascript',description:'Page contains some content when its scripts are not available',helpText:'Your app should display some content when JavaScript is disabled, even if it\'s '+'just a warning to the user that JavaScript is required to use the app. '+'[Learn more](https://developers.google.com/web/tools/lighthouse/audits/no-js).',requiredArtifacts:['HTMLWithoutJavaScript']};}
static audit(artifacts){const artifact=artifacts.HTMLWithoutJavaScript;if(typeof artifact.value!=='string'){return WithoutJavaScript.generateAuditResult({rawValue:-1,debugString:artifact.debugString||'HTMLWithoutJavaScript gatherer did not complete successfully'});}
if(artifact.value.trim()===''){return WithoutJavaScript.generateAuditResult({rawValue:false,debugString:'The page body should render some content if its scripts are not available.'});}
return WithoutJavaScript.generateAuditResult({rawValue:true});}}
module.exports=WithoutJavaScript;},{"./audit":3}],"../audits/works-offline":[function(require,module,exports){'use strict';const Audit=require('./audit');class WorksOffline extends Audit{static get meta(){return{category:'Offline',name:'works-offline',description:'URL responds with a 200 when offline',helpText:'If you\'re building a Progressive Web App, consider using a service worker so '+'that your app can work offline. '+'[Learn more](https://developers.google.com/web/tools/lighthouse/audits/http-200-when-offline).',requiredArtifacts:['Offline']};}
static audit(artifacts){return WorksOffline.generateAuditResult({rawValue:artifacts.Offline===200});}}
module.exports=WorksOffline;},{"./audit":3}],"./computed/computed-artifact":[function(require,module,exports){'use strict';class ComputedArtifact{constructor(){this.cache=new Map();}
compute_(artifact){throw new Error('compute_() not implemented for computed artifact '+this.name);}
request(artifact){if(this.cache.has(artifact)){return Promise.resolve(this.cache.get(artifact));}
return Promise.resolve(this.compute_(artifact)).then(computedArtifact=>{this.cache.set(artifact,computedArtifact);return computedArtifact;});}}
module.exports=ComputedArtifact;},{}],"./computed/critical-request-chains":[function(require,module,exports){'use strict';const ComputedArtifact=require('./computed-artifact');const WebInspector=require('../../lib/web-inspector');const includes=(arr,elm)=>arr.indexOf(elm)>-1;class CriticalRequestChains extends ComputedArtifact{get name(){return'CriticalRequestChains';}
isCritical(request){const resourceTypeCategory=request._resourceType&&request._resourceType._category;if(resourceTypeCategory===WebInspector.resourceTypes.XHR._category){return false;}
if(request.mimeType==='image/x-icon'||(request.parsedURL&&request.parsedURL.lastPathComponent==='favicon.ico')){return false;}
return includes(['VeryHigh','High','Medium'],request.priority());}
compute_(networkRecords){const requestIdToRequests=new Map();for(const request of networkRecords){requestIdToRequests.set(request.requestId,request);}
const criticalRequests=networkRecords.filter(req=>this.isCritical(req));const flattenRequest=request=>{return{url:request._url,startTime:request.startTime,endTime:request.endTime,responseReceivedTime:request.responseReceivedTime,transferSize:request.transferSize};};const criticalRequestChains={};for(const request of criticalRequests){const ancestors=[];let ancestorRequest=request.initiatorRequest();let node=criticalRequestChains;while(ancestorRequest){const ancestorIsCritical=this.isCritical(ancestorRequest);if(!ancestorIsCritical||includes(ancestors,ancestorRequest.requestId)){ancestors.length=0;node=undefined;break;}
ancestors.push(ancestorRequest.requestId);ancestorRequest=ancestorRequest.initiatorRequest();}
let ancestor=ancestors.pop();while(ancestor){const parentRequest=requestIdToRequests.get(ancestor);const parentRequestId=parentRequest.requestId;if(!node[parentRequestId]){node[parentRequestId]={request:flattenRequest(parentRequest),children:{}};}
ancestor=ancestors.pop();node=node[parentRequestId].children;}
if(!node){continue;}
if(node[request.requestId]){continue;}
node[request.requestId]={request:flattenRequest(request),children:{}};}
return criticalRequestChains;}}
module.exports=CriticalRequestChains;},{"../../lib/web-inspector":31,"./computed-artifact":"./computed/computed-artifact"}],"./computed/pushed-requests":[function(require,module,exports){'use strict';const ComputedArtifact=require('./computed-artifact');class PushedRequests extends ComputedArtifact{get name(){return'PushedRequests';}
compute_(records){const pushedRecords=records.filter(r=>r._timing&&!!r._timing.pushStart);return pushedRecords;}}
module.exports=PushedRequests;},{"./computed-artifact":"./computed/computed-artifact"}],"./computed/screenshots":[function(require,module,exports){'use strict';const ComputedArtifact=require('./computed-artifact');const DevtoolsTimelineModel=require('../../lib/traces/devtools-timeline-model');class ScreenshotFilmstrip extends ComputedArtifact{get name(){return'Screenshots';}
fetchScreenshot(frame){return frame.imageDataPromise().then(data=>'data:image/jpg;base64,'+data);}
compute_(trace){const model=new DevtoolsTimelineModel(trace.traceEvents);const filmStripFrames=model.filmStripModel().frames();const frameFetches=filmStripFrames.map(frame=>this.fetchScreenshot(frame));return Promise.all(frameFetches).then(images=>{const result=filmStripFrames.map((frame,i)=>({timestamp:frame.timestamp,datauri:images[i]}));return result;});}}
module.exports=ScreenshotFilmstrip;},{"../../lib/traces/devtools-timeline-model":28,"./computed-artifact":"./computed/computed-artifact"}],"./computed/speedline":[function(require,module,exports){'use strict';const ComputedArtifact=require('./computed-artifact');const speedline=require('speedline');class Speedline extends ComputedArtifact{get name(){return'Speedline';}
compute_(trace){return Promise.resolve().then(_=>{return speedline(trace.traceEvents);}).then(speedlineResults=>{return speedlineResults;});}}
module.exports=Speedline;},{"./computed-artifact":"./computed/computed-artifact","speedline":284}],"./gatherers/accessibility":[function(require,module,exports){(function(Buffer){'use strict';const Gatherer=require('./gatherer');const axe=Buffer(" ","base64");function runA11yChecks(){return axe.run(document,{runOnly:{type:'rule',values:['aria-allowed-attr','aria-required-attr','aria-valid-attr','aria-valid-attr-value','color-contrast','image-alt','label','tabindex']}});}
class Accessibility extends Gatherer{static _errorAccessibility(errorString){return{raw:undefined,value:undefined,debugString:errorString};}
afterPass(options){const driver=options.driver;const expression=`(function () {
      ${axe};
      return (${runA11yChecks.toString()}());
    })()`;return driver.evaluateAsync(expression).then(returnedValue=>{if(!returnedValue){return Accessibility._errorAccessibility('Unable to parse axe results');}
if(returnedValue.error){return Accessibility._errorAccessibility(returnedValue.error);}
return returnedValue;},_=>{return Accessibility._errorAccessibility('Axe results timed out');});}}
module.exports=Accessibility;}).call(this,require("buffer").Buffer)},{"./gatherer":18,"buffer":200}],"./gatherers/cache-contents":[function(require,module,exports){'use strict';const Gatherer=require('./gatherer');function getCacheContents(){return caches.keys().then(cacheNames=>Promise.all(cacheNames.map(cacheName=>caches.open(cacheName)))).then(caches=>{const requests=[];return Promise.all(caches.map(cache=>{return cache.keys().then(reqs=>{requests.push(...reqs.map(r=>r.url));});})).then(_=>{return requests;});});}
class CacheContents extends Gatherer{static _error(errorString){return{raw:undefined,value:undefined,debugString:errorString};}
afterPass(options){const driver=options.driver;return driver.evaluateAsync(`(${getCacheContents.toString()}())`).then(returnedValue=>{if(!returnedValue){return CacheContents._error('Unable to retrieve cache contents');}
return returnedValue;},_=>{return CacheContents._error('Unable to retrieve cache contents');});}}
module.exports=CacheContents;},{"./gatherer":18}],"./gatherers/content-width":[function(require,module,exports){'use strict';const Gatherer=require('./gatherer');function getContentWidth(){return Promise.resolve({scrollWidth:window.innerWidth,viewportWidth:window.outerWidth});}
class ContentWidth extends Gatherer{afterPass(options){const driver=options.driver;return driver.evaluateAsync(`(${getContentWidth.toString()}())`).then(returnedValue=>{if(!Number.isFinite(returnedValue.scrollWidth)||!Number.isFinite(returnedValue.viewportWidth)){throw new Error(`ContentWidth results were not numeric: ${JSON.stringify(returnedValue)}`);}
return returnedValue;},_=>{return{scrollWidth:-1,viewportWidth:-1};});}}
module.exports=ContentWidth;},{"./gatherer":18}],"./gatherers/css-usage":[function(require,module,exports){'use strict';const Gatherer=require('./gatherer');class CSSUsage extends Gatherer{beforePass(options){return options.driver.sendCommand('DOM.enable').then(_=>options.driver.sendCommand('CSS.enable')).then(_=>options.driver.sendCommand('CSS.startRuleUsageTracking'));}
afterPass(options){const driver=options.driver;return driver.sendCommand('CSS.stopRuleUsageTracking').then(results=>{return driver.sendCommand('CSS.disable').then(_=>driver.sendCommand('DOM.disable')).then(_=>results.ruleUsage);}).catch(err=>{return{rawValue:-1,debugString:err,};});}}
module.exports=CSSUsage;},{"./gatherer":18}],"./gatherers/dobetterweb/all-event-listeners":[function(require,module,exports){'use strict';const Gatherer=require('../gatherer');class EventListeners extends Gatherer{listenForScriptParsedEvents(){return this.driver.sendCommand('Debugger.enable').then(_=>{this.driver.on('Debugger.scriptParsed',script=>{this._parsedScripts.set(script.scriptId,script);});});}
unlistenForScriptParsedEvents(){this.driver.off('Debugger.scriptParsed',this.listenForScriptParsedEvents);return this.driver.sendCommand('Debugger.disable');}
_listEventListeners(nodeIdOrObject){let promise;if(typeof nodeIdOrObject==='string'){promise=this.driver.sendCommand('Runtime.evaluate',{expression:nodeIdOrObject,objectGroup:'event-listeners-gatherer'});}else{promise=this.driver.sendCommand('DOM.resolveNode',{nodeId:nodeIdOrObject,objectGroup:'event-listeners-gatherer'});}
return promise.then(result=>{const obj=result.object||result.result;return this.driver.sendCommand('DOMDebugger.getEventListeners',{objectId:obj.objectId}).then(results=>{return{listeners:results.listeners,tagName:obj.description};});});}
getEventListeners(nodeId){const matchedListeners=[];return this._listEventListeners(nodeId).then(results=>{results.listeners.forEach(listener=>{const script=this._parsedScripts.get(listener.scriptId);if(script){const combo=Object.assign(listener,script);combo.objectName=results.tagName;combo.line=combo.lineNumber+1;combo.col=combo.columnNumber+1;matchedListeners.push(combo);}});return matchedListeners;});}
collectListeners(nodes){return nodes.reduce((chain,node)=>{return chain.then(prevArr=>{return this.getEventListeners(node.element?node.element.nodeId:node).then(result=>prevArr.concat(result));});},Promise.resolve([]));}
beforePass(options){this.driver=options.driver;this._parsedScripts=new Map();return this.listenForScriptParsedEvents();}
afterPass(options){return this.unlistenForScriptParsedEvents().then(_=>options.driver.querySelectorAll('body, body /deep/ *')).then(nodes=>{nodes.push('document','window');return this.collectListeners(nodes);}).catch(_=>{return{rawValue:-1,debugString:'Unable to collect passive events listener usage.'};});}}
module.exports=EventListeners;},{"../gatherer":18}],"./gatherers/dobetterweb/anchors-with-no-rel-noopener":[function(require,module,exports){'use strict';const Gatherer=require('../gatherer');class AnchorsWithNoRelNoopener extends Gatherer{afterPass(options){const driver=options.driver;return driver.querySelectorAll('a[target="_blank"]:not([rel~="noopener"])').then(failingNodeList=>{const failingNodes=failingNodeList.map(node=>{return Promise.all([node.getProperty('href'),node.getAttribute('rel'),node.getAttribute('target')]);});return Promise.all(failingNodes);}).then(failingNodes=>{return{usages:failingNodes.map(node=>{return{href:node[0],rel:node[1],target:node[2]};})};}).catch(_=>{return-1;});}}
module.exports=AnchorsWithNoRelNoopener;},{"../gatherer":18}],"./gatherers/dobetterweb/appcache":[function(require,module,exports){'use strict';const Gatherer=require('../gatherer');class AppCacheManifest extends Gatherer{afterPass(options){const driver=options.driver;return driver.querySelector('html').then(node=>node&&node.getAttribute('manifest')).catch(_=>{return-1;});}}
module.exports=AppCacheManifest;},{"../gatherer":18}],"./gatherers/dobetterweb/console-time-usage":[function(require,module,exports){'use strict';const Gatherer=require('../gatherer');class ConsoleTimeUsage extends Gatherer{beforePass(options){this.collectUsage=options.driver.captureFunctionCallSites('console.time');}
afterPass(){return this.collectUsage().then(consoleTimeUsage=>{return{usage:consoleTimeUsage};},e=>{return{value:-1,debugString:e.message};});}}
module.exports=ConsoleTimeUsage;},{"../gatherer":18}],"./gatherers/dobetterweb/datenow":[function(require,module,exports){'use strict';const Gatherer=require('../gatherer');class DateNowUse extends Gatherer{beforePass(options){this.collectUsage=options.driver.captureFunctionCallSites('Date.now');}
afterPass(){return this.collectUsage().then(dateNowUses=>{return{usage:dateNowUses};},e=>{return{value:-1,debugString:e.message};});}}
module.exports=DateNowUse;},{"../gatherer":18}],"./gatherers/dobetterweb/document-write":[function(require,module,exports){'use strict';const Gatherer=require('../gatherer');class DocWriteUse extends Gatherer{beforePass(options){this.collectUsage=options.driver.captureFunctionCallSites('document.write');}
afterPass(){return this.collectUsage().then(DocWriteUses=>{return{usage:DocWriteUses};},e=>{return{value:-1,debugString:e.message};});}}
module.exports=DocWriteUse;},{"../gatherer":18}],"./gatherers/dobetterweb/geolocation-on-start":[function(require,module,exports){'use strict';const Gatherer=require('../gatherer');class GeolocationOnStart extends Gatherer{beforePass(options){this.collectCurrentPosUsage=options.driver.captureFunctionCallSites('navigator.geolocation.getCurrentPosition');this.collectWatchPosUsage=options.driver.captureFunctionCallSites('navigator.geolocation.watchPosition');}
afterPass(options){return options.driver.queryPermissionState('geolocation').then(state=>{if(state==='granted'||state==='denied'){return{value:-1,debugString:'Unable to determine if this permission was requested '+'on page load because it had already been set. '+'Try resetting the permission and run Lighthouse again.'};}
return this.collectCurrentPosUsage().then(results=>{return this.collectWatchPosUsage().then(results2=>results.concat(results2));}).then(results=>{return{usage:results};});}).catch(e=>{return{value:-1,debugString:e&&e.message};});}}
module.exports=GeolocationOnStart;},{"../gatherer":18}],"./gatherers/dobetterweb/notification-on-start":[function(require,module,exports){'use strict';const Gatherer=require('../gatherer');class NotificationOnStart extends Gatherer{beforePass(options){this.collectNotificationUsage=options.driver.captureFunctionCallSites('Notification.requestPermission');}
afterPass(options){return options.driver.queryPermissionState('notifications').then(state=>{if(state==='granted'||state==='denied'){return{value:-1,debugString:'Unable to determine if this permission was requested '+'on page load because it had already been set. '+'Try resetting the permission and run Lighthouse again.'};}
return this.collectNotificationUsage().then(results=>{return{usage:results};});}).catch(e=>{return{value:-1,debugString:e&&e.message};});}}
module.exports=NotificationOnStart;},{"../gatherer":18}],"./gatherers/dobetterweb/tags-blocking-first-paint":[function(require,module,exports){'use strict';const Gatherer=require('../gatherer');function saveAsyncLinks(){function checkForLinks(){document.querySelectorAll('link').forEach(link=>{if(link.rel==='preload'||link.disabled){window.__asyncLinks[link.href]=true;}});}
window.__asyncLinks=window.__asyncLinks||{};setInterval(checkForLinks,100);checkForLinks();}
function collectTagsThatBlockFirstPaint(){return new Promise((resolve,reject)=>{try{const tagList=[...document.querySelectorAll('link, head script[src]')].filter(tag=>{if(tag.tagName==='SCRIPT'){return!tag.hasAttribute('async')&&!tag.hasAttribute('defer')&&!/^data:/.test(tag.src);}
const blockingStylesheet=(tag.rel==='stylesheet'&&window.matchMedia(tag.media).matches&&!tag.disabled);const blockingImport=tag.rel==='import'&&!tag.hasAttribute('async');return blockingStylesheet||blockingImport;}).map(tag=>{return{tagName:tag.tagName,url:tag.tagName==='LINK'?tag.href:tag.src,src:tag.src,href:tag.href,rel:tag.rel,media:tag.media,disabled:tag.disabled};}).filter(tag=>!window.__asyncLinks[tag.url]);resolve(tagList);}catch(e){const friendly='Unable to gather Scripts/Stylesheets/HTML Imports on the page';reject(new Error(`${friendly}: ${e.message}`));}});}
function filteredAndIndexedByUrl(networkRecords){return networkRecords.reduce((prev,record)=>{const isParserGenerated=record._initiator.type==='parser';const isParserScriptOrStyle=/(css|script)/.test(record._mimeType)&&isParserGenerated;const isFailedRequest=record._failed;const isHtml=record._mimeType&&record._mimeType.indexOf('html')>-1;if(isHtml||isParserScriptOrStyle||(isFailedRequest&&isParserGenerated)){prev[record._url]={transferSize:record._transferSize,startTime:record._startTime,endTime:record._endTime};}
return prev;},{});}
class TagsBlockingFirstPaint extends Gatherer{constructor(){super();this._filteredAndIndexedByUrl=filteredAndIndexedByUrl;}
static findBlockingTags(driver,networkRecords){const scriptSrc=`(${collectTagsThatBlockFirstPaint.toString()}())`;return driver.evaluateAsync(scriptSrc).then(tags=>{const requests=filteredAndIndexedByUrl(networkRecords);let totalTransferSize=0;let totalSpendTime=0;const blockingTags=tags.reduce((prev,tag)=>{const request=requests[tag.url];if(request){const data={tag,transferSize:request.transferSize,spendTime:Math.round((request.endTime-request.startTime)*1000)};totalTransferSize+=data.transferSize;totalSpendTime+=data.spendTime;prev.push(data);}
return prev;},[]);return{items:blockingTags,total:{transferSize:totalTransferSize,spendTime:totalSpendTime}};});}
beforePass(options){const scriptSrc=`(${saveAsyncLinks.toString()})()`;return options.driver.evaluateScriptOnLoad(scriptSrc);}
afterPass(options,tracingData){return TagsBlockingFirstPaint.findBlockingTags(options.driver,tracingData.networkRecords).catch(err=>{return{value:-1,debugString:err.message};});}}
module.exports=TagsBlockingFirstPaint;},{"../gatherer":18}],"./gatherers/dobetterweb/websql":[function(require,module,exports){'use strict';const Gatherer=require('../gatherer');const MAX_WAIT_TIMEOUT=500;class WebSQL extends Gatherer{listenForDatabaseEvents(driver){let timeout;return new Promise((resolve,reject)=>{driver.once('Database.addDatabase',db=>{clearTimeout(timeout);driver.sendCommand('Database.disable').then(_=>resolve(db),reject);});driver.sendCommand('Database.enable').catch(reject);timeout=setTimeout(function(){resolve(null);},MAX_WAIT_TIMEOUT);});}
afterPass(options){return this.listenForDatabaseEvents(options.driver).then(database=>{const artifact={database};if(!database){artifact.debugString='No WebSQL databases were opened';}
return artifact;}).catch(_=>{return{database:-1,debugString:'Unable to gather WebSQL database state'};});}}
module.exports=WebSQL;},{"../gatherer":18}],"./gatherers/html-without-javascript":[function(require,module,exports){'use strict';const Gatherer=require('./gatherer');function getBodyText(){const body=document.querySelector('body');return Promise.resolve(body?body.innerText:'');}
class HTMLWithoutJavaScript extends Gatherer{beforePass(options){options.disableJavaScript=true;}
afterPass(options){options.disableJavaScript=false;return options.driver.evaluateAsync(`(${getBodyText.toString()}())`).then(result=>{if(typeof result!=='string'){throw new Error('result was not a string');}
return{value:result};}).catch(err=>{return{value:-1,debugString:`Unable to get document body innerText: ${err.message}`};});}}
module.exports=HTMLWithoutJavaScript;},{"./gatherer":18}],"./gatherers/html":[function(require,module,exports){'use strict';const Gatherer=require('./gatherer');class HTML extends Gatherer{afterPass(options){const driver=options.driver;return driver.sendCommand('DOM.getDocument').then(result=>result.root.nodeId).then(nodeId=>driver.sendCommand('DOM.getOuterHTML',{nodeId:nodeId})).then(nodeHTML=>{return nodeHTML.outerHTML;}).catch(_=>{return{value:-1,debugString:'Unable to get document HTML'};});}}
module.exports=HTML;},{"./gatherer":18}],"./gatherers/http-redirect":[function(require,module,exports){'use strict';const Gatherer=require('./gatherer');class HTTPRedirect extends Gatherer{constructor(){super();this._preRedirectURL=undefined;}
beforePass(options){this._preRedirectURL=options.url;options.url=this._preRedirectURL.replace(/^https/,'http');}
afterPass(options){options.url=this._preRedirectURL;const timeout=options._testTimeout||10000;const securityPromise=options.driver.getSecurityState().then(state=>{return{value:state.schemeIsCryptographic};},_=>{return{value:false,debugString:'Error requesting security state'};});let noSecurityChangesTimeout;const timeoutPromise=new Promise((resolve,reject)=>{noSecurityChangesTimeout=setTimeout(_=>{resolve({value:false,debugString:'Timed out waiting for HTTP redirection.'});},timeout);});return Promise.race([securityPromise,timeoutPromise]).then(result=>{clearTimeout(noSecurityChangesTimeout);return result;});}}
module.exports=HTTPRedirect;},{"./gatherer":18}],"./gatherers/https":[function(require,module,exports){'use strict';const Gatherer=require('./gatherer');class HTTPS extends Gatherer{constructor(){super();this._noSecurityChangesTimeout=undefined;}
afterPass(options){const timeout=options._testTimeout||10000;const securityPromise=options.driver.getSecurityState().then(state=>{return{value:state.schemeIsCryptographic};},_=>{return{value:false,debugString:'Error requesting page security state.'};});let noSecurityChangesTimeout;const timeoutPromise=new Promise((resolve,reject)=>{noSecurityChangesTimeout=setTimeout(_=>{resolve({value:false,debugString:'Timed out waiting for page security state.'});},timeout);});return Promise.race([securityPromise,timeoutPromise]).then(result=>{clearTimeout(noSecurityChangesTimeout);return result;});}}
module.exports=HTTPS;},{"./gatherer":18}],"./gatherers/manifest":[function(require,module,exports){'use strict';const Gatherer=require('./gatherer');const manifestParser=require('../../lib/manifest-parser');class Manifest extends Gatherer{static _errorManifest(errorString){return{raw:undefined,value:undefined,debugString:errorString};}
afterPass(options){return options.driver.sendCommand('Page.getAppManifest').then(response=>{if(!response.data){let errorString;if(response.url){errorString=`Unable to retrieve manifest at ${response.url}`;}else{errorString='No manifest found.';}
return Manifest._errorManifest(errorString);}
return manifestParser(response.data,response.url,options.url);},err=>{return Manifest._errorManifest('Unable to retrieve manifest: '+err);});}}
module.exports=Manifest;},{"../../lib/manifest-parser":25,"./gatherer":18}],"./gatherers/offline":[function(require,module,exports){'use strict';const Gatherer=require('./gatherer');class Offline extends Gatherer{beforePass(options){return options.driver.goOffline();}
afterPass(options,tracingData){const navigationRecord=tracingData.networkRecords.filter(record=>{return record._url===options.url&&record._fetchedViaServiceWorker;}).pop();return options.driver.goOnline(options).then(_=>{return navigationRecord?navigationRecord.statusCode:-1;});}}
module.exports=Offline;},{"./gatherer":18}],"./gatherers/service-worker":[function(require,module,exports){'use strict';const Gatherer=require('./gatherer');class ServiceWorker extends Gatherer{beforePass(options){const driver=options.driver;return driver.getServiceWorkerVersions().then(data=>{return{versions:data.versions};}).catch(err=>{return{debugString:`Error in querying Service Worker status: ${err.message}`};});}}
module.exports=ServiceWorker;},{"./gatherer":18}],"./gatherers/styles":[function(require,module,exports){'use strict';const WebInspector=require('../../lib/web-inspector');const Gatherer=require('./gatherer');const log=require('../../lib/log.js');function getCSSPropsInStyleSheet(parseTree){const results=[];parseTree.traverseByType('declaration',function(node,index,parent){if(parent.type==='arguments'){return;}
const keyVal=node.toString().split(':').map(item=>item.trim());results.push({property:{name:keyVal[0],val:keyVal[1]},declarationRange:node.declarationRange,selector:parent.selectors.toString()});});return results;}
class Styles extends Gatherer{constructor(){super();this._activeStyleSheetIds=[];this._activeStyleHeaders={};this._onStyleSheetAdded=this.onStyleSheetAdded.bind(this);this._onStyleSheetRemoved=this.onStyleSheetRemoved.bind(this);}
onStyleSheetAdded(styleHeader){if(styleHeader.header.origin!=='regular'){return;}
this._activeStyleHeaders[styleHeader.header.styleSheetId]=styleHeader;this._activeStyleSheetIds.push(styleHeader.header.styleSheetId);}
onStyleSheetRemoved(styleHeader){delete this._activeStyleHeaders[styleHeader.styleSheetId];const idx=this._activeStyleSheetIds.indexOf(styleHeader.styleSheetId);if(idx!==-1){this._activeStyleSheetIds.splice(idx,1);}}
beginStylesCollect(driver){driver.on('CSS.styleSheetAdded',this._onStyleSheetAdded);driver.on('CSS.styleSheetRemoved',this._onStyleSheetRemoved);return driver.sendCommand('DOM.enable').then(_=>driver.sendCommand('CSS.enable'));}
endStylesCollect(driver){return new Promise((resolve,reject)=>{if(!this._activeStyleSheetIds.length){resolve([]);return;}
const parser=new WebInspector.SCSSParser();const contentPromises=this._activeStyleSheetIds.map(sheetId=>{return driver.sendCommand('CSS.getStyleSheetText',{styleSheetId:sheetId}).then(content=>{const styleHeader=this._activeStyleHeaders[sheetId];styleHeader.content=content.text;const parsedContent=parser.parse(styleHeader.content);if(parsedContent.error){log.warn('Styles Gatherer',`Could not parse content: ${parsedContent.error}`);styleHeader.parsedContent=[];}else{styleHeader.parsedContent=getCSSPropsInStyleSheet(parsedContent);}
return styleHeader;});});Promise.all(contentPromises).then(styleHeaders=>{driver.off('CSS.styleSheetAdded',this._onStyleSheetAdded);driver.off('CSS.styleSheetRemoved',this._onStyleSheetRemoved);resolve(styleHeaders);}).catch(err=>reject(err));});}
beforePass(options){return this.beginStylesCollect(options.driver);}
afterPass(options){return this.endStylesCollect(options.driver).then(stylesheets=>{const map=new Map(stylesheets.map(s=>[s.content,s]));return stylesheets.map(stylesheet=>{const idInMap=map.get(stylesheet.content).header.styleSheetId;stylesheet.isDuplicate=idInMap!==stylesheet.header.styleSheetId;return stylesheet;});},err=>{return{rawValue:-1,debugString:err};});}}
module.exports=Styles;},{"../../lib/log.js":24,"../../lib/web-inspector":31,"./gatherer":18}],"./gatherers/theme-color":[function(require,module,exports){'use strict';const Gatherer=require('./gatherer');class ThemeColor extends Gatherer{afterPass(options){const driver=options.driver;return driver.querySelector('head meta[name="theme-color"]').then(node=>node&&node.getAttribute('content')).catch(_=>{return-1;});}}
module.exports=ThemeColor;},{"./gatherer":18}],"./gatherers/url":[function(require,module,exports){'use strict';const Gatherer=require('./gatherer');class URL extends Gatherer{afterPass(options){return{initialUrl:options.initialUrl,finalUrl:options.url};}}
module.exports=URL;},{"./gatherer":18}],"./gatherers/viewport":[function(require,module,exports){'use strict';const Gatherer=require('./gatherer');class Viewport extends Gatherer{afterPass(options){const driver=options.driver;return driver.querySelector('head meta[name="viewport"]').then(node=>node&&node.getAttribute('content')).catch(_=>{return-1;});}}
module.exports=Viewport;},{"./gatherer":18}],1:[function(require,module,exports){'use strict';class Aggregate{static _filterResultsByAuditNames(results,expected){const expectedNames=Object.keys(expected);return results.filter(r=>expectedNames.indexOf((r.name))!==-1);}
static _getTotalWeight(expected){const expectedNames=Object.keys(expected);const totalWeight=expectedNames.reduce((last,e)=>last+(expected[e].weight||0),0);return totalWeight;}
static _remapResultsByName(results){const remapped={};results.forEach(r=>{if(remapped[r.name]){throw new Error(`Cannot remap: ${r.name} already exists`);}
remapped[r.name]=r;});return remapped;}
static _convertToWeight(result,expected,name){let weight=0;if(typeof expected==='undefined'||typeof expected.expectedValue==='undefined'||typeof expected.weight==='undefined'){const msg=`aggregations: ${name} audit does not contain expectedValue or weight properties`;throw new Error(msg);}
if(typeof result==='undefined'||typeof result.score==='undefined'){let msg=`${name} audit result is undefined or does not contain score property`;if(result&&result.debugString){msg+=': '+result.debugString;}
throw new Error(msg);}
if(typeof result.score!==typeof expected.expectedValue){const expectedType=typeof expected.expectedValue;const resultType=typeof result.rawValue;let msg=`Expected expectedValue of type ${expectedType}, got ${resultType}`;if(result.debugString){msg+=': '+result.debugString;}
throw new Error(msg);}
switch(typeof expected.expectedValue){case'boolean':weight=this._convertBooleanToWeight(result.score,expected.expectedValue,expected.weight);break;case'number':weight=this._convertNumberToWeight(result.score,expected.expectedValue,expected.weight);break;default:weight=0;break;}
return weight;}
static _convertNumberToWeight(resultValue,expectedValue,weight){return(resultValue/expectedValue)*weight;}
static _convertBooleanToWeight(resultValue,expectedValue,weight){return(resultValue===expectedValue)?weight:0;}
static compare(results,items,aggregationIsScored){return items.map(item=>{const expectedNames=Object.keys(item.audits);const filteredAndRemappedResults=Aggregate._remapResultsByName(Aggregate._filterResultsByAuditNames(results,item.audits));const subItems=[];let overallScore=0;let maxScore=1;expectedNames.forEach(e=>{if(item.audits[e].comingSoon){subItems.push({score:'¯\\_(ツ)_/¯',name:'coming-soon',category:item.audits[e].category,description:item.audits[e].description,comingSoon:true});return;}
if(!filteredAndRemappedResults[e]){throw new Error(`aggregations: expected audit results not found under audit name ${e}`);}
subItems.push(filteredAndRemappedResults[e].name);if(!aggregationIsScored){return;}
overallScore+=Aggregate._convertToWeight(filteredAndRemappedResults[e],item.audits[e],e);});if(aggregationIsScored){maxScore=Aggregate._getTotalWeight(item.audits);}
return{overall:(overallScore/maxScore),name:item.name,description:item.description,subItems:subItems};});}
static getTotal(scores){return scores.reduce((total,s)=>total+s.overall,0)/scores.length;}
static aggregate(aggregation,auditResults){const score=Aggregate.compare(auditResults,aggregation.items,aggregation.scored);return{name:aggregation.name,description:aggregation.description,scored:aggregation.scored,total:(aggregation.scored?Aggregate.getTotal(score):null),categorizable:aggregation.categorizable,score:score};}}
module.exports=Aggregate;},{}],2:[function(require,module,exports){'use strict';const Audit=require('../audit');const Formatter=require('../../formatters/formatter');class AxeAudit extends Audit{static audit(artifacts){const violations=artifacts.Accessibility.violations||[];const rule=violations.find(result=>result.id===this.meta.name);return this.generateAuditResult({rawValue:typeof rule==='undefined',debugString:this.createDebugString(rule),extendedInfo:{formatter:Formatter.SUPPORTED_FORMATS.ACCESSIBILITY,value:rule}});}
static createDebugString(rule){if(typeof rule==='undefined'){return'';}
const elementsStr=rule.nodes.length===1?'element':'elements';return`${rule.help} (Failed on ${rule.nodes.length} ${elementsStr})`;}}
module.exports=AxeAudit;},{"../../formatters/formatter":8,"../audit":3}],3:[function(require,module,exports){'use strict';const DEFAULT_PASS='defaultPass';class Audit{static get DEFAULT_PASS(){return DEFAULT_PASS;}
static get meta(){throw new Error('Audit meta information must be overridden.');}
static generateAuditResult(result){if(typeof result.rawValue==='undefined'){throw new Error('generateAuditResult requires a rawValue');}
const score=typeof result.score==='undefined'?result.rawValue:result.score;let displayValue=result.displayValue;if(typeof displayValue==='undefined'){displayValue=result.rawValue?result.rawValue:'';}
if(displayValue===score){displayValue='';}
return{score,displayValue:`${displayValue}`,rawValue:result.rawValue,debugString:result.debugString,optimalValue:result.optimalValue,extendedInfo:result.extendedInfo,name:this.meta.name,category:this.meta.category,description:this.meta.description,helpText:this.meta.helpText};}}
module.exports=Audit;},{}],4:[function(require,module,exports){(function(__dirname){'use strict';const defaultConfigPath='./default.json';const defaultConfig=require('./default.json');const recordsFromLogs=require('../lib/network-recorder').recordsFromLogs;const GatherRunner=require('../gather/gather-runner');const log=require('../lib/log');const path=require('path');const Audit=require('../audits/audit');const Runner=require('../runner');const _flatten=arr=>[].concat(...arr);const _uniq=arr=>Array.from(new Set(arr));function cleanTrace(trace){const traceEvents=trace.traceEvents;const threads=[];const countsByThread={};const traceStartEvents=[];const makeMockEvent=(evt,ts)=>{return{pid:evt.pid,tid:evt.tid,ts:ts||0,ph:'I',cat:'disabled-by-default-devtools.timeline',name:'TracingStartedInPage',args:{data:{page:evt.frame}},s:'t'};};let frame;let data;let name;let counter;traceEvents.forEach((evt,idx)=>{if(evt.name.startsWith('TracingStartedIn')){traceStartEvents.push(idx);}
data=evt.args&&(evt.args.data||evt.args.beginData||evt.args.counters);frame=(evt.args&&evt.args.frame)||data&&(data.frame||data.page);if(!frame){return;}
name=`pid${evt.pid}-tid${evt.tid}-frame${frame}`;counter=countsByThread[name];if(!counter){counter={pid:evt.pid,tid:evt.tid,frame:frame,count:0};countsByThread[name]=counter;threads.push(counter);}
counter.count++;});threads.sort((a,b)=>b.count-a.count);const mostActiveFrame=threads[0];const ts=traceEvents[traceStartEvents[0]]&&traceEvents[traceStartEvents[0]].ts;let i=0;for(const dup of traceStartEvents){traceEvents.splice(dup-i,1);i++;}
traceEvents.unshift(makeMockEvent(mostActiveFrame,ts));return trace;}
function validatePasses(passes,audits,rootPath){if(!Array.isArray(passes)){return;}
const requiredGatherers=Config.getGatherersNeededByAudits(audits);passes.forEach(pass=>{pass.gatherers.forEach(gatherer=>{const GathererClass=GatherRunner.getGathererClass(gatherer,rootPath);const isGatherRequiredByAudits=requiredGatherers.has(GathererClass.name);if(isGatherRequiredByAudits===false){const msg=`${GathererClass.name} gatherer requested, however no audit requires it.`;log.warn('config',msg);}});});const usedNames=new Set();passes.forEach((pass,index)=>{if(!pass.recordNetwork&&!pass.recordTrace){return;}
const passName=pass.passName||Audit.DEFAULT_PASS;if(usedNames.has(passName)){log.warn('config',`passes[${index}] may overwrite trace or network `+`data of earlier pass without a unique passName (repeated name: ${passName}.`);}
usedNames.add(passName);});}
function assertValidAudit(auditDefinition,auditPath){const auditName=auditPath||auditDefinition.meta.name;if(typeof auditDefinition.audit!=='function'){throw new Error(`${auditName} has no audit() method.`);}
if(typeof auditDefinition.meta.name!=='string'){throw new Error(`${auditName} has no meta.name property, or the property is not a string.`);}
if(typeof auditDefinition.meta.category!=='string'){throw new Error(`${auditName} has no meta.category property, or the property is not a string.`);}
if(typeof auditDefinition.meta.description!=='string'){throw new Error(`${auditName} has no meta.description property, or the property is not a string.`);}
if(!Array.isArray(auditDefinition.meta.requiredArtifacts)){throw new Error(`${auditName} has no meta.requiredArtifacts property, or the property is not an array.`);}
if(typeof auditDefinition.generateAuditResult!=='function'){throw new Error(`${auditName} has no generateAuditResult() method. `+'Did you inherit from the proper base class?');}}
function expandArtifacts(artifacts){if(!artifacts){return null;}
if(artifacts.traces){Object.keys(artifacts.traces).forEach(key=>{log.log('info','Normalizng trace contents into expected state...');let trace=require(artifacts.traces[key]);if(Array.isArray(trace)){trace={traceEvents:trace};}
trace=cleanTrace(trace);artifacts.traces[key]=trace;});}
if(artifacts.performanceLog){if(typeof artifacts.performanceLog==='string'){const log=require(artifacts.performanceLog);artifacts.networkRecords={[Audit.DEFAULT_PASS]:recordsFromLogs(log)};}else{artifacts.networkRecords={};Object.keys(artifacts.performanceLog).forEach(key=>{const log=require(artifacts.performanceLog[key]);artifacts.networkRecords[key]=recordsFromLogs(log);});}}
return artifacts;}
class Config{constructor(configJSON,configPath){if(!configJSON){configJSON=defaultConfig;configPath=path.resolve(__dirname,defaultConfigPath);}
if(configPath&&!path.isAbsolute(configPath)){throw new Error('configPath must be an absolute path.');}
const inputConfig=configJSON;configJSON=JSON.parse(JSON.stringify(inputConfig));if(Array.isArray(inputConfig.passes)){configJSON.passes.forEach((pass,i)=>{pass.gatherers=Array.from(inputConfig.passes[i].gatherers);});}
if(Array.isArray(inputConfig.audits)){configJSON.audits=Array.from(inputConfig.audits);}
this._configDir=configPath?path.dirname(configPath):undefined;this._passes=configJSON.passes||null;this._auditResults=configJSON.auditResults||null;if(this._auditResults&&!Array.isArray(this._auditResults)){throw new Error('config.auditResults must be an array');}
this._aggregations=configJSON.aggregations||null;this._audits=Config.requireAudits(configJSON.audits,this._configDir);this._artifacts=expandArtifacts(configJSON.artifacts);validatePasses(configJSON.passes,this._audits,this._configDir);}
static getMapOfAuditPathToName(config){const auditObjectsAll=Config.requireAudits(config.audits);const auditPathToName=new Map(auditObjectsAll.map((AuditClass,index)=>{const auditPath=config.audits[index];const auditName=AuditClass.meta.name;return[auditPath,auditName];}));return auditPathToName;}
static getAuditsNeededByAggregations(aggregations){const requestedItems=_flatten(aggregations.map(aggregation=>aggregation.items));const requestedAudits=_flatten(requestedItems.map(item=>Object.keys(item.audits)));return new Set(requestedAudits);}
static getGatherersNeededByAudits(audits){if(!audits){return new Set();}
return audits.reduce((list,audit)=>{audit.meta.requiredArtifacts.forEach(artifact=>list.add(artifact));return list;},new Set());}
static selectPassesNeededByGatherers(passes,requiredGatherers){const filteredPasses=passes.map(pass=>{pass.gatherers=pass.gatherers.filter(gathererName=>{gathererName=GatherRunner.getGathererClass(gathererName).name;return requiredGatherers.has(gathererName);});return pass;}).filter(pass=>pass.gatherers.length>0);if(filteredPasses.length===0){if(requiredGatherers.has('traces')||requiredGatherers.has('networkRecords')){filteredPasses.push({recordNetwork:requiredGatherers.has('networkRecords'),recordTrace:requiredGatherers.has('traces'),gatherers:[]});}}
return filteredPasses;}
static getAggregationsByTags(aggregations,chosenTags){const isAggregationSelected=agg=>agg.tags.some(itemTag=>chosenTags.includes(itemTag));const chosenAggregations=[];aggregations.forEach(aggregation=>{if(aggregation.items.length===1){if(isAggregationSelected(aggregation)){chosenAggregations.push(aggregation);}
return;}
aggregation.items=aggregation.items.filter(isAggregationSelected);if(aggregation.items.length&&!isAggregationSelected(aggregation)){aggregation.items.forEach(item=>{item.scored=false;item.categorizable=false;item.items=[{audits:item.audits}];delete item.audits;chosenAggregations.push(item);});return;};if(aggregation.items.length===0){return;}
chosenAggregations.push(aggregation);});return chosenAggregations;}
static rebuildConfigFromTags(config,chosenTags){config.aggregations=Config.getAggregationsByTags(config.aggregations,chosenTags);const requestedAuditNames=Config.getAuditsNeededByAggregations(config.aggregations);const auditPathToName=Config.getMapOfAuditPathToName(config);config.audits=config.audits.filter(auditPath=>requestedAuditNames.has(auditPathToName.get(auditPath)));const auditObjectsSelected=Config.requireAudits(config.audits);const requiredGatherers=Config.getGatherersNeededByAudits(auditObjectsSelected);config.passes=Config.selectPassesNeededByGatherers(config.passes,requiredGatherers);}
static requireAudits(audits,configPath){if(!audits){return null;}
const coreList=Runner.getAuditList();return audits.map(pathOrAuditClass=>{let AuditClass;if(typeof pathOrAuditClass==='string'){const path=pathOrAuditClass;const coreAudit=coreList.find(a=>a===`${path}.js`);let requirePath=`../audits/${path}`;if(!coreAudit){requirePath=Runner.resolvePlugin(path,configPath,'audit');}
AuditClass=require(requirePath);assertValidAudit(AuditClass,path);}else{AuditClass=pathOrAuditClass;assertValidAudit(AuditClass);}
return AuditClass;});}
get configDir(){return this._configDir;}
get passes(){return this._passes;}
get audits(){return this._audits;}
get auditResults(){return this._auditResults;}
get artifacts(){return this._artifacts;}
get aggregations(){return this._aggregations;}}
module.exports=Config;}).call(this,"/../lighthouse-core/config")},{"../audits/audit":3,"../gather/gather-runner":17,"../lib/log":24,"../lib/network-recorder":26,"../runner":33,"./default.json":5,"path":204}],5:[function(require,module,exports){module.exports={"passes":[{"recordNetwork":true,"recordTrace":true,"gatherers":["url","https","viewport","theme-color","manifest","accessibility","content-width"]},{"passName":"offlinePass","recordNetwork":true,"gatherers":["service-worker","offline"]},{"gatherers":["http-redirect","html-without-javascript"]},{"recordNetwork":true,"passName":"dbw","gatherers":["styles","css-usage","dobetterweb/all-event-listeners","dobetterweb/anchors-with-no-rel-noopener","dobetterweb/appcache","dobetterweb/console-time-usage","dobetterweb/datenow","dobetterweb/document-write","dobetterweb/geolocation-on-start","dobetterweb/notification-on-start","dobetterweb/tags-blocking-first-paint","dobetterweb/websql"]}],"audits":["is-on-https","redirects-http","service-worker","works-offline","viewport","manifest-display","without-javascript","first-meaningful-paint","speed-index-metric","estimated-input-latency","time-to-interactive","user-timings","critical-request-chains","manifest-exists","manifest-background-color","manifest-theme-color","manifest-icons-min-192","manifest-icons-min-144","manifest-name","manifest-short-name","manifest-short-name-length","manifest-start-url","theme-color-meta","unused-css-rules","content-width","accessibility/aria-allowed-attr","accessibility/aria-required-attr","accessibility/aria-valid-attr-value","accessibility/aria-valid-attr","accessibility/color-contrast","accessibility/image-alt","accessibility/label","accessibility/tabindex","dobetterweb/external-anchors-use-rel-noopener","dobetterweb/appcache-manifest","dobetterweb/geolocation-on-start","dobetterweb/link-blocking-first-paint","dobetterweb/no-console-time","dobetterweb/no-datenow","dobetterweb/no-document-write","dobetterweb/no-mutation-events","dobetterweb/no-old-flexbox","dobetterweb/no-websql","dobetterweb/notification-on-start","dobetterweb/script-blocking-first-paint","dobetterweb/uses-http2","dobetterweb/uses-passive-event-listeners"],"aggregations":[{"name":"Progressive Web App","description":"These audits validate the aspects of a Progressive Web App.","id":"pwa_parent","tags":["pwa"],"scored":true,"categorizable":true,"items":[{"name":"App can load on offline/flaky connections","description":"Ensuring your web app can respond when the network connection is unavailable or flaky is critical to providing your users a good experience. This is achieved through use of a [Service Worker](https://developers.google.com/web/fundamentals/primers/service-worker/).","tags":["pwa"],"audits":{"service-worker":{"expectedValue":true,"weight":1},"works-offline":{"expectedValue":true,"weight":1}}},{"name":"Page load performance is fast","description":"Users notice if sites and apps don't perform well. These top-level metrics capture the most important perceived performance concerns.","id":"perf_metrics","tags":["pwa","perf"],"audits":{"first-meaningful-paint":{"expectedValue":100,"weight":1},"speed-index-metric":{"expectedValue":100,"weight":1},"estimated-input-latency":{"expectedValue":100,"weight":1},"time-to-interactive":{"expectedValue":100,"weight":1},"scrolling-60fps":{"expectedValue":true,"weight":0,"comingSoon":true,"description":"Content scrolls at 60fps","category":"UX"},"touch-150ms":{"expectedValue":true,"weight":0,"comingSoon":true,"description":"Touch input gets a response in < 150ms","category":"UX"},"fmp-no-jank":{"expectedValue":true,"weight":0,"comingSoon":true,"description":"App is interactive without jank after the first meaningful paint","category":"UX"}}},{"name":"Site is progressively enhanced","description":"Progressive enhancement means that everyone can access the basic content and functionality of a page in any browser, and those without certain browser features may receive a reduced but still functional experience.","id":"progressive_enhancement","tags":["pwa"],"audits":{"without-javascript":{"expectedValue":true,"weight":1}}},{"name":"Network connection is secure","description":"Security is an important part of the web for both developers and users. Moving forward, Transport Layer Security (TLS) support will be required for many APIs.","id":"network_security","tags":["pwa"],"audits":{"is-on-https":{"expectedValue":true,"weight":1},"redirects-http":{"expectedValue":true,"weight":1}}},{"name":"User can be prompted to Add to Homescreen","description":"While users can manually add your site to their homescreen in the browser menu, the [prompt (aka app install banner)](https://developers.google.com/web/updates/2015/03/increasing-engagement-with-app-install-banners-in-chrome-for-android) will proactively prompt the user to install the app if the below requirements are met and the user has visited your site at least twice (with at least five minutes between visits).","tags":["pwa"],"id":"a2hs","see":"https://github.com/GoogleChrome/lighthouse/issues/23","audits":{"service-worker":{"expectedValue":true,"weight":1},"manifest-exists":{"expectedValue":true,"weight":1},"manifest-start-url":{"expectedValue":true,"weight":1},"manifest-icons-min-144":{"expectedValue":true,"weight":1},"manifest-short-name":{"expectedValue":true,"weight":1}}},{"name":"Installed web app will launch with custom splash screen","description":"A default splash screen will be constructed, but meeting these requirements guarantee a high-quality and customizable [splash screen](https://developers.google.com/web/updates/2015/10/splashscreen) the user sees between tapping the home screen icon and your app's first paint.","tags":["pwa"],"id":"splash_screen","see":"https://github.com/GoogleChrome/lighthouse/issues/24","audits":{"manifest-exists":{"expectedValue":true,"weight":1},"manifest-name":{"expectedValue":true,"weight":1},"manifest-background-color":{"expectedValue":true,"weight":1},"manifest-theme-color":{"expectedValue":true,"weight":1},"manifest-icons-min-192":{"expectedValue":true,"weight":1}}},{"name":"Address bar matches brand colors","description":"The browser address bar can be themed to match your site. A `theme-color` [meta tag](https://developers.google.com/web/updates/2014/11/Support-for-theme-color-in-Chrome-39-for-Android) will upgrade the address bar when a user browses the site, and the [manifest theme-color](https://developers.google.com/web/updates/2015/08/using-manifest-to-set-sitewide-theme-color) will apply the same theme site-wide once it's been added to homescreen.","tags":["pwa"],"id":"omnibox","audits":{"manifest-exists":{"expectedValue":true,"weight":1},"theme-color-meta":{"expectedValue":true,"weight":1},"manifest-theme-color":{"expectedValue":true,"weight":1}}},{"name":"Design is mobile-friendly","description":"Users increasingly experience your app on mobile devices, so it's important to ensure that the experience can adapt to smaller screens.","id":"mobile_friendly","tags":["pwa"],"audits":{"viewport":{"expectedValue":true,"weight":1},"content-width":{"expectedValue":true,"weight":1}}}]},{"name":"Best Practices","description":"We've compiled some recommendations for modernizing your web app and avoiding performance pitfalls. These audits do not affect your score but are worth a look.","id":"best_practices_parent","tags":["best_practices"],"scored":false,"categorizable":true,"items":[{"name":"Using modern offline features","id":"modern_offline","tags":["best_practices"],"audits":{"appcache-manifest":{"expectedValue":false},"no-websql":{"expectedValue":false}}},{"name":"Using modern protocols","id":"modern_network","tags":["best_practices"],"audits":{"is-on-https":{"expectedValue":false},"uses-http2":{"expectedValue":false,"description":"Resources made by this application should be severed over HTTP/2 for improved performance."}}},{"name":"Using bytes efficiently","id":"byte_efficiency","tags":["best_practices"],"audits":{"unused-css-rules":{"expectedValue":false}}},{"name":"Using modern CSS features","id":"modern_css","tags":["best_practices"],"audits":{"no-old-flexbox":{"expectedValue":false}}},{"name":"Using modern JavaScript features","id":"modern_js","tags":["best_practices"],"audits":{"uses-passive-event-listeners":{"expectedValue":true},"no-mutation-events":{"expectedValue":false}}},{"name":"Avoiding APIs that harm the user experience","id":"ux_harmful_apis","tags":["best_practices"],"audits":{"no-document-write":{"expectedValue":false},"link-blocking-first-paint":{"expectedValue":false},"script-blocking-first-paint":{"expectedValue":false},"external-anchors-use-rel-noopener":{"expectedValue":true},"geolocation-on-start":{"expectedValue":false},"notification-on-start":{"expectedValue":false}}},{"name":"Accessibility","id":"a11y","tags":["best_practices"],"audits":{"aria-allowed-attr":{"expectedValue":true,"weight":1},"aria-required-attr":{"expectedValue":true,"weight":1},"aria-valid-attr":{"expectedValue":true,"weight":1},"aria-valid-attr-value":{"expectedValue":true,"weight":1},"color-contrast":{"expectedValue":true,"weight":1},"image-alt":{"expectedValue":true,"weight":1},"label":{"expectedValue":true,"weight":1},"tabindex":{"expectedValue":true,"weight":1}}},{"name":"Other","id":"other_best_practices","tags":["best_practices"],"audits":{"manifest-short-name-length":{"expectedValue":true,"weight":1},"manifest-display":{"expectedValue":true,"weight":1},"serviceworker-push":{"expectedValue":true,"weight":0,"comingSoon":true,"description":"Service worker makes use of push notifications, if appropriate","category":"UX"},"tap-targets":{"expectedValue":true,"weight":0,"comingSoon":true,"description":"Tap targets are appropriately sized for touch","category":"UX"},"payments-autocomplete":{"expectedValue":true,"weight":0,"comingSoon":true,"description":"Payment forms marked up with `autocomplete` attributes","category":"UX"},"login-autocomplete":{"expectedValue":true,"weight":0,"comingSoon":true,"description":"Login forms marked up with `autocomplete` attributes","category":"UX"},"input-type":{"expectedValue":true,"weight":0,"comingSoon":true,"description":"Input fields use appropriate `type` attributes for custom keyboards","category":"UX"}}}]},{"name":"Performance Metrics","description":"These encapsulate your app's performance.","id":"perf_diagnostics","tags":["perf"],"scored":false,"categorizable":false,"items":[{"audits":{"critical-request-chains":{"expectedValue":0,"weight":1},"user-timings":{"expectedValue":0,"weight":1}}}]},{"name":"Fancier stuff","description":"A list of newer features that you could be using in your app. These audits do not affect your score and are just suggestions.","id":"fancy_best_practices","tags":["best_practices"],"scored":false,"categorizable":true,"items":[{"name":"New JavaScript features","audits":{"no-datenow":{"expectedValue":false},"no-console-time":{"expectedValue":false}}}]}]}},{}],6:[function(require,module,exports){'use strict';const path=require('path');const Formatter=require('./formatter');const html="<details class=\"subitem__details\">\n  <summary class=\"subitem__detail\">\n    {{#if (gt this.nodes.length 1)}}\n      {{this.nodes.length}} elements fail this test\n    {{else}}\n      {{this.nodes.length}} element fails this test\n    {{/if}}\n    <a href=\"{{ this.helpUrl }}\" target=\"_blank\"><small>learn more</small></a>\n  </summary>\n  <ul class=\"subitem__details\">\n  {{#each this.nodes}}\n    <li class=\"subitem__detail\"><code>{{ this.target }}</code></li>\n  {{/each}}\n  </ul>\n</details>\n";class Accessibilty extends Formatter{static getFormatter(type){switch(type){case'pretty':return function(info){if(info===null||typeof info==='undefined'||typeof info.impact==='undefined'||typeof info.helpUrl==='undefined'||typeof info.nodes==='undefined'||!Array.isArray(info.nodes)){return'';}
const output=`      - Rating: ${info.impact}\n`+`      - See: ${info.helpUrl}\n`+`      - Nodes: ${info.nodes.length} nodes identified (see HTML output for details)\n`;return output;};case'html':return html;default:throw new Error('Unknown formatter type');}}
static getHelpers(){return{gt(a,b){return a>b;}};}}
module.exports=Accessibilty;},{"./formatter":8,"path":204}],7:[function(require,module,exports){(function(process){'use strict';const URL=require('../lib/url-shim');const path=require('path');const Formatter=require('./formatter');const html="<style>\n.tree-marker {\n  width: 12px;\n  height: 26px;\n  display: block;\n  float: left;\n  background-position: top left;\n}\n\n.horiz-down {\n  background: url('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+Cjxzdmcgd2lkdGg9IjE2cHgiIGhlaWdodD0iMjZweCIgdmlld0JveD0iMCAwIDE2IDI2IiB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPgogICAgPCEtLSBHZW5lcmF0b3I6IFNrZXRjaCAzLjcuMiAoMjgyNzYpIC0gaHR0cDovL3d3dy5ib2hlbWlhbmNvZGluZy5jb20vc2tldGNoIC0tPgogICAgPHRpdGxlPmhvcml6LWRvd248L3RpdGxlPgogICAgPGRlc2M+Q3JlYXRlZCB3aXRoIFNrZXRjaC48L2Rlc2M+CiAgICA8ZGVmcz48L2RlZnM+CiAgICA8ZyBpZD0iUGFnZS0xIiBzdHJva2U9Im5vbmUiIHN0cm9rZS13aWR0aD0iMSIgZmlsbD0ibm9uZSIgZmlsbC1ydWxlPSJldmVub2RkIj4KICAgICAgICA8ZyBpZD0iaG9yaXotZG93biIgZmlsbD0iI0Q4RDhEOCI+CiAgICAgICAgICAgIDxyZWN0IGlkPSJSZWN0YW5nbGUtMTM4IiB0cmFuc2Zvcm09InRyYW5zbGF0ZSg3LjAwMDAwMCwgMTMuMDAwMDAwKSByb3RhdGUoLTI3MC4wMDAwMDApIHRyYW5zbGF0ZSgtNy4wMDAwMDAsIC0xMy4wMDAwMDApICIgeD0iNiIgeT0iNCIgd2lkdGg9IjIiIGhlaWdodD0iMTgiPjwvcmVjdD4KICAgICAgICAgICAgPHJlY3QgaWQ9IlJlY3RhbmdsZS0xMzkiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDguMDAwMDAwLCAxOS4wMDAwMDApIHJvdGF0ZSgtMjcwLjAwMDAwMCkgdHJhbnNsYXRlKC04LjAwMDAwMCwgLTE5LjAwMDAwMCkgIiB4PSIxIiB5PSIxOCIgd2lkdGg9IjE0IiBoZWlnaHQ9IjIiPjwvcmVjdD4KICAgICAgICA8L2c+CiAgICA8L2c+Cjwvc3ZnPg==');\n}\n\n.right {\n  background: url('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+Cjxzdmcgd2lkdGg9IjE2cHgiIGhlaWdodD0iMjZweCIgdmlld0JveD0iMCAwIDE2IDI2IiB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPgogICAgPCEtLSBHZW5lcmF0b3I6IFNrZXRjaCAzLjcuMiAoMjgyNzYpIC0gaHR0cDovL3d3dy5ib2hlbWlhbmNvZGluZy5jb20vc2tldGNoIC0tPgogICAgPHRpdGxlPnJpZ2h0PC90aXRsZT4KICAgIDxkZXNjPkNyZWF0ZWQgd2l0aCBTa2V0Y2guPC9kZXNjPgogICAgPGRlZnM+PC9kZWZzPgogICAgPGcgaWQ9IlBhZ2UtMSIgc3Ryb2tlPSJub25lIiBzdHJva2Utd2lkdGg9IjEiIGZpbGw9Im5vbmUiIGZpbGwtcnVsZT0iZXZlbm9kZCI+CiAgICAgICAgPGcgaWQ9InJpZ2h0IiBmaWxsPSIjRDhEOEQ4Ij4KICAgICAgICAgICAgPHJlY3QgaWQ9IlJlY3RhbmdsZS0xMzgiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDguMDAwMDAwLCAxMy4wMDAwMDApIHJvdGF0ZSgtMjcwLjAwMDAwMCkgdHJhbnNsYXRlKC04LjAwMDAwMCwgLTEzLjAwMDAwMCkgIiB4PSI3IiB5PSI1IiB3aWR0aD0iMiIgaGVpZ2h0PSIxNiI+PC9yZWN0PgogICAgICAgIDwvZz4KICAgIDwvZz4KPC9zdmc+');\n}\n\n.up-right {\n  background: url('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+Cjxzdmcgd2lkdGg9IjE2cHgiIGhlaWdodD0iMjZweCIgdmlld0JveD0iMCAwIDE2IDI2IiB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPgogICAgPCEtLSBHZW5lcmF0b3I6IFNrZXRjaCAzLjcuMiAoMjgyNzYpIC0gaHR0cDovL3d3dy5ib2hlbWlhbmNvZGluZy5jb20vc2tldGNoIC0tPgogICAgPHRpdGxlPnVwLXJpZ2h0PC90aXRsZT4KICAgIDxkZXNjPkNyZWF0ZWQgd2l0aCBTa2V0Y2guPC9kZXNjPgogICAgPGRlZnM+PC9kZWZzPgogICAgPGcgaWQ9IlBhZ2UtMSIgc3Ryb2tlPSJub25lIiBzdHJva2Utd2lkdGg9IjEiIGZpbGw9Im5vbmUiIGZpbGwtcnVsZT0iZXZlbm9kZCI+CiAgICAgICAgPGcgaWQ9InVwLXJpZ2h0IiBmaWxsPSIjRDhEOEQ4Ij4KICAgICAgICAgICAgPHJlY3QgaWQ9IlJlY3RhbmdsZS0xMzgiIHg9IjciIHk9IjAiIHdpZHRoPSIyIiBoZWlnaHQ9IjE0Ij48L3JlY3Q+CiAgICAgICAgICAgIDxyZWN0IGlkPSJSZWN0YW5nbGUtMTM5IiB4PSI5IiB5PSIxMiIgd2lkdGg9IjciIGhlaWdodD0iMiI+PC9yZWN0PgogICAgICAgIDwvZz4KICAgIDwvZz4KPC9zdmc+');\n}\n\n.vert-right {\n  background: url('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+Cjxzdmcgd2lkdGg9IjE2cHgiIGhlaWdodD0iMjZweCIgdmlld0JveD0iMCAwIDE2IDI2IiB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPgogICAgPCEtLSBHZW5lcmF0b3I6IFNrZXRjaCAzLjcuMiAoMjgyNzYpIC0gaHR0cDovL3d3dy5ib2hlbWlhbmNvZGluZy5jb20vc2tldGNoIC0tPgogICAgPHRpdGxlPnZlcnQtcmlnaHQ8L3RpdGxlPgogICAgPGRlc2M+Q3JlYXRlZCB3aXRoIFNrZXRjaC48L2Rlc2M+CiAgICA8ZGVmcz48L2RlZnM+CiAgICA8ZyBpZD0iUGFnZS0xIiBzdHJva2U9Im5vbmUiIHN0cm9rZS13aWR0aD0iMSIgZmlsbD0ibm9uZSIgZmlsbC1ydWxlPSJldmVub2RkIj4KICAgICAgICA8ZyBpZD0idmVydC1yaWdodCIgZmlsbD0iI0Q4RDhEOCI+CiAgICAgICAgICAgIDxyZWN0IGlkPSJSZWN0YW5nbGUtMTM4IiB4PSI3IiB5PSIwIiB3aWR0aD0iMiIgaGVpZ2h0PSIyNyI+PC9yZWN0PgogICAgICAgICAgICA8cmVjdCBpZD0iUmVjdGFuZ2xlLTEzOSIgeD0iOSIgeT0iMTIiIHdpZHRoPSI3IiBoZWlnaHQ9IjIiPjwvcmVjdD4KICAgICAgICA8L2c+CiAgICA8L2c+Cjwvc3ZnPg==');\n}\n\n.vert {\n  background: url('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+Cjxzdmcgd2lkdGg9IjE2cHgiIGhlaWdodD0iMjZweCIgdmlld0JveD0iMCAwIDE2IDI2IiB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPgogICAgPCEtLSBHZW5lcmF0b3I6IFNrZXRjaCAzLjcuMiAoMjgyNzYpIC0gaHR0cDovL3d3dy5ib2hlbWlhbmNvZGluZy5jb20vc2tldGNoIC0tPgogICAgPHRpdGxlPnZlcnQ8L3RpdGxlPgogICAgPGRlc2M+Q3JlYXRlZCB3aXRoIFNrZXRjaC48L2Rlc2M+CiAgICA8ZGVmcz48L2RlZnM+CiAgICA8ZyBpZD0iUGFnZS0xIiBzdHJva2U9Im5vbmUiIHN0cm9rZS13aWR0aD0iMSIgZmlsbD0ibm9uZSIgZmlsbC1ydWxlPSJldmVub2RkIj4KICAgICAgICA8ZyBpZD0idmVydCIgZmlsbD0iI0Q4RDhEOCI+CiAgICAgICAgICAgIDxyZWN0IGlkPSJSZWN0YW5nbGUtMTM4IiB4PSI3IiB5PSIwIiB3aWR0aD0iMiIgaGVpZ2h0PSIyNiI+PC9yZWN0PgogICAgICAgIDwvZz4KICAgIDwvZz4KPC9zdmc+');\n}\n\n.space {\n  background: url('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+Cjxzdmcgd2lkdGg9IjE2cHgiIGhlaWdodD0iMTZweCIgdmlld0JveD0iMCAwIDE2IDE2IiB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPgogICAgPCEtLSBHZW5lcmF0b3I6IFNrZXRjaCAzLjcuMiAoMjgyNzYpIC0gaHR0cDovL3d3dy5ib2hlbWlhbmNvZGluZy5jb20vc2tldGNoIC0tPgogICAgPHRpdGxlPmhvcml6LWRvd248L3RpdGxlPgogICAgPGRlc2M+Q3JlYXRlZCB3aXRoIFNrZXRjaC48L2Rlc2M+CiAgICA8ZGVmcz48L2RlZnM+CiAgICA8ZyBpZD0iUGFnZS0xIiBzdHJva2U9Im5vbmUiIHN0cm9rZS13aWR0aD0iMSIgZmlsbD0ibm9uZSIgZmlsbC1ydWxlPSJldmVub2RkIj4KICAgICAgICA8ZyBpZD0iaG9yaXotZG93biI+PC9nPgogICAgPC9nPgo8L3N2Zz4=');\n}\n\n.cnc-tree {\n  font-size: 14px;\n  width: 100%;\n  overflow-x: auto;\n}\n\n.cnc-node {\n  height: 26px;\n  line-height: 26px;\n  white-space: nowrap;\n}\n\n.cnc-node__tree-value {\n  margin-left: 10px;\n}\n\n.cnc-node__chain-duration {\n  font-weight: bold;\n}\n\n.cnc-node__tree-hostname {\n  color: #999;\n}\n\n</style>\n\n{{#*inline \"writeNode\"}}\n  <div class=\"cnc-node\" title=\"{{ this.node.request.url }}\">\n    <span class=\"cnc-node__tree-marker\">\n    {{#each treeMarkers as |separator| }}\n      {{#separator}}\n      <span class=\"tree-marker vert\"></span>\n      <span class=\"tree-marker space\"></span>\n      {{else}}\n      <span class=\"tree-marker space\"></span>\n      <span class=\"tree-marker space\"></span>\n      {{/separator}}\n    {{/each}}\n    {{#isLastChild}}\n      <span class=\"tree-marker up-right\"></span>\n      <span class=\"tree-marker right\"></span>\n    {{else}}\n      <span class=\"tree-marker vert-right\"></span>\n      <span class=\"tree-marker right\"></span>\n    {{/isLastChild}}\n\n    {{#hasChildren}}\n      <span class=\"tree-marker horiz-down\"></span>\n    {{else}}\n      <span class=\"tree-marker right\"></span>\n    {{/hasChildren}}\n    </span>\n\n    <span class=\"cnc-node__tree-value\">\n      {{#parseURL this.node.request.url }}\n        <span class=\"cnc-node__tree-file\">{{ this.file }}</span>\n        <span class=\"cnc-node__tree-hostname\">({{ this.hostname }})</span>\n      {{/parseURL}}\n      {{#unless hasChildren}}\n        - <span class=\"cnc-node__chain-duration\">{{chainDuration startTime this.node.request.endTime }}ms, {{formatTransferSize this.transferSize}}KB</span>\n      {{/unless}}\n    </span>\n  </div>\n\n  {{#each this.node.children as |child| }}\n    {{#createContextFor ../node.children @key ../treeMarkers ../isLastChild ../startTime ../transferSize }}\n      {{> writeNode this }}\n    {{/createContextFor }}\n  {{/each}}\n{{/inline}}\n\n<ul class=\"subitem__details\">\n  <li class=\"subitem__detail\">Longest request chain (shorter is better): <strong>{{longestChain this}}</strong></li>\n  <li class=\"subitem__detail\">Longest chain duration (shorter is better): <strong>{{formatTime (longestDuration this)}}ms</strong></li>\n  <li class=\"subitem__detail\">Longest chain transfer size (smaller is better): <strong>{{formatTransferSize (longestChainTransferSize this)}}KB</strong></li>\n  <li class=\"subitem__detail\">\n    <div>Initial navigation</div>\n    {{#createTreeRenderContext this}}\n      {{#each this.tree }}\n        {{#createContextFor ../tree @key undefined undefined ../startTime ../transferSize }}\n          {{> writeNode this }}\n        {{/createContextFor}}\n      {{/each}}\n    {{/createTreeRenderContext}}\n  </li>\n</ul>\n";const isWindows=process.platform==='win32';const heavyHorizontal=isWindows?'\u2500':'━';const heavyVertical=isWindows?'\u2502 ':'┃ ';const heavyUpAndRight=isWindows?'\u2514':'┗';const heavyUpAndRightLong=heavyUpAndRight+heavyHorizontal;const heavyVerticalAndRight=isWindows?'\u251C':'┣';const heavyVerticalAndRightLong=heavyVerticalAndRight+heavyHorizontal;const heavyDownAndHorizontal=isWindows?'\u252C':'┳';class CriticalRequestChains extends Formatter{static getFormatter(type){switch(type){case'pretty':return function(info){if(info===null||typeof info==='undefined'){return'';}
const longestChain=CriticalRequestChains._getLongestChainLength(info);const longestDuration=CriticalRequestChains._getLongestChainDuration(info).toFixed(2);const longestTransferSize=CriticalRequestChains.formatTransferSize(CriticalRequestChains._getLongestChainTransferSize(info));const urlTree=CriticalRequestChains._createURLTreeOutput(info);const output=`    - Longest request chain (shorter is better): ${longestChain}\n`+`    - Longest chain duration (shorter is better): ${longestDuration}ms\n`+`    - Longest chain transfer size (smaller is better): ${longestTransferSize}KB\n`+'    - Initial navigation\n'+'      '+urlTree.replace(/\n/g,'\n      ')+'\n';return output;};case'html':return html;default:throw new Error('Unknown formatter type');}}
static _traverse(tree,cb){function walk(node,depth,startTime,transferSize){const children=Object.keys(node);if(children.length===0){return;}
if(!transferSize){transferSize=0;}
children.forEach(id=>{const child=node[id];if(!startTime){startTime=child.request.startTime;}
cb({depth,id,node:child,chainDuration:(child.request.endTime-startTime)*1000,chainTransferSize:(transferSize+child.request.transferSize)});walk(child.children,depth+1,startTime);},'');}
walk(tree,0);}
static _getLongestChainLength(tree){let longestChain=0;this._traverse(tree,opts=>{const depth=opts.depth;if(depth>longestChain){longestChain=depth;}});return(longestChain+1);}
static _getLongestChainDuration(tree){let longestChainDuration=0;this._traverse(tree,opts=>{const duration=opts.chainDuration;if(duration>longestChainDuration){longestChainDuration=duration;}});return longestChainDuration;}
static _getLongestChainTransferSize(tree){let transferSize=0;this._traverse(tree,opts=>{const chainTransferSize=opts.chainTransferSize;if(chainTransferSize>transferSize){transferSize=chainTransferSize;}});return transferSize;}
static _createURLTreeOutput(tree){function write(opts){const node=opts.node;const depth=opts.depth;const treeMarkers=opts.treeMarkers;let startTime=opts.startTime;const transferSize=opts.transferSize;return Object.keys(node).reduce((output,id,currentIndex,arr)=>{const hasChildren=(Object.keys(node[id].children).length>0);const isLastChild=(currentIndex===arr.length-1);const ancestorTreeMarker=treeMarkers.reduce((markers,marker)=>{return markers+(marker?heavyVertical:'  ');},'');const newTreeMakers=treeMarkers.slice(0);newTreeMakers.push(!isLastChild);const treeMarker=ancestorTreeMarker+
(isLastChild?heavyUpAndRightLong:heavyVerticalAndRightLong)+
(hasChildren?heavyDownAndHorizontal:heavyHorizontal);const parsedURL=CriticalRequestChains.parseURL(node[id].request.url);if(!startTime){startTime=node[id].request.startTime;}
const duration=((node[id].request.endTime-startTime)*1000).toFixed(2);const chainTransferSize=transferSize+node[id].request.transferSize;const formattedTransferSize=CriticalRequestChains.formatTransferSize(chainTransferSize);return output+`${treeMarker} ${parsedURL.file} (${parsedURL.hostname})`+
(hasChildren?'':` - ${duration}ms, ${formattedTransferSize}KB`)+'\n'+
write({node:node[id].children,depth:depth+1,treeMarkers:newTreeMakers,startTime,transferSize:chainTransferSize});},'');}
return write({node:tree,depth:0,treeMarkers:[],startTime:0,transferSize:0});}
static formatTime(time){return time.toFixed(2);}
static formatTransferSize(size){return(size/1024).toFixed(2);}
static parseURL(resourceURL,opts){const parsedURL={file:URL.getDisplayName(resourceURL),hostname:new URL(resourceURL).hostname};if(opts){return opts.fn(parsedURL);}
return parsedURL;}
static getHelpers(){return{longestChain(info){return CriticalRequestChains._getLongestChainLength(info);},longestDuration(info){return CriticalRequestChains._getLongestChainDuration(info);},longestChainTransferSize(info){return CriticalRequestChains._getLongestChainTransferSize(info);},chainDuration(startTime,endTime){return((endTime-startTime)*1000).toFixed(2);},formatTransferSize:CriticalRequestChains.formatTransferSize,parseURL:CriticalRequestChains.parseURL,formatTime:CriticalRequestChains.formatTime,createContextFor(parent,id,treeMarkers,parentIsLastChild,startTime,transferSize,opts){const node=parent[id];const siblings=Object.keys(parent);const isLastChild=siblings.indexOf(id)===(siblings.length-1);const hasChildren=Object.keys(node.children).length>0;const newTreeMarkers=Array.isArray(treeMarkers)?treeMarkers.slice(0):[];if(typeof parentIsLastChild!=='undefined'){newTreeMarkers.push(!parentIsLastChild);}
return opts.fn({node,isLastChild,hasChildren,startTime,transferSize:(transferSize+node.request.transferSize),treeMarkers:newTreeMarkers});},createTreeRenderContext(tree,opts){const transferSize=0;let startTime=0;const rootNodes=Object.keys(tree);if(rootNodes.length>0){startTime=tree[rootNodes[0]].request.startTime;}
return opts.fn({tree,startTime,transferSize});}};}}
module.exports=CriticalRequestChains;}).call(this,require('_process'))},{"../lib/url-shim":30,"./formatter":8,"_process":205,"path":204}],8:[function(require,module,exports){'use strict';class Formatter{static get CAPITAL_LETTERS(){return/([A-Z])/g;}
static get SUPPORTED_FORMATS(){if(!this._formatters){this._getFormatters();}
if(!this._supportedFormatsNames){this._generateSupportedFormats();}
return this._supportedFormatsNames;}
static _getFormatters(){this._formatters={accessibility:require('./accessibility'),criticalRequestChains:require('./critical-request-chains'),urllist:require('./url-list'),null:require('./null-formatter'),speedline:require('./speedline-formatter'),userTimings:require('./user-timings')};}
static _generateSupportedFormats(){const formatNames=Object.keys(this._formatters);this._supportedFormatsNames=formatNames.reduce((prev,format)=>{const formatName=format.replace(Formatter.CAPITAL_LETTERS,'_$1').toUpperCase();prev[formatName]=format;return prev;},{});}
static getByName(name){if(!this._formatters){this._getFormatters();}
if(!this._formatters[name]){throw new Error(`Unknown formatter: ${name}`);}
return this._formatters[name];}
static getFormatter(){throw new Error('Formatter must implement getPrettyFormatter()');}
static getHelpers(){}}
module.exports=Formatter;},{"./accessibility":6,"./critical-request-chains":7,"./null-formatter":9,"./speedline-formatter":10,"./url-list":11,"./user-timings":12}],9:[function(require,module,exports){'use strict';const Formatter=require('./formatter');class NullFormatter extends Formatter{static getFormatter(type){switch(type){case'pretty':return _=>'';case'html':return'';default:throw new Error('Unknown formatter type');}}}
module.exports=NullFormatter;},{"./formatter":8}],10:[function(require,module,exports){'use strict';const Formatter=require('./formatter');const path=require('path');const html="<style>\n  .speedline-measures {\n    font-size: 14px\n  }\n</style>\n\n<ul class=\"subitem__details\">\n  <li class=\"subitem__detail\">First Visual Change: <strong>{{this.first}}ms</strong></li>\n  <li class=\"subitem__detail\">Last Visual Change: <strong>{{this.complete}}ms</strong></li>\n</ul>\n";class SpeedlineFormatter extends Formatter{static getFormatter(type){switch(type){case'pretty':return function(info){if(!info||!Array.isArray(info.frames)){return'';}
const output=`    - First Visual Change: ${info.first}ms\n`+`    - Last Visual Change: ${info.complete}ms\n`;return output;};case'html':return html;default:throw new Error('Unknown formatter type');}}}
module.exports=SpeedlineFormatter;},{"./formatter":8,"path":204}],11:[function(require,module,exports){'use strict';const Formatter=require('./formatter');const path=require('path');const html="<style>\n  .http-resource__protocol,\n  .http-resource__code {\n    color: var(--secondary-text-color);\n  }\n  .http-resource__code {\n    text-overflow: ellipsis;\n    overflow: hidden;\n    white-space: pre-line;\n  }\n</style>\n\n<details class=\"subitem__details\">\n  <summary class=\"subitem__detail\">URLs</summary>\n  <ul class=\"subitem__details\">\n  {{#each this}}\n    <li class=\"subitem__detail http-resource\">\n      <span class=\"http-resource__url\">{{this.url}}</span>\n      {{#if this.label}}\n        <span class=\"http-resource__protocol\">({{this.label}})</span>\n      {{/if}}\n      {{#if this.code}}\n        <pre class=\"http-resource__code\">{{this.code}}</pre>\n      {{/if}}\n    </li>\n  {{/each}}\n  </ul>\n</details>\n";class UrlList extends Formatter{static getFormatter(type){switch(type){case'pretty':return resources=>{if(!Array.isArray(resources)){return'';}
let output='';resources.forEach(resource=>{output+=`      ${resource.url}`;if(resource.label){output+=` (${resource.label})`;}
output+='\n';});return output;};case'html':return html;default:throw new Error('Unknown formatter type');}}}
module.exports=UrlList;},{"./formatter":8,"path":204}],12:[function(require,module,exports){'use strict';const Formatter=require('./formatter');const path=require('path');const html="<style>\n  .ut-measure_listing-duration {\n    font-weight: bold\n  }\n</style>\n\n<ul class=\"subitem__details\">\n  {{#each this}}\n    <li class=\"subitem__detail\">\n      {{#if this.isMark}}\n        <strong class=\"ut-measure_listing-duration\">Mark: {{ decimal this.startTime }}ms</strong> - {{ this.name }}\n      {{else}}\n        <strong class=\"ut-measure_listing-duration\">Measure {{ decimal this.duration }}ms</strong> - {{ this.name }}\n      {{/if}}\n    </li>\n  {{/each}}\n</ul>\n";class UserTimings extends Formatter{static getFormatter(type){switch(type){case'pretty':return events=>{if(!Array.isArray(events)){return'';}
const measuresStr=events.filter(e=>!e.isMark).reduce((prev,event)=>{let output=prev+`    - measure ${event.name}: \t`;output+=`duration: ${event.duration.toFixed(1)}ms,\t`;output+=`start: ${event.startTime.toFixed(1)}ms,\tend: ${event.endTime.toFixed(1)}`;return output+'\n';},'');const marksStr=events.filter(e=>e.isMark).reduce((prev,event)=>{return prev+`    - mark ${event.name}: \t time: ${event.startTime.toFixed(1)}ms\n`;},'');return measuresStr+marksStr;};case'html':return html;default:throw new Error('Unknown formatter type');}}}
module.exports=UserTimings;},{"./formatter":8,"path":204}],13:[function(require,module,exports){'use strict';const EventEmitter=require('events').EventEmitter;const log=require('../../lib/log.js');class Connection{constructor(){this._lastCommandId=0;this._callbacks=new Map();this._eventEmitter=new EventEmitter();}
connect(){return Promise.reject(new Error('Not implemented'));}
disconnect(){return Promise.reject(new Error('Not implemented'));}
sendCommand(method,params){log.formatProtocol('method => browser',{method,params},'verbose');const id=++this._lastCommandId;params=params||{};const message=JSON.stringify({id,method,params});this.sendRawMessage(message);return new Promise((resolve,reject)=>{this._callbacks.set(id,{resolve,reject,method});});}
on(eventName,cb){if(eventName!=='notification'){throw new Error('Only supports "notification" events');}
this._eventEmitter.on(eventName,cb);}
sendRawMessage(message){return Promise.reject(new Error('Not implemented'));}
handleRawMessage(message){const object=JSON.parse(message);if(object.id){const callback=this._callbacks.get(object.id);this._callbacks.delete(object.id);return callback.resolve(Promise.resolve().then(_=>{if(object.error){return this.handleRawError(object.error,callback.method);}
log.formatProtocol('method <= browser OK',{method:callback.method,params:object.result},'verbose');return object.result;}));}
log.formatProtocol('<= event',{method:object.method,params:object.params},'verbose');this.emitNotification(object.method,object.params);}
handleRawError(error,method){if(error.message&&error.message.includes('DOM agent hasn\'t been enabled')){return;}
log.formatProtocol('method <= browser ERR',{method},'error');throw new Error(`Protocol error (${method}): ${error.message}`);}
emitNotification(method,params){this._eventEmitter.emit('notification',{method,params});}
dispose(){this._eventEmitter.removeAllListeners();this._eventEmitter=null;}}
module.exports=Connection;},{"../../lib/log.js":24,"events":201}],14:[function(require,module,exports){'use strict';const Connection=require('./connection.js');const log=require('../../lib/log.js');class ExtensionConnection extends Connection{constructor(){super();this._tabId=null;this._onEvent=this._onEvent.bind(this);this._onUnexpectedDetach=this._onUnexpectedDetach.bind(this);}
_onEvent(source,method,params){log.log('<=',method,params);this.emitNotification(method,params);}
_onUnexpectedDetach(debuggee,detachReason){this._detachCleanup();throw new Error('Lighthouse detached from browser: '+detachReason);}
_detachCleanup(){this._tabId=null;chrome.debugger.onEvent.removeListener(this._onEvent);chrome.debugger.onDetach.removeListener(this._onUnexpectedDetach);this.dispose();}
connect(){if(this._tabId!==null){return Promise.resolve();}
return this._queryCurrentTab().then(tab=>{const tabId=this._tabId=tab.id;chrome.debugger.onEvent.addListener(this._onEvent);chrome.debugger.onDetach.addListener(this._onUnexpectedDetach);return new Promise((resolve,reject)=>{chrome.debugger.attach({tabId},'1.1',_=>{if(chrome.runtime.lastError){return reject(new Error(chrome.runtime.lastError.message));}
resolve(tabId);});});});}
disconnect(){if(this._tabId===null){log.warn('ExtensionConnection','disconnect() was called without an established connection.');return Promise.resolve();}
const tabId=this._tabId;return new Promise((resolve,reject)=>{chrome.debugger.detach({tabId},_=>{if(chrome.runtime.lastError){return reject(new Error(chrome.runtime.lastError.message));}
chrome.tabs.reload(tabId);resolve();});}).then(_=>this._detachCleanup());}
sendCommand(command,params){return new Promise((resolve,reject)=>{log.formatProtocol('method => browser',{method:command,params:params},'verbose');if(!this._tabId){log.error('ExtensionConnection','No tabId set for sendCommand');}
chrome.debugger.sendCommand({tabId:this._tabId},command,params,result=>{if(chrome.runtime.lastError){const message=chrome.runtime.lastError.message;let error;try{error=JSON.parse(message);}catch(e){}
error=error||{message:'Unknown debugger protocol error.'};try{return resolve(this.handleRawError(error,command));}catch(err){return reject(err);}}
log.formatProtocol('method <= browser OK',{method:command,params:result},'verbose');resolve(result);});});}
_queryCurrentTab(){return new Promise((resolve,reject)=>{const queryOpts={active:true,lastFocusedWindow:true,windowType:'normal'};chrome.tabs.query(queryOpts,(tabs=>{if(chrome.runtime.lastError){return reject(chrome.runtime.lastError);}
if(tabs.length===0){const message='Couldn\'t resolve current tab. Please file a bug.';return reject(new Error(message));}
resolve(tabs[0]);}));});}
getCurrentTabURL(){return this._queryCurrentTab().then(tab=>tab.url);}}
module.exports=ExtensionConnection;},{"../../lib/log.js":24,"./connection.js":13}],15:[function(require,module,exports){'use strict';const Connection=require('./connection.js');class Port{on(eventName,cb){}
send(message){}
close(){}}
class RawConnection extends Connection{constructor(port){super();this._port=port;this._port.on('message',this.handleRawMessage.bind(this));this._port.on('close',this.dispose.bind(this));}
connect(){return Promise.resolve();}
disconnect(){this._port.close();return Promise.resolve();}
sendRawMessage(message){this._port.send(message);}}
module.exports=RawConnection;},{"./connection.js":13}],16:[function(require,module,exports){'use strict';const NetworkRecorder=require('../lib/network-recorder');const emulation=require('../lib/emulation');const Element=require('../lib/element');const EventEmitter=require('events').EventEmitter;const URL=require('../lib/url-shim');const log=require('../lib/log.js');const MAX_WAIT_FOR_FULLY_LOADED=25*1000;const PAUSE_AFTER_LOAD=500;class Driver{constructor(connection){this._traceEvents=[];this._traceCategories=Driver.traceCategories;this._eventEmitter=new EventEmitter();this._connection=connection;this.online=true;connection.on('notification',event=>this._eventEmitter.emit(event.method,event.params));}
static get traceCategories(){return['-*','toplevel','blink.console','blink.user_timing','benchmark','latencyInfo','devtools.timeline','disabled-by-default-devtools.timeline','disabled-by-default-devtools.timeline.frame','disabled-by-default-devtools.timeline.stack','disabled-by-default-devtools.screenshot'];}
connect(){return this._connection.connect();}
disconnect(){return this._connection.disconnect();}
on(eventName,cb){if(this._eventEmitter===null){throw new Error('connect() must be called before attempting to listen to events.');}
log.formatProtocol('listen for event =>',{method:eventName},'verbose');this._eventEmitter.on(eventName,cb);}
once(eventName,cb){if(this._eventEmitter===null){throw new Error('connect() must be called before attempting to listen to events.');}
log.formatProtocol('listen once for event =>',{method:eventName},'verbose');this._eventEmitter.once(eventName,cb);}
off(eventName,cb){if(this._eventEmitter===null){throw new Error('connect() must be called before attempting to remove an event listener.');}
this._eventEmitter.removeListener(eventName,cb);}
sendCommand(method,params){return this._connection.sendCommand(method,params);}
evaluateScriptOnLoad(scriptSource){return this.sendCommand('Page.addScriptToEvaluateOnLoad',{scriptSource});}
evaluateAsync(expression){return new Promise((resolve,reject)=>{const asyncTimeout=setTimeout((_=>reject(new Error('The asynchronous expression exceeded the allotted time of 60s'))),60000);this.sendCommand('Runtime.evaluate',{expression:`(function wrapInNativePromise() {
          const __nativePromise = window.__nativePromise || Promise;
          return new __nativePromise(function (resolve) {
            return __nativePromise.resolve()
              .then(_ => ${expression})
              .catch(${wrapRuntimeEvalErrorInBrowser.toString()})
              .then(resolve);
          });
        }())`,includeCommandLineAPI:true,awaitPromise:true,returnByValue:true}).then(result=>{clearTimeout(asyncTimeout);const value=result.result.value;if(result.exceptionDetails){reject(new Error('an unexpected driver error occurred'));}if(value&&value.__failedInBrowser){reject(Object.assign(new Error(),value));}else{resolve(value);}}).catch(err=>{clearTimeout(asyncTimeout);reject(err);});});}
getSecurityState(){return new Promise((resolve,reject)=>{this.once('Security.securityStateChanged',data=>{this.sendCommand('Security.disable').then(_=>resolve(data),reject);});this.sendCommand('Security.enable').catch(reject);});}
getServiceWorkerVersions(){return new Promise((resolve,reject)=>{this.once('ServiceWorker.workerVersionUpdated',data=>{this.sendCommand('ServiceWorker.disable').then(_=>resolve(data),reject);});this.sendCommand('ServiceWorker.enable').catch(reject);});}
getServiceWorkerRegistrations(){return new Promise((resolve,reject)=>{this.once('ServiceWorker.workerRegistrationUpdated',data=>{this.sendCommand('ServiceWorker.disable').then(_=>resolve(data),reject);});this.sendCommand('ServiceWorker.enable').catch(reject);});}
assertNoSameOriginServiceWorkerClients(pageUrl){let registrations;let versions;return this.getServiceWorkerRegistrations().then(data=>{registrations=data.registrations;}).then(_=>this.getServiceWorkerVersions()).then(data=>{versions=data.versions;}).then(_=>{const origin=new URL(pageUrl).origin;registrations.filter(reg=>{const swOrigin=new URL(reg.scopeURL).origin;return origin===swOrigin;}).forEach(reg=>{versions.forEach(ver=>{if(ver.registrationId!==reg.registrationId){return;}
if(ver.controlledClients&&ver.controlledClients.length>0){throw new Error('You probably have multiple tabs open to the same origin.');}});});});}
enableUrlUpdateIfRedirected(opts){this._networkRecorder.on('requestloaded',redirectRequest=>{if(!redirectRequest.redirectSource){return;}
const earlierRequest=redirectRequest.redirectSource;if(earlierRequest.url===opts.url){opts.url=redirectRequest.url;}});}
_waitForNetworkIdle(pauseAfterLoadMs){let idleTimeout;let cancel;const promise=new Promise((resolve,reject)=>{const onIdle=()=>{this._networkRecorder.once('networkbusy',onBusy);idleTimeout=setTimeout(_=>{cancel();resolve();},pauseAfterLoadMs);};const onBusy=()=>{this._networkRecorder.once('networkidle',onIdle);clearTimeout(idleTimeout);};cancel=()=>{clearTimeout(idleTimeout);this._networkRecorder.removeListener('networkbusy',onBusy);this._networkRecorder.removeListener('networkidle',onIdle);};if(this._networkRecorder.isIdle()){onIdle();}else{onBusy();}});return{promise,cancel};}
_waitForLoadEvent(pauseAfterLoadMs){let loadListener;let loadTimeout;const promise=new Promise((resolve,reject)=>{loadListener=function(){loadTimeout=setTimeout(resolve,pauseAfterLoadMs);};this.once('Page.loadEventFired',loadListener);});const cancel=()=>{this.off('Page.loadEventFired',loadListener);clearTimeout(loadTimeout);};return{promise,cancel};}
_waitForFullyLoaded(pauseAfterLoadMs){let maxTimeoutHandle;const waitForLoadEvent=this._waitForLoadEvent(pauseAfterLoadMs);const waitForNetworkIdle=this._waitForNetworkIdle(pauseAfterLoadMs);const loadPromise=Promise.all([waitForLoadEvent.promise,waitForNetworkIdle.promise]).then(_=>{return function(){log.verbose('Driver','loadEventFired and network considered idle');clearTimeout(maxTimeoutHandle);};});const maxTimeoutPromise=new Promise((resolve,reject)=>{maxTimeoutHandle=setTimeout(resolve,MAX_WAIT_FOR_FULLY_LOADED);}).then(_=>{return function(){log.warn('Driver','Timed out waiting for page load. Moving on...');waitForLoadEvent.cancel();waitForNetworkIdle.cancel();};});return Promise.race([loadPromise,maxTimeoutPromise]).then(cleanup=>cleanup());}
gotoURL(url,options){const _options=options||{};const waitForLoad=_options.waitForLoad||false;const disableJS=_options.disableJavaScript||false;const pauseAfterLoadMs=(_options.flags&&_options.flags.pauseAfterLoad)||PAUSE_AFTER_LOAD;return this.sendCommand('Page.enable').then(_=>this.sendCommand('Emulation.setScriptExecutionDisabled',{value:disableJS})).then(_=>this.sendCommand('Page.navigate',{url})).then(_=>waitForLoad&&this._waitForFullyLoaded(pauseAfterLoadMs));}
getObjectProperty(objectId,propName){return new Promise((resolve,reject)=>{this.sendCommand('Runtime.getProperties',{objectId,accessorPropertiesOnly:true,generatePreview:false,ownProperties:false,}).then(properties=>{const propertyForName=properties.result.find(property=>property.name===propName);if(propertyForName){resolve(propertyForName.value.value);}else{reject(null);}});});}
queryPermissionState(name){const expressionToEval=`
      navigator.permissions.query({name: '${name}'}).then(result => {
        return result.state;
      })
    `;return this.evaluateAsync(expressionToEval);}
querySelector(selector){return this.sendCommand('DOM.getDocument').then(result=>result.root.nodeId).then(nodeId=>this.sendCommand('DOM.querySelector',{nodeId,selector})).then(element=>{if(element.nodeId===0){return null;}
return new Element(element,this);});}
querySelectorAll(selector){return this.sendCommand('DOM.getDocument').then(result=>result.root.nodeId).then(nodeId=>this.sendCommand('DOM.querySelectorAll',{nodeId,selector})).then(nodeList=>{const elementList=[];nodeList.nodeIds.forEach(nodeId=>{if(nodeId!==0){elementList.push(new Element({nodeId},this));}});return elementList;});}
beginTrace(){const tracingOpts={categories:this._traceCategories.join(','),transferMode:'ReturnAsStream',options:'sampling-frequency=10000'};return this.sendCommand('Debugger.disable').then(_=>this.sendCommand('CSS.disable')).then(_=>this.sendCommand('DOM.disable')).then(_=>this.sendCommand('Page.enable')).then(_=>this.sendCommand('Tracing.start',tracingOpts));}
endTrace(){return new Promise((resolve,reject)=>{this.once('Tracing.tracingComplete',streamHandle=>{this._readTraceFromStream(streamHandle).then(traceContents=>resolve(traceContents),reject);});this.sendCommand('Tracing.end').catch(reject);});}
_readTraceFromStream(streamHandle){return new Promise((resolve,reject)=>{let isEOF=false;let result='';const readArguments={handle:streamHandle.stream};const onChunkRead=response=>{if(isEOF){return;}
result+=response.data;if(response.eof){isEOF=true;return resolve(JSON.parse(result));}
return this.sendCommand('IO.read',readArguments).then(onChunkRead);};this.sendCommand('IO.read',readArguments).then(onChunkRead).catch(reject);});}
beginNetworkCollect(opts){return new Promise((resolve,reject)=>{this._networkRecords=[];this._networkRecorder=new NetworkRecorder(this._networkRecords);this.enableUrlUpdateIfRedirected(opts);this.on('Network.requestWillBeSent',this._networkRecorder.onRequestWillBeSent);this.on('Network.requestServedFromCache',this._networkRecorder.onRequestServedFromCache);this.on('Network.responseReceived',this._networkRecorder.onResponseReceived);this.on('Network.dataReceived',this._networkRecorder.onDataReceived);this.on('Network.loadingFinished',this._networkRecorder.onLoadingFinished);this.on('Network.loadingFailed',this._networkRecorder.onLoadingFailed);this.on('Network.resourceChangedPriority',this._networkRecorder.onResourceChangedPriority);this.sendCommand('Network.enable').then(resolve,reject);});}
endNetworkCollect(){return new Promise((resolve,reject)=>{this.off('Network.requestWillBeSent',this._networkRecorder.onRequestWillBeSent);this.off('Network.requestServedFromCache',this._networkRecorder.onRequestServedFromCache);this.off('Network.responseReceived',this._networkRecorder.onResponseReceived);this.off('Network.dataReceived',this._networkRecorder.onDataReceived);this.off('Network.loadingFinished',this._networkRecorder.onLoadingFinished);this.off('Network.loadingFailed',this._networkRecorder.onLoadingFailed);this.off('Network.resourceChangedPriority',this._networkRecorder.onResourceChangedPriority);resolve(this._networkRecords);this._networkRecorder=null;this._networkRecords=[];});}
enableRuntimeEvents(){return this.sendCommand('Runtime.enable');}
beginEmulation(flags){const emulations=[];if(!flags.disableDeviceEmulation){emulations.push(emulation.enableNexus5X(this));}
if(!flags.disableNetworkThrottling){emulations.push(emulation.enableNetworkThrottling(this));}
if(!flags.disableCpuThrottling){emulations.push(emulation.enableCPUThrottling(this));}
return Promise.all(emulations);}
goOffline(){return this.sendCommand('Network.enable').then(_=>{return emulation.goOffline(this);}).then(_=>{this.online=false;});}
goOnline(options){return this.sendCommand('Network.enable').then(_=>{if(!options.flags.disableNetworkThrottling){return emulation.enableNetworkThrottling(this);}
return emulation.disableNetworkThrottling(this);}).then(_=>{this.online=true;});}
cleanAndDisableBrowserCaches(){return Promise.all([this.clearBrowserCache(),this.disableBrowserCache()]);}
clearBrowserCache(){return this.sendCommand('Network.clearBrowserCache');}
disableBrowserCache(){return this.sendCommand('Network.setCacheDisabled',{cacheDisabled:true});}
clearDataForOrigin(url){const origin=new URL(url).origin;const typesToClear=['appcache','file_systems','indexeddb','local_storage','shader_cache','websql','service_workers','cache_storage'].join(',');return this.sendCommand('Storage.clearDataForOrigin',{origin:origin,storageTypes:typesToClear});}
cacheNatives(){return this.evaluateScriptOnLoad(`window.__nativePromise = Promise;
        window.__nativeError = Error;`);}
captureFunctionCallSites(funcName){const globalVarToPopulate=`window['__${funcName}StackTraces']`;const collectUsage=()=>{return this.evaluateAsync(`Promise.resolve(Array.from(${globalVarToPopulate}).map(item => JSON.parse(item)))`).then(result=>{if(!Array.isArray(result)){throw new Error('Driver failure: Expected evaluateAsync results to be an array '+`but got "${JSON.stringify(result)}" instead.`);}
return result.filter(item=>!item.isExtension);});};const funcBody=captureJSCallUsage.toString();this.evaluateScriptOnLoad(`
        ${globalVarToPopulate} = new Set();
        (${funcName} = ${funcBody}(${funcName}, ${globalVarToPopulate}))`);return collectUsage;}
blockUrlPatterns(urlPatterns){const promiseArr=urlPatterns.map(url=>this.sendCommand('Network.addBlockedURL',{url}));return Promise.all(promiseArr);}}
function captureJSCallUsage(funcRef,set){const __nativeError=window.__nativeError||Error;const originalFunc=funcRef;const originalPrepareStackTrace=__nativeError.prepareStackTrace;return function(){const args=[...arguments];__nativeError.prepareStackTrace=function(error,structStackTrace){const callFrame=structStackTrace[1];let url=callFrame.getFileName()||callFrame.getEvalOrigin();const line=callFrame.getLineNumber();const col=callFrame.getColumnNumber();const isEval=callFrame.isEval();let isExtension=false;const stackTrace=structStackTrace.slice(1).map(callsite=>callsite.toString());if(isEval){url=stackTrace[1];}
if(stackTrace[0].startsWith('<anonymous>')){url=stackTrace[0];isExtension=true;}
return{url,args,line,col,isEval,isExtension};};const e=new __nativeError(`__called ${funcRef.name}__`);set.add(JSON.stringify(e.stack));__nativeError.prepareStackTrace=originalPrepareStackTrace;return originalFunc.apply(this,arguments);};}
function wrapRuntimeEvalErrorInBrowser(err){err=err||new Error();const fallbackMessage=typeof err==='string'?err:'unknown error';return{__failedInBrowser:true,name:err.name||'Error',message:err.message||fallbackMessage,stack:err.stack||(new Error()).stack,};}
module.exports=Driver;},{"../lib/element":20,"../lib/emulation":21,"../lib/log.js":24,"../lib/network-recorder":26,"../lib/url-shim":30,"events":201}],17:[function(require,module,exports){'use strict';const log=require('../lib/log.js');const Audit=require('../audits/audit');const path=require('path');class GatherRunner{static loadBlank(driver){return driver.gotoURL('about:blank').then(_=>new Promise((resolve,reject)=>setTimeout(resolve,300)));}
static loadPage(driver,options){return Promise.resolve().then(_=>options.config.recordTrace&&driver.beginTrace()).then(_=>driver.beginNetworkCollect(options)).then(_=>driver.gotoURL(options.url,{waitForLoad:true,disableJavaScript:!!options.disableJavaScript,flags:options.flags,}));}
static setupDriver(driver,options){log.log('status','Initializing…');return driver.assertNoSameOriginServiceWorkerClients(options.url).then(_=>driver.beginEmulation(options.flags)).then(_=>driver.enableRuntimeEvents()).then(_=>driver.cacheNatives()).then(_=>driver.cleanAndDisableBrowserCaches()).then(_=>driver.clearDataForOrigin(options.url)).then(_=>driver.blockUrlPatterns(options.flags.blockedUrlPatterns||[]));}
static disposeDriver(driver){log.log('status','Disconnecting from browser...');driver.disconnect();}
static recoverOrThrow(promise){return promise.catch(err=>{if(!err.recoverable){throw err;}});}
static beforePass(options,gathererResults){const pass=GatherRunner.loadBlank(options.driver);return options.config.gatherers.reduce((chain,gatherer)=>{return chain.then(_=>{const artifactPromise=Promise.resolve().then(_=>gatherer.beforePass(options));gathererResults[gatherer.name]=[artifactPromise];return GatherRunner.recoverOrThrow(artifactPromise);});},pass);}
static pass(options,gathererResults){const driver=options.driver;const config=options.config;const gatherers=config.gatherers;const gatherernames=gatherers.map(g=>g.name).join(', ');const status='Loading page & waiting for onload';log.log('status',status,gatherernames);const pass=GatherRunner.loadPage(driver,options).then(_=>{log.log('statusEnd',status);});return gatherers.reduce((chain,gatherer)=>{return chain.then(_=>{const artifactPromise=Promise.resolve().then(_=>gatherer.pass(options));gathererResults[gatherer.name].push(artifactPromise);return GatherRunner.recoverOrThrow(artifactPromise);});},pass);}
static afterPass(options,gathererResults){const driver=options.driver;const config=options.config;const gatherers=config.gatherers;const passData={};let pass=Promise.resolve();if(config.recordTrace){pass=pass.then(_=>{log.log('status','Retrieving trace');return driver.endTrace();}).then(traceContents=>{passData.trace=Array.isArray(traceContents)?{traceEvents:traceContents}:traceContents;log.verbose('statusEnd','Retrieving trace');});}
const status='Retrieving network records';pass=pass.then(_=>{log.log('status',status);return driver.endNetworkCollect();}).then(networkRecords=>{const mainRecord=networkRecords.find(record=>record.url===options.url);if(driver.online&&mainRecord.failed){log.error('GatherRunner',mainRecord.localizedFailDescription);const error=new Error(`Unable to load the page: ${mainRecord.localizedFailDescription}`);error.code='PAGE_LOAD_ERROR';return Promise.reject(error);}
config.recordNetwork&&(passData.networkRecords=networkRecords);log.verbose('statusEnd',status);});pass=gatherers.reduce((chain,gatherer)=>{const status=`Retrieving: ${gatherer.name}`;return chain.then(_=>{log.log('status',status);const artifactPromise=Promise.resolve().then(_=>gatherer.afterPass(options,passData));gathererResults[gatherer.name].push(artifactPromise);return GatherRunner.recoverOrThrow(artifactPromise);}).then(_=>{log.verbose('statusEnd',status);});},pass);return pass.then(_=>passData);}
static collectArtifacts(gathererResults){const artifacts={};return Object.keys(gathererResults).reduce((chain,gathererName)=>{return chain.then(_=>{const phaseResultsPromises=gathererResults[gathererName];return Promise.all(phaseResultsPromises).then(phaseResults=>{const definedResults=phaseResults.filter(element=>element!==undefined);const artifact=definedResults[definedResults.length-1];if(artifact===undefined){throw new Error(`${gathererName} failed to provide an artifact.`);}
artifacts[gathererName]=artifact;},err=>{artifacts[gathererName]=err;});});},Promise.resolve()).then(_=>{return artifacts;});}
static run(passes,options){const driver=options.driver;const tracingData={traces:{},networkRecords:{}};if(typeof options.url!=='string'||options.url.length===0){return Promise.reject(new Error('You must provide a url to the driver'));}
if(typeof options.flags==='undefined'){options.flags={};}
if(typeof options.config==='undefined'){return Promise.reject(new Error('You must provide a config'));}
if(typeof options.flags.disableCpuThrottling==='undefined'){options.flags.disableCpuThrottling=true;}
passes=this.instantiateGatherers(passes,options.config.configDir);const gathererResults={};return driver.connect().then(_=>GatherRunner.loadBlank(driver)).then(_=>GatherRunner.setupDriver(driver,options)).then(_=>{let urlAfterRedirects;return passes.reduce((chain,config,passIndex)=>{const runOptions=Object.assign({},options,{config});return chain.then(_=>GatherRunner.beforePass(runOptions,gathererResults)).then(_=>GatherRunner.pass(runOptions,gathererResults)).then(_=>GatherRunner.afterPass(runOptions,gathererResults)).then(passData=>{const passName=config.passName||Audit.DEFAULT_PASS;config.recordTrace&&(tracingData.traces[passName]=passData.trace);config.recordNetwork&&(tracingData.networkRecords[passName]=passData.networkRecords);if(passIndex===0){urlAfterRedirects=runOptions.url;}});},Promise.resolve()).then(_=>{options.url=urlAfterRedirects;});}).then(_=>GatherRunner.disposeDriver(driver)).then(_=>GatherRunner.collectArtifacts(gathererResults)).then(artifacts=>{const computedArtifacts=this.instantiateComputedArtifacts();Object.assign(artifacts,computedArtifacts,tracingData);return artifacts;}).catch(err=>{GatherRunner.disposeDriver(driver);throw err;});}
static getGathererClass(nameOrGathererClass,configPath){const Runner=require('../runner');const coreList=Runner.getGathererList();let GathererClass;if(typeof nameOrGathererClass==='string'){const name=nameOrGathererClass;const coreGatherer=coreList.find(a=>a===`${name}.js`);let requirePath=`./gatherers/${name}`;if(!coreGatherer){requirePath=Runner.resolvePlugin(name,configPath,'gatherer');}
GathererClass=require(requirePath);this.assertValidGatherer(GathererClass,name);}else{GathererClass=nameOrGathererClass;this.assertValidGatherer(GathererClass);}
return GathererClass;}
static assertValidGatherer(GathererDefinition,gathererName){const gathererInstance=new GathererDefinition();gathererName=gathererName||gathererInstance.name||'gatherer';if(typeof gathererInstance.beforePass!=='function'){throw new Error(`${gathererName} has no beforePass() method.`);}
if(typeof gathererInstance.pass!=='function'){throw new Error(`${gathererName} has no pass() method.`);}
if(typeof gathererInstance.afterPass!=='function'){throw new Error(`${gathererName} has no afterPass() method.`);}}
static instantiateComputedArtifacts(){const computedArtifacts={};["computed-artifact.js","critical-request-chains.js","pushed-requests.js","screenshots.js","speedline.js"].forEach(function(file){file=file.replace(/\.js$/,'');const ArtifactClass=require('./computed/'+file);const artifact=new ArtifactClass();computedArtifacts['request'+artifact.name]=artifact.request.bind(artifact);});return computedArtifacts;}
static instantiateGatherers(passes,rootPath){return passes.map(pass=>{pass.gatherers=pass.gatherers.map(gatherer=>{if(typeof gatherer!=='string'){return gatherer;}
const GathererClass=GatherRunner.getGathererClass(gatherer,rootPath);return new GathererClass();});return pass;});}}
module.exports=GatherRunner;},{"../audits/audit":3,"../lib/log.js":24,"../runner":33,"path":204}],18:[function(require,module,exports){'use strict';class Gatherer{get name(){return this.constructor.name;}
beforePass(options){}
pass(options){}
afterPass(options,loadData){}}
module.exports=Gatherer;},{}],19:[function(require,module,exports){'use strict';const log=require('./log.js');class ConsoleQuieter{static mute(opts){ConsoleQuieter._logs=ConsoleQuieter._logs||[];console.log=function(){ConsoleQuieter._logs.push({type:'log',args:arguments,prefix:opts.prefix});};console.warn=function(){ConsoleQuieter._logs.push({type:'warn',args:arguments,prefix:opts.prefix});};console.error=function(){ConsoleQuieter._logs.push({type:'error',args:arguments,prefix:opts.prefix});};}
static unmuteAndFlush(){console.log=ConsoleQuieter._consolelog;console.warn=ConsoleQuieter._consolewarn;console.error=ConsoleQuieter._consoleerror;ConsoleQuieter._logs.forEach(entry=>{log.verbose(`${entry.prefix}-${entry.type}`,...entry.args);});ConsoleQuieter._logs=[];}}
ConsoleQuieter._consolelog=console.log.bind(console);ConsoleQuieter._consolewarn=console.warn.bind(console);ConsoleQuieter._consoleerror=console.error.bind(console);module.exports=ConsoleQuieter;},{"./log.js":24}],20:[function(require,module,exports){'use strict';class Element{constructor(element,driver){if(!element||!driver){throw Error('Driver and element required to create Element');}
this.driver=driver;this.element=element;}
getAttribute(name){return this.driver.sendCommand('DOM.getAttributes',{nodeId:this.element.nodeId}).then(resp=>{const attrIndex=resp.attributes.indexOf(name);if(attrIndex===-1){return null;}
return resp.attributes[attrIndex+1];});}
getProperty(propName){return this.driver.sendCommand('DOM.resolveNode',{nodeId:this.element.nodeId}).then(resp=>{return this.driver.getObjectProperty(resp.object.objectId,propName);});}}
module.exports=Element;},{}],21:[function(require,module,exports){'use strict';const NEXUS5X_EMULATION_METRICS={mobile:true,screenWidth:412,screenHeight:732,width:412,height:732,positionX:0,positionY:0,scale:1,deviceScaleFactor:2.625,fitWindow:false,screenOrientation:{angle:0,type:'portraitPrimary'}};const NEXUS5X_USERAGENT={userAgent:'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5 Build/MRA58N) AppleWebKit/537.36'+'(KHTML, like Gecko) Chrome/52.0.2743.8 Mobile Safari/537.36'};const TYPICAL_MOBILE_THROTTLING_METRICS={latency:150,downloadThroughput:Math.floor(1.6*1024*1024/8),uploadThroughput:Math.floor(750*1024/8),offline:false};const OFFLINE_METRICS={offline:true,latency:0,downloadThroughput:0,uploadThroughput:0};const NO_THROTTLING_METRICS={latency:0,downloadThroughput:0,uploadThroughput:0,offline:false};const NO_CPU_THROTTLE_METRICS={rate:1};const CPU_THROTTLE_METRICS={rate:5};function enableNexus5X(driver){const injectedTouchEventsFunction=function(){const touchEvents=['ontouchstart','ontouchend','ontouchmove','ontouchcancel'];const recepients=[window.__proto__,document.__proto__];for(let i=0;i<touchEvents.length;++i){for(let j=0;j<recepients.length;++j){if(!(touchEvents[i]in recepients[j])){Object.defineProperty(recepients[j],touchEvents[i],{value:null,writable:true,configurable:true,enumerable:true});}}}};return Promise.all([driver.sendCommand('Emulation.setDeviceMetricsOverride',NEXUS5X_EMULATION_METRICS),driver.sendCommand('Network.enable'),driver.sendCommand('Network.setUserAgentOverride',NEXUS5X_USERAGENT),driver.sendCommand('Emulation.setTouchEmulationEnabled',{enabled:true,configuration:'mobile'}),driver.sendCommand('Page.addScriptToEvaluateOnLoad',{scriptSource:'('+injectedTouchEventsFunction.toString()+')()'})]);}
function enableNetworkThrottling(driver){return driver.sendCommand('Network.emulateNetworkConditions',TYPICAL_MOBILE_THROTTLING_METRICS);}
function disableNetworkThrottling(driver){return driver.sendCommand('Network.emulateNetworkConditions',NO_THROTTLING_METRICS);}
function goOffline(driver){return driver.sendCommand('Network.emulateNetworkConditions',OFFLINE_METRICS);}
function enableCPUThrottling(driver){return driver.sendCommand('Emulation.setCPUThrottlingRate',CPU_THROTTLE_METRICS);}
function disableCPUThrottling(driver){return driver.sendCommand('Emulation.setCPUThrottlingRate',NO_CPU_THROTTLE_METRICS);}
module.exports={enableNexus5X,enableNetworkThrottling,disableNetworkThrottling,enableCPUThrottling,disableCPUThrottling,goOffline};},{}],22:[function(require,module,exports){'use strict';function addFormattedCodeSnippet(listener){const handler=listener.handler?listener.handler.description:'...';const objectName=listener.objectName.toLowerCase().replace('#document','document');return Object.assign({label:`line: ${listener.line}, col: ${listener.col}`,code:`${objectName}.addEventListener('${listener.type}', ${handler})`},listener);}
function groupCodeSnippetsByLocation(listeners){const locToListenersMap=new Map();listeners.forEach(loc=>{const key=JSON.stringify({line:loc.line,col:loc.col,url:loc.url,type:loc.type});if(locToListenersMap.has(key)){locToListenersMap.get(key).push(loc);}else{locToListenersMap.set(key,[loc]);}});const results=[];locToListenersMap.forEach((listenersForLocation,key)=>{const lineColUrlObj=JSON.parse(key);const codeSnippets=listenersForLocation.reduce((prev,loc)=>{return prev+loc.code.trim()+'\n\n';},'');lineColUrlObj.code=codeSnippets;lineColUrlObj.label=listenersForLocation[0].label;results.push(lineColUrlObj);});return results;}
module.exports={addFormattedCodeSnippet,groupCodeSnippetsByLocation};},{}],23:[function(require,module,exports){'use strict';function doExist(manifest){if(!manifest||!manifest.icons){return false;}
if(manifest.icons.value.length===0){return false;}
return true;}
function sizeAtLeast(sizeRequirement,manifest){const iconValues=manifest.icons.value;const nestedSizes=iconValues.map(icon=>icon.value.sizes.value);const flattenedSizes=[].concat(...nestedSizes);return flattenedSizes.filter(size=>typeof size==='string').filter(size=>/\d+x\d+/.test(size)).filter(size=>{const sizeStrs=size.split(/x/i);const sizeNums=[parseFloat(sizeStrs[0]),parseFloat(sizeStrs[1])];const areIconsBigEnough=sizeNums[0]>=sizeRequirement&&sizeNums[1]>=sizeRequirement;const areIconsSquare=sizeNums[0]===sizeNums[1];return areIconsBigEnough&&areIconsSquare;});}
module.exports={doExist,sizeAtLeast};},{}],24:[function(require,module,exports){(function(process){'use strict';const debug=require('debug');const EventEmitter=require('events').EventEmitter;const isWindows=process.platform==='win32';const isBrowser=process.browser;const colors={red:isBrowser?'crimson':1,yellow:isBrowser?'gold':3,cyan:isBrowser?'darkturquoise':6,green:isBrowser?'forestgreen':2,blue:isBrowser?'steelblue':4,magenta:isBrowser?'palevioletred':5};debug.colors=[colors.cyan,colors.green,colors.blue,colors.magenta];class Emitter extends EventEmitter{issueStatus(title,args){if(title==='status'||title==='statusEnd'){this.emit(title,args);}}
issueWarning(args){this.emit('warning',args);}}
const loggersByTitle={};const loggingBufferColumns=25;class Log{static _logToStdErr(title,argsArray){const args=[...argsArray];const log=Log.loggerfn(title);log(...args);}
static loggerfn(title){let log=loggersByTitle[title];if(!log){log=debug(title);loggersByTitle[title]=log;if(title.endsWith('error')){log.color=colors.red;}else if(title.endsWith('warn')){log.color=colors.yellow;}}
return log;}
static setLevel(level){switch(level){case'silent':debug.disable();break;case'verbose':debug.enable('*');break;case'error':debug.enable('*:error');break;default:debug.enable('*, -*:verbose');}}
static formatProtocol(prefix,data,level){const columns=(!process||process.browser)?Infinity:process.stdout.columns;const maxLength=columns-data.method.length-prefix.length-loggingBufferColumns;const snippet=(data.params&&data.method!=='IO.read')?JSON.stringify(data.params).substr(0,maxLength):'';Log._logToStdErr(`${prefix}:${level || ''}`,[data.method,snippet]);}
static log(title){Log.events.issueStatus(title,arguments);return Log._logToStdErr(title,Array.from(arguments).slice(1));}
static warn(title){Log.events.issueWarning(arguments);return Log._logToStdErr(`${title}:warn`,Array.from(arguments).slice(1));}
static error(title){return Log._logToStdErr(`${title}:error`,Array.from(arguments).slice(1));}
static verbose(title){Log.events.issueStatus(title);return Log._logToStdErr(`${title}:verbose`,Array.from(arguments).slice(1));}
static greenify(str){return`${Log.green}${str}${Log.reset}`;}
static redify(str){return`${Log.red}${str}${Log.reset}`;}
static get green(){return'\x1B[32m';}
static get red(){return'\x1B[31m';}
static get yellow(){return'\x1b[33m';}
static get purple(){return'\x1b[95m';}
static get reset(){return'\x1B[0m';}
static get bold(){return'\x1b[1m';}
static get tick(){return isWindows?'\u221A':'✓';}
static get cross(){return isWindows?'\u00D7':'✘';}
static get whiteSmallSquare(){return isWindows?'\u0387':'▫';}
static get doubleLightHorizontal(){return'──';}}
Log.events=new Emitter();module.exports=Log;}).call(this,require('_process'))},{"_process":205,"debug":234,"events":201}],25:[function(require,module,exports){'use strict';const URL=require('./url-shim');const validateColor=require('./web-inspector').Color.parse;const ALLOWED_DISPLAY_VALUES=['fullscreen','standalone','minimal-ui','browser'];const DEFAULT_DISPLAY_MODE='browser';const ALLOWED_ORIENTATION_VALUES=['any','natural','landscape','portrait','portrait-primary','portrait-secondary','landscape-primary','landscape-secondary'];function parseString(raw,trim){let value;let debugString;if(typeof raw==='string'){value=trim?raw.trim():raw;}else{if(raw!==undefined){debugString='ERROR: expected a string.';}
value=undefined;}
return{raw,value,debugString};}
function parseColor(raw){const color=parseString(raw);if(color.value===undefined){return color;}
const validatedColor=validateColor(color.raw);if(!validatedColor){color.value=undefined;color.debugString='ERROR: color parsing failed.';}
return color;}
function parseName(jsonInput){return parseString(jsonInput.name,true);}
function parseShortName(jsonInput){return parseString(jsonInput.short_name,true);}
function checkSameOrigin(url1,url2){const parsed1=new URL(url1);const parsed2=new URL(url2);return parsed1.origin===parsed2.origin;}
function parseStartUrl(jsonInput,manifestUrl,documentUrl){const raw=jsonInput.start_url;if(raw===''){return{raw,value:documentUrl,debugString:'ERROR: start_url string empty'};}
const parsedAsString=parseString(raw);if(!parsedAsString.value){parsedAsString.value=documentUrl;return parsedAsString;}
let startUrl;try{startUrl=new URL(raw,manifestUrl).href;}catch(e){return{raw,value:documentUrl,debugString:'ERROR: invalid start_url relative to ${manifestUrl}'};}
if(!checkSameOrigin(startUrl,documentUrl)){return{raw,value:documentUrl,debugString:'ERROR: start_url must be same-origin as document'};}
return{raw,value:startUrl};}
function parseDisplay(jsonInput){const display=parseString(jsonInput.display,true);if(!display.value){display.value=DEFAULT_DISPLAY_MODE;return display;}
display.value=display.value.toLowerCase();if(ALLOWED_DISPLAY_VALUES.indexOf(display.value)===-1){display.debugString='ERROR: \'display\' has invalid value '+display.value+` will fall back to ${DEFAULT_DISPLAY_MODE}.`;display.value=DEFAULT_DISPLAY_MODE;}
return display;}
function parseOrientation(jsonInput){const orientation=parseString(jsonInput.orientation,true);if(orientation.value&&ALLOWED_ORIENTATION_VALUES.indexOf(orientation.value.toLowerCase())===-1){orientation.value=undefined;orientation.debugString='ERROR: \'orientation\' has an invalid value, will be ignored.';}
return orientation;}
function parseIcon(raw,manifestUrl){const src=parseString(raw.src,true);if(src.value===''){src.value=undefined;}
if(src.value){src.value=new URL(src.value,manifestUrl).href;}
const type=parseString(raw.type,true);const density={raw:raw.density,value:1,debugString:undefined};if(density.raw!==undefined){density.value=parseFloat(density.raw);if(isNaN(density.value)||!isFinite(density.value)||density.value<=0){density.value=1;density.debugString='ERROR: icon density cannot be NaN, +∞, or less than or equal to +0.';}}
const sizes=parseString(raw.sizes);if(sizes.value!==undefined){const set=new Set();sizes.value.trim().split(/\s+/).forEach(size=>set.add(size.toLowerCase()));sizes.value=set.size>0?Array.from(set):undefined;}
return{raw,value:{src,type,density,sizes},debugString:undefined};}
function parseIcons(jsonInput,manifestUrl){const raw=jsonInput.icons;if(raw===undefined){return{raw,value:[],debugString:undefined};}
if(!Array.isArray(raw)){return{raw,value:[],debugString:'ERROR: \'icons\' expected to be an array but is not.'};}
const value=raw.filter(icon=>icon.src!==undefined).map(icon=>parseIcon(icon,manifestUrl)).filter(parsedIcon=>parsedIcon.value.src.value!==undefined);return{raw,value,debugString:undefined};}
function parseApplication(raw){const platform=parseString(raw.platform,true);const id=parseString(raw.id,true);const appUrl=parseString(raw.url,true);if(appUrl.value){try{appUrl.value=new URL(appUrl.value).href;}catch(e){appUrl.value=undefined;appUrl.debugString='ERROR: invalid application URL ${raw.url}';}}
return{raw,value:{platform,id,url:appUrl},debugString:undefined};}
function parseRelatedApplications(jsonInput){const raw=jsonInput.related_applications;if(raw===undefined){return{raw,value:undefined,debugString:undefined};}
if(!Array.isArray(raw)){return{raw,value:undefined,debugString:'ERROR: \'related_applications\' expected to be an array but is not.'};}
const value=raw.filter(application=>!!application.platform).map(parseApplication).filter(parsedApp=>!!parsedApp.value.id.value||!!parsedApp.value.url.value);return{raw,value,debugString:undefined};}
function parsePreferRelatedApplications(jsonInput){const raw=jsonInput.prefer_related_applications;let value;let debugString;if(typeof raw==='boolean'){value=raw;}else{if(raw!==undefined){debugString='ERROR: \'prefer_related_applications\' expected to be a boolean.';}
value=undefined;}
return{raw,value,debugString};}
function parseThemeColor(jsonInput){return parseColor(jsonInput.theme_color);}
function parseBackgroundColor(jsonInput){return parseColor(jsonInput.background_color);}
function parse(string,manifestUrl,documentUrl){if(manifestUrl===undefined||documentUrl===undefined){throw new Error('Manifest and document URLs required for manifest parsing.');}
let jsonInput;try{jsonInput=JSON.parse(string);}catch(e){return{raw:string,value:undefined,debugString:'ERROR: file isn\'t valid JSON: '+e};}
const manifest={name:parseName(jsonInput),short_name:parseShortName(jsonInput),start_url:parseStartUrl(jsonInput,manifestUrl,documentUrl),display:parseDisplay(jsonInput),orientation:parseOrientation(jsonInput),icons:parseIcons(jsonInput,manifestUrl),related_applications:parseRelatedApplications(jsonInput),prefer_related_applications:parsePreferRelatedApplications(jsonInput),theme_color:parseThemeColor(jsonInput),background_color:parseBackgroundColor(jsonInput)};return{raw:string,value:manifest,debugString:undefined};}
module.exports=parse;},{"./url-shim":30,"./web-inspector":31}],26:[function(require,module,exports){'use strict';const NetworkManager=require('./web-inspector').NetworkManager;const EventEmitter=require('events').EventEmitter;const log=require('../lib/log.js');class NetworkRecorder extends EventEmitter{constructor(recordArray){super();this._records=recordArray;this.networkManager=NetworkManager.createWithFakeTarget();this.startedRequestCount=0;this.finishedRequestCount=0;this.networkManager.addEventListener(this.EventTypes.RequestStarted,this.onRequestStarted.bind(this));this.networkManager.addEventListener(this.EventTypes.RequestFinished,this.onRequestFinished.bind(this));this.onRequestWillBeSent=this.onRequestWillBeSent.bind(this);this.onRequestServedFromCache=this.onRequestServedFromCache.bind(this);this.onResponseReceived=this.onResponseReceived.bind(this);this.onDataReceived=this.onDataReceived.bind(this);this.onLoadingFinished=this.onLoadingFinished.bind(this);this.onLoadingFailed=this.onLoadingFailed.bind(this);this.onResourceChangedPriority=this.onResourceChangedPriority.bind(this);}
get EventTypes(){return NetworkManager.Events;}
activeRequestCount(){return this.startedRequestCount-this.finishedRequestCount;}
isIdle(){return this.activeRequestCount()===0;}
onRequestStarted(){this.startedRequestCount++;const activeCount=this.activeRequestCount();log.verbose('NetworkRecorder',`Request started. ${activeCount} requests in progress`+` (${this.startedRequestCount} started and ${this.finishedRequestCount} finished).`);if(activeCount===1){this.emit('networkbusy');}}
onRequestFinished(request){this.finishedRequestCount++;this._records.push(request.data);this.emit('requestloaded',request.data);const activeCount=this.activeRequestCount();log.verbose('NetworkRecorder',`Request finished. ${activeCount} requests in progress`+` (${this.startedRequestCount} started and ${this.finishedRequestCount} finished).`);if(this.isIdle()){this.emit('networkidle');}}
onRequestWillBeSent(data){this.networkManager._dispatcher.requestWillBeSent(data.requestId,data.frameId,data.loaderId,data.documentURL,data.request,data.timestamp,data.wallTime,data.initiator,data.redirectResponse,data.type);}
onRequestServedFromCache(data){this.networkManager._dispatcher.requestServedFromCache(data.requestId);}
onResponseReceived(data){this.networkManager._dispatcher.responseReceived(data.requestId,data.frameId,data.loaderId,data.timestamp,data.type,data.response);}
onDataReceived(data){this.networkManager._dispatcher.dataReceived(data.requestId,data.timestamp,data.dataLength,data.encodedDataLength);}
onLoadingFinished(data){this.networkManager._dispatcher.loadingFinished(data.requestId,data.timestamp,data.encodedDataLength);}
onLoadingFailed(data){this.networkManager._dispatcher.loadingFailed(data.requestId,data.timestamp,data.type,data.errorText,data.canceled,data.blockedReason);}
onResourceChangedPriority(data){this.networkManager._dispatcher.resourceChangedPriority(data.requestId,data.newPriority,data.timestamp);}
static recordsFromLogs(logs){const records=[];const nr=new NetworkRecorder(records);const dispatcher=method=>{switch(method){case'Network.requestWillBeSent':return nr.onRequestWillBeSent;case'Network.requestServedFromCache':return nr.onRequestServedFromCache;case'Network.responseReceived':return nr.onResponseReceived;case'Network.dataReceived':return nr.onDataReceived;case'Network.loadingFinished':return nr.onLoadingFinished;case'Network.loadingFailed':return nr.onLoadingFailed;case'Network.resourceChangedPriority':return nr.onResourceChangedPriority;default:return()=>{};}};logs.forEach(networkEvent=>{dispatcher(networkEvent.method)(networkEvent.params);});return records;}}
module.exports=NetworkRecorder;},{"../lib/log.js":24,"./web-inspector":31,"events":201}],27:[function(require,module,exports){'use strict';function filterStylesheetsByUsage(stylesheets,propName,propVal){if(!propName&&!propVal){return[];}
const deepClone=stylesheets.map(sheet=>Object.assign({},sheet));return deepClone.filter(s=>{if(s.isDuplicate){return false;}
s.parsedContent=s.parsedContent.filter(item=>{let usedName='';let usedVal='';if(propName){propName=Array.isArray(propName)?propName:[propName];usedName=propName.indexOf(item.property.name)>-1;}
if(propVal){propVal=Array.isArray(propVal)?propVal:[propVal];usedVal=propVal.indexOf(item.property.val)>-1;}
if(propName&&!propVal){return usedName;}else if(!propName&&propVal){return usedVal;}else if(propName&&propVal){return usedName&&usedVal;}
return false;});return s.parsedContent.length>0;});}
function getFormattedStyleRule(content,parsedContent){const lines=content.split('\n');const declarationRange=parsedContent.declarationRange;const startLine=declarationRange.startLine;const endLine=declarationRange.endLine;const start=declarationRange.startColumn;const end=declarationRange.endColumn;let rule;if(startLine===endLine){rule=lines[startLine].substring(start,end);}else{rule=lines.slice(startLine,endLine+1).reduce((prev,line)=>{prev.push(line);return prev;},[]).join('\n');}
const block=`
${parsedContent.selector} {
  ${rule}
}`;return{styleRule:block.trim(),location:`line: ${startLine}, row: ${start}, col: ${end}`};}
function addVendorPrefixes(propsNames){const vendorPrefixes=['-o-','-ms-','-moz-','-webkit-'];propsNames=Array.isArray(propsNames)?propsNames:[propsNames];let propsNamesWithPrefixes=propsNames;for(const prefix of vendorPrefixes){const temp=propsNames.map(propName=>`${prefix}${propName}`);propsNamesWithPrefixes=propsNamesWithPrefixes.concat(temp);}
return propsNamesWithPrefixes;}
module.exports={filterStylesheetsByUsage,getFormattedStyleRule,addVendorPrefixes};},{}],28:[function(require,module,exports){'use strict';const WebInspector=require('../web-inspector');const ConsoleQuieter=require('../console-quieter');const TimelineModelTreeView=require('devtools-timeline-model/lib/timeline-model-treeview.js')(WebInspector);class TimelineModel{constructor(events){this.init(events);}
init(events){this._tracingModel=new WebInspector.TracingModel(new WebInspector.TempFileBackingStorage('tracing'));this._timelineModel=new WebInspector.TimelineModel(WebInspector.TimelineUIUtils.visibleEventsFilter());if(typeof events==='string'){events=JSON.parse(events);}
if(events.hasOwnProperty('traceEvents')){events=events.traceEvents;}
this._tracingModel.reset();ConsoleQuieter.mute({prefix:'timelineModel'});this._tracingModel.addEvents(events);this._tracingModel.tracingComplete();this._timelineModel.setEvents(this._tracingModel);ConsoleQuieter.unmuteAndFlush();return this;}
_createAggregator(){return WebInspector.AggregatedTimelineTreeView.prototype._createAggregator();}
timelineModel(){return this._timelineModel;}
tracingModel(){return this._tracingModel;}
topDown(){const filters=[];filters.push(WebInspector.TimelineUIUtils.visibleEventsFilter());filters.push(new WebInspector.ExcludeTopLevelFilter());const nonessentialEvents=[WebInspector.TimelineModel.RecordType.EventDispatch,WebInspector.TimelineModel.RecordType.FunctionCall,WebInspector.TimelineModel.RecordType.TimerFire];filters.push(new WebInspector.ExclusiveNameFilter(nonessentialEvents));const topDown=WebInspector.TimelineProfileTree.buildTopDown(this._timelineModel.mainThreadEvents(),filters,0,Infinity,WebInspector.TimelineAggregator.eventId);return topDown;}
bottomUp(){const topDown=this.topDown();const noGrouping=WebInspector.TimelineAggregator.GroupBy.None;const noGroupAggregator=this._createAggregator().groupFunction(noGrouping);return WebInspector.TimelineProfileTree.buildBottomUp(topDown,noGroupAggregator);}
bottomUpGroupBy(grouping){const topDown=this.topDown();const groupSetting=WebInspector.TimelineAggregator.GroupBy[grouping];const groupingAggregator=this._createAggregator().groupFunction(groupSetting);const bottomUpGrouped=WebInspector.TimelineProfileTree.buildBottomUp(topDown,groupingAggregator);new TimelineModelTreeView(bottomUpGrouped).sortingChanged('self','desc');return bottomUpGrouped;}
frameModel(){const frameModel=new WebInspector.TimelineFrameModel(event=>WebInspector.TimelineUIUtils.eventStyle(event).category.name);frameModel.addTraceEvents({},this._timelineModel.inspectedTargetEvents(),this._timelineModel.sessionId()||'');return frameModel;}
filmStripModel(){return new WebInspector.FilmStripModel(this._tracingModel);}
interactionModel(){const irModel=new WebInspector.TimelineIRModel();irModel.populate(this._timelineModel);return irModel;}}
module.exports=TimelineModel;},{"../console-quieter":19,"../web-inspector":31,"devtools-timeline-model/lib/timeline-model-treeview.js":236}],29:[function(require,module,exports){(function(global){'use strict';if(typeof global.window==='undefined'){global.window=global;}
const BASE_RESPONSE_LATENCY=16;const glMatrixModule=require('gl-matrix');Object.keys(glMatrixModule).forEach(exportName=>{global[exportName]=glMatrixModule[exportName];});global.JSZip={};global.mannwhitneyu={};global.HTMLImportsLoader={};global.HTMLImportsLoader.hrefToAbsolutePath=function(path){if(path==='/gl-matrix-min.js'){return'../../../lib/empty-stub.js';}
if(path==='/jszip.min.js'){return'../../../lib/empty-stub.js';}
if(path==='/mannwhitneyu.js'){return'../../../lib/empty-stub.js';}};require('../../third_party/traceviewer-js/');const traceviewer=global.tr;class TraceProcessor{get RESPONSE(){return'Response';}
get ANIMATION(){return'Animation';}
get LOAD(){return'Load';}
init(trace){const io=new traceviewer.importer.ImportOptions();io.showImportWarnings=false;io.pruneEmptyContainers=false;io.shiftWorldToZero=true;const model=new traceviewer.Model();const importer=new traceviewer.importer.Import(model,io);importer.importTraces([trace]);return model;}
static _findMainThreadFromIds(model,processId,threadId){const modelHelper=model.getOrCreateHelper(traceviewer.model.helpers.ChromeModelHelper);const renderHelpers=traceviewer.b.dictionaryValues(modelHelper.rendererHelpers);const mainThread=renderHelpers.find(helper=>{return helper.mainThread&&helper.pid===processId&&helper.mainThread.tid===threadId;}).mainThread;return mainThread;}
static _riskPercentiles(durations,totalTime,percentiles,clippedLength){clippedLength=clippedLength||0;let busyTime=0;for(let i=0;i<durations.length;i++){busyTime+=durations[i];}
busyTime-=clippedLength;let completedTime=totalTime-busyTime;let duration=0;let cdfTime=completedTime;const results=[];let durationIndex=-1;let remainingCount=durations.length+1;if(clippedLength>0){remainingCount--;}
for(const percentile of percentiles){const percentileTime=percentile*totalTime;while(cdfTime<percentileTime&&durationIndex<durations.length-1){completedTime+=duration;remainingCount-=(duration<0?-1:1);if(clippedLength>0&&clippedLength<durations[durationIndex+1]){duration=-clippedLength;clippedLength=0;}else{durationIndex++;duration=durations[durationIndex];}
cdfTime=completedTime+Math.abs(duration)*remainingCount;}
results.push({percentile,time:Math.max(0,(percentileTime-completedTime)/remainingCount)+BASE_RESPONSE_LATENCY});}
return results;}
static getRiskToResponsiveness(model,trace,startTime,endTime,percentiles){startTime=startTime===undefined?model.bounds.min:startTime;endTime=endTime===undefined?model.bounds.max:endTime;const totalTime=endTime-startTime;if(percentiles){percentiles.sort((a,b)=>a-b);}else{percentiles=[0.5,0.75,0.9,0.99,1];}
const ret=TraceProcessor.getMainThreadTopLevelEventDurations(model,trace,startTime,endTime);return TraceProcessor._riskPercentiles(ret.durations,totalTime,percentiles,ret.clippedLength);}
static getMainThreadTopLevelEventDurations(model,trace,startTime,endTime){const startEvent=trace.traceEvents.find(event=>{return event.name==='TracingStartedInPage';});const mainThread=TraceProcessor._findMainThreadFromIds(model,startEvent.pid,startEvent.tid);const durations=[];let clippedLength=0;mainThread.sliceGroup.topLevelSlices.forEach(slice=>{if(slice.end<=startTime||slice.start>=endTime){return;}
let duration=slice.duration;let sliceStart=slice.start;if(sliceStart<startTime){sliceStart=startTime;duration=slice.end-sliceStart;}
if(slice.end>endTime){clippedLength=duration-(endTime-sliceStart);}
durations.push(duration);});durations.sort((a,b)=>a-b);return{durations,clippedLength};}
static getLogNormalDistribution(median,falloff){const location=Math.log(median);const logRatio=Math.log(falloff/median);const shape=0.5*Math.sqrt(1-3*logRatio-
Math.sqrt((logRatio-3)*(logRatio-3)-8));return new traceviewer.b.Statistics.LogNormalDistribution(location,shape);}}
module.exports=TraceProcessor;}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../../third_party/traceviewer-js/":85,"gl-matrix":237}],30:[function(require,module,exports){'use strict';const URL=(typeof self!=='undefined'&&self.URL)||require('whatwg-url').URL;URL.INVALID_URL_DEBUG_STRING='Lighthouse was unable to determine the URL of some script executions. '+'It\'s possible a Chrome extension or other eval\'d code is the source.';URL.isValid=function isValid(url){try{new URL(url);return true;}catch(e){return false;}};URL.hostsMatch=function hostsMatch(urlA,urlB){try{return new URL(urlA).host===new URL(urlB).host;}catch(e){return false;}};URL.getDisplayName=function getDisplayName(url){const parsed=new URL(url);let name=parsed.protocol==='about:'?parsed.href:parsed.pathname.replace(/\?.*/,'').split('/').slice(-2).join('/');const MAX_LENGTH=64;name=name.replace(/([a-f0-9]{7})[a-f0-9]{13}[a-f0-9]*/g,'$1\u2026');if(name.length>MAX_LENGTH){const dotIndex=name.lastIndexOf('.');name=name.slice(0,MAX_LENGTH-1-(name.length-dotIndex))+`\u2026${name.slice(dotIndex)}`;}
return name;};module.exports=URL;},{"whatwg-url":199}],31:[function(require,module,exports){(function(global){'use strict';module.exports=(function(){if(global.WebInspector){return global.WebInspector;}
if(global.self!==global){global.self=global;}
if(typeof global.window==='undefined'){global.window=global;}
global.Runtime={};global.Runtime.experiments={isEnabled(experimentName){switch(experimentName){case'timelineLatencyInfo':return true;default:return false;}}};global.Runtime.queryParam=function(arg){switch(arg){case'remoteFrontend':return false;case'ws':return false;default:throw Error('Mock queryParam case not implemented.');}};global.TreeElement={};global.WorkerRuntime={};global.Protocol={Agents(){}};global.WebInspector={};const WebInspector=global.WebInspector;WebInspector._moduleSettings={cacheDisabled:{addChangeListener(){},get(){return false;}},monitoringXHREnabled:{addChangeListener(){},get(){return false;}},showNativeFunctionsInJSProfile:{addChangeListener(){},get(){return true;}}};WebInspector.moduleSetting=function(settingName){return this._moduleSettings[settingName];};global.NetworkAgent={RequestMixedContentType:{Blockable:'blockable',OptionallyBlockable:'optionally-blockable',None:'none'},BlockedReason:{CSP:'csp',MixedContent:'mixed-content',Origin:'origin',Inspector:'inspector',Other:'other'},InitiatorType:{Other:'other',Parser:'parser',Redirect:'redirect',Script:'script'}};global.SecurityAgent={SecurityState:{Unknown:'unknown',Neutral:'neutral',Insecure:'insecure',Warning:'warning',Secure:'secure',Info:'info'}};global.PageAgent={ResourceType:{Document:'document',Stylesheet:'stylesheet',Image:'image',Media:'media',Font:'font',Script:'script',TextTrack:'texttrack',XHR:'xhr',Fetch:'fetch',EventSource:'eventsource',WebSocket:'websocket',Manifest:'manifest',Other:'other'}};require('chrome-devtools-frontend/front_end/common/Object.js');require('chrome-devtools-frontend/front_end/common/ParsedURL.js');require('chrome-devtools-frontend/front_end/common/ResourceType.js');require('chrome-devtools-frontend/front_end/common/UIString.js');require('chrome-devtools-frontend/front_end/platform/utilities.js');require('chrome-devtools-frontend/front_end/sdk/Target.js');require('chrome-devtools-frontend/front_end/sdk/TargetManager.js');require('chrome-devtools-frontend/front_end/sdk/NetworkManager.js');require('chrome-devtools-frontend/front_end/sdk/NetworkRequest.js');WebInspector.targetManager={observeTargets(){},addEventListener(){}};WebInspector.settings={createSetting(){return{get(){return false;},addChangeListener(){}};}};WebInspector.console={error(){}};WebInspector.VBox=function(){};WebInspector.HBox=function(){};WebInspector.ViewportDataGrid=function(){};WebInspector.ViewportDataGridNode=function(){};global.WorkerRuntime.Worker=function(){};require('chrome-devtools-frontend/front_end/common/SegmentedRange.js');require('chrome-devtools-frontend/front_end/bindings/TempFile.js');require('chrome-devtools-frontend/front_end/sdk/TracingModel.js');require('chrome-devtools-frontend/front_end/sdk/ProfileTreeModel.js');require('chrome-devtools-frontend/front_end/timeline/TimelineUIUtils.js');require('chrome-devtools-frontend/front_end/timeline_model/TimelineJSProfile.js');require('chrome-devtools-frontend/front_end/sdk/CPUProfileDataModel.js');require('chrome-devtools-frontend/front_end/timeline_model/LayerTreeModel.js');require('chrome-devtools-frontend/front_end/timeline_model/TimelineModel.js');require('chrome-devtools-frontend/front_end/ui_lazy/SortableDataGrid.js');require('chrome-devtools-frontend/front_end/timeline/TimelineTreeView.js');require('chrome-devtools-frontend/front_end/timeline_model/TimelineProfileTree.js');require('chrome-devtools-frontend/front_end/components_lazy/FilmStripModel.js');require('chrome-devtools-frontend/front_end/timeline_model/TimelineIRModel.js');require('chrome-devtools-frontend/front_end/timeline_model/TimelineFrameModel.js');WebInspector.DeferredTempFile=function(){};WebInspector.DeferredTempFile.prototype={write:function(){},finishWriting:function(){}};WebInspector.ConsoleMessage=function(){};WebInspector.ConsoleMessage.MessageSource={Network:'network'};WebInspector.ConsoleMessage.MessageLevel={Log:'log'};WebInspector.ConsoleMessage.MessageType={Log:'log'};WebInspector.NetworkLog=function(target){this._requests=new Map();target.networkManager.addEventListener(WebInspector.NetworkManager.Events.RequestStarted,this._onRequestStarted,this);};WebInspector.NetworkLog.prototype={requestForURL:function(url){return this._requests.get(url)||null;},_onRequestStarted:function(event){const request=event.data;if(this._requests.has(request.url)){return;}
this._requests.set(request.url,request);}};require('chrome-devtools-frontend/front_end/common/Color.js');WebInspector.NetworkManager.createWithFakeTarget=function(){const fakeNetworkAgent={enable(){}};const fakeConsoleModel={addMessage(){},target(){}};const fakeTarget={_modelByConstructor:new Map(),get consoleModel(){return fakeConsoleModel;},networkAgent(){return fakeNetworkAgent;},registerNetworkDispatcher(){},model(){}};fakeTarget.networkManager=new WebInspector.NetworkManager(fakeTarget);fakeTarget.networkLog=new WebInspector.NetworkLog(fakeTarget);WebInspector.NetworkLog.fromTarget=()=>{return fakeTarget.networkLog;};return fakeTarget.networkManager;};require('chrome-devtools-frontend/front_end/common/TextRange.js');const gonzales=require('chrome-devtools-frontend/front_end/gonzales/gonzales-scss.js');require('chrome-devtools-frontend/front_end/gonzales/SCSSParser.js');WebInspector.SCSSParser.prototype.parse=function(content){let ast=null;try{ast=gonzales.parse(content,{syntax:'css'});}catch(e){return{error:e};}
const rootBlock={properties:[],node:ast};const blocks=[rootBlock];ast.selectors=[];WebInspector.SCSSParser.extractNodes(ast,blocks,rootBlock);return ast;};return WebInspector;})();}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"chrome-devtools-frontend/front_end/bindings/TempFile.js":206,"chrome-devtools-frontend/front_end/common/Color.js":207,"chrome-devtools-frontend/front_end/common/Object.js":208,"chrome-devtools-frontend/front_end/common/ParsedURL.js":209,"chrome-devtools-frontend/front_end/common/ResourceType.js":210,"chrome-devtools-frontend/front_end/common/SegmentedRange.js":211,"chrome-devtools-frontend/front_end/common/TextRange.js":212,"chrome-devtools-frontend/front_end/common/UIString.js":213,"chrome-devtools-frontend/front_end/components_lazy/FilmStripModel.js":214,"chrome-devtools-frontend/front_end/gonzales/SCSSParser.js":215,"chrome-devtools-frontend/front_end/gonzales/gonzales-scss.js":216,"chrome-devtools-frontend/front_end/platform/utilities.js":217,"chrome-devtools-frontend/front_end/sdk/CPUProfileDataModel.js":218,"chrome-devtools-frontend/front_end/sdk/NetworkManager.js":219,"chrome-devtools-frontend/front_end/sdk/NetworkRequest.js":220,"chrome-devtools-frontend/front_end/sdk/ProfileTreeModel.js":221,"chrome-devtools-frontend/front_end/sdk/Target.js":222,"chrome-devtools-frontend/front_end/sdk/TargetManager.js":223,"chrome-devtools-frontend/front_end/sdk/TracingModel.js":224,"chrome-devtools-frontend/front_end/timeline/TimelineTreeView.js":225,"chrome-devtools-frontend/front_end/timeline/TimelineUIUtils.js":226,"chrome-devtools-frontend/front_end/timeline_model/LayerTreeModel.js":227,"chrome-devtools-frontend/front_end/timeline_model/TimelineFrameModel.js":228,"chrome-devtools-frontend/front_end/timeline_model/TimelineIRModel.js":229,"chrome-devtools-frontend/front_end/timeline_model/TimelineJSProfile.js":230,"chrome-devtools-frontend/front_end/timeline_model/TimelineModel.js":231,"chrome-devtools-frontend/front_end/timeline_model/TimelineProfileTree.js":232,"chrome-devtools-frontend/front_end/ui_lazy/SortableDataGrid.js":233}],32:[function(require,module,exports){'use strict';const Formatter=require('../formatters/formatter');const Handlebars=require('handlebars');const path=require('path');const marked=require('marked');const RATINGS={GOOD:{label:'good',minScore:75},AVERAGE:{label:'average',minScore:45},POOR:{label:'poor'}};function calculateRating(value){let rating=RATINGS.POOR.label;if(value>=RATINGS.GOOD.minScore){rating=RATINGS.GOOD.label;}else if(value>=RATINGS.AVERAGE.minScore){rating=RATINGS.AVERAGE.label;}
return rating;}
class ReportGenerator{constructor(){const getTotalScore=aggregation=>{return Math.round(aggregation.total*100);};const getItemRating=value=>{if(typeof value==='boolean'){return value?RATINGS.GOOD.label:RATINGS.POOR.label;}
return calculateRating(value);};Handlebars.registerHelper('nameToLink',name=>{return name.toLowerCase().replace(/\s/,'-');});Handlebars.registerHelper('getTotalScore',getTotalScore);Handlebars.registerHelper('getTotalScoreRating',aggregation=>{const totalScore=getTotalScore(aggregation);return calculateRating(totalScore);});Handlebars.registerHelper('getItemRating',getItemRating);Handlebars.registerHelper('shouldShowHelpText',value=>(getItemRating(value)!==RATINGS.GOOD.label));Handlebars.registerHelper('decimal',number=>{if(number&&number.toFixed){return number.toFixed(2);}
return number;});Handlebars.registerHelper('is-bool',value=>(typeof value==='boolean'));Handlebars.registerHelper('not',value=>!value);Handlebars.registerHelper('if_not_eq',function(lhs,rhs,options){if(lhs!==rhs){return options.fn(this);}else{return options.inverse(this);}});Handlebars.registerHelper('and',function(){let arg=false;for(let i=0,n=arguments.length-1;i<n;i++){arg=arguments[i];if(!arg){break;}}
return arg;});Handlebars.registerHelper('sanitize',function(str,opts){const renderer=new marked.Renderer();renderer.link=(href,title,text)=>{title=title||text;return`<a href="${href}" target="_blank" rel="noopener" title="${title}">${text}</a>`;};renderer.codespan=function(str){return`<code>${str}</code>`;};renderer.paragraph=function(str){return str;};try{str=marked(str,{renderer,sanitize:true});}catch(e){}
return new Handlebars.SafeString(str);});}
_formatTime(date){const options={day:'numeric',month:'numeric',year:'numeric',hour:'numeric',minute:'numeric',second:'numeric',timeZoneName:'short'};let formatter=new Intl.DateTimeFormat('en-US',options);const tz=formatter.resolvedOptions().timeZone;if(!tz||tz.toLowerCase()==='etc/unknown'){options.timeZone='UTC';formatter=new Intl.DateTimeFormat('en-US',options);}
return formatter.format(new Date(date));}
_escapeScriptTags(jsonStr){return jsonStr.replace(/<\/script>/g,'<\\/script>');}
getReportTemplate(){return"<!--\n\nCopyright 2016 Google Inc. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\n-->\n<!doctype html>\n\n<html data-report-context=\"{{reportContext}}\">\n<head>\n  <meta charset=\"utf-8\">\n  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, minimum-scale=1.0\">\n  <link rel=\"shortcut icon\" href=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAEfElEQVR4Aa2WA5B0RxDH/z3zuDp/tq2Lbdu2XUoxKMW2bdu2nZxte/dpplO3hTjZ2s0z5zftpkVrFXJYGCBAggEoUPY2p0XkOLoJNoE+yH5II3vLOQJyHL0bsgpiC9G1meishuiBzJEhchm9HXIL0fu5e949TuX1cvVbxplbiu6O3BjiP19HEFMpuNI9Z4O8XpIlKb6SbrnQOG0WeQGkKATAgAVdz3Sw/G6BenwoXAnls/JH1IqZ0fN70DeN2Q84b4AA0jBWkHewfXsUh0ykKSZTcVGamoincKR7xyrKpGH8uxDGv0vgmOqXZuf1o87ccP6wCpIkgb5ePZw2Yvj0icN+eshdMUcFIRVgAwIyGHTKUGqLEluUOWJqkpISRRi2S+BDgAuyAYHhwYsIxCACM/wMSQEBNXkLAjhvFVnEP2WMYzdvO6/4muDZMVCavSD8ujHDQkmxe90VP8y+5s1oznSoCJSfkRkC07yBhd3XRz+m1bd9/tN14XMd3kutI4/5s1qfnmEPjWgIcL5GZoCQUcbA56Cpw4g8TguxZBYiloomfGRCE1SAigKIxZKfG1rCW7cddOhIFIEEEWutIeLmyy+nXni8bMkMDiORv5uaxHW+NRSbFhbL0AeBI9MOyZyRbkpO2D2WVQ7lgSg/L6IsA8xJ0zMiX5GMpFnc37L+/bs3uX/d8rrPkYJQXFAuIgJ8UNwMLaest7Hy3Vs2e/S4OZ9dB4YV09CgAnOR0IwkzR5p2+SNSzd+9Jhp394M6YbJBRCuISYAFJpN5SQAy2q/SP1wg3JnRIlFDAIRokwi6If4XyoaQzohYgmAASGiCWv4W6QqR5asQgBNVGjBAWDLcSAug1Fj9FOvaH7tztd+fOhDzZXbYoiVKBwgkAiGMdYzPnVN1V6PfXLI9dUb9vHtZBwZ6RAYlHegAVkNBAjnzKzf4om6WVso2zFD3/HGyYZpGimjsJJJgBKUmOCarfdpXLYdAbY/QVplwVLHHMMEc4FGZhg2HBFZfppYg6GF4bkJGXiLWz6aYfg+CyoEoDVcC4ahmaGk6Ttx2x9b9t3Lmz9+9tp3Li5yw0CD8sumTExi8ujGoFwzbRuxgZ45tR/M+OlpZ+ATuHP9otluvxfqJBGzBmn6bwALhmQApAT5knyoYcRKsKC3Y+U3rxZ/8xzGPkNsLcwNSIcp3ZfqFpkxUNIgB7CZDQUAikjTHwEENjSYaFxiEIiACuYZozx1yC8dSZZ31U9cXl9W1bfvosDYkXRoMMcjuyjggcq37cGl0UBK95RQV5LasqOVACnNQiMSxKCFlSFFEp0EG3p1v15Rr+b/oqdWcVETOx0whpXwe3k+yAKHwB+63hR1JDjSUYnwp9PoPNG3TDSvkFVLxA/TMQTMBDsRLZrGPDVUO34TrX9LzfyQ3ToiQBVBJ6BtsCRGjEJiZqLfezDAabY0AaRAAeQE5CgjJG+u6NnS+HFH451NqSZO8879PNjpLl3xFnEMYQWUAzBIAxrEyHUhsJjcQBABzEEWA2Jkc/Ojk38Fe4MpHMjZ+XoAAAAASUVORK5CYII=\">\n  <title>Lighthouse report: {{ url }}</title>\n  <style>{{{ css }}}</style>\n  {{#each scripts }}\n    <script>{{{ this }}}</script>\n  {{/each}}\n</head>\n<body>\n\n<div class=\"js-report report\">\n  <section class=\"report-body js-report-body\" status=\"stable\">\n    <div class=\"report-body__header\">\n      <div class=\"report-body__metadata\">\n        <div class=\"report-body__url\">Results for: <a href=\"{{ url }}\" target=\"_blank\">{{ url }}</a></div>\n        <div class=\"report-body__url\">Generated on: {{generatedTime}}</div>\n      </div>\n      <div class=\"report-body__buttons\">\n        <span class=\"export-section\">\n          <button class=\"export-button js-export\" title=\"Export report in different formats\">Export...</button>\n          <ul class=\"export-dropdown\">\n            <a href=\"#\" data-action=\"print\">Print...</a>\n            <a href=\"#\" data-action=\"copy\">Copy JSON...</a>\n            <a href=\"#\" data-action=\"save-html\">Save as HTML...</a>\n            <a href=\"#\" data-action=\"save-json\">Save as JSON...</a>\n          </ul>\n        </span>\n        <button class=\"report-body__icon rerun-button js-rerun-button\" title=\"Rerun this test\"></button>\n        <button class=\"report-body__icon share js-share\"></button>\n        {{#if_not_eq reportContext \"viewer\"}}\n          <button class=\"report-body__icon print js-print\"></button>\n        {{/if_not_eq}}\n      </div>\n    </div>\n    <div class=\"report-body__content\">\n      <div class=\"report-body__menu-container\">\n        <div class=\"menu\">\n          <div class=\"menu__header\">\n            <h1 class=\"menu__header-title\">Lighthouse</h1>\n            <div class=\"menu__header-version\">Version: {{lighthouseVersion}}</div>\n          </div>\n          <ul class=\"menu__nav\">\n            {{#each aggregations}}\n            <li class=\"menu__nav-item\">\n              <a class=\"menu__link\" href=\"#{{nameToLink this.name}}\">\n                {{ this.name }}\n              </a>\n            </li>\n            {{/each}}\n          </ul>\n        </div>\n      </div>\n\n      <div class=\"report-body__aggregations-container\">\n      {{#each aggregations}}\n      <section class=\"js-breakdown aggregations\" id=\"{{nameToLink this.name}}\">\n        <header class=\"aggregations__header\">\n          <h1>{{ this.name }}</h1>\n          <p class=\"aggregations__desc\">{{ sanitize this.description }}</p>\n          {{#if this.scored}}\n          <div class=\"section-result\">\n            <span class=\"section-result__score score-{{ getTotalScoreRating this }}-bg\">\n              <span class=\"section-result__points\">{{ getTotalScore this }}</span>\n              <span class=\"section-result__divider\">/</span>\n              <span class=\"section-result__total\">100</span>\n            </span>\n          </div>\n          {{/if}}\n        </header>\n\n        <div class=\"js-report-by-user-feature\">\n          {{#each this.score as |aggregation|}}\n            <section class=\"aggregation\">\n\n            {{#if aggregation.name }}\n            <header class=\"aggregation__header\">\n              <h2>{{ aggregation.name }}</h2>\n              {{#if aggregation.description }}\n                <p class=\"aggregation__desc\">{{ sanitize aggregation.description }}</p>\n              {{/if}}\n            </header>\n            {{/if}}\n\n            <ul class=\"subitems\">\n              {{#each aggregation.subItems as |subItem| }}\n                <li class=\"subitem {{#if subItem.comingSoon}}--coming-soon{{/if}} {{#if (shouldShowHelpText subItem.score)}}--show-help{{/if}}\">\n\n                  <p class=\"subitem__desc\">\n                    {{#unless ../../scored }}\n                      <strong class=\"subitem__category\">{{ subItem.category }}:</strong>\n                    {{/unless}}\n\n                    {{ sanitize subItem.description }}\n\n                    {{~#if (and subItem.displayValue (not (is-bool subItem.displayValue))) ~}}\n                      <strong class=\"subitem__raw-value\">: {{ subItem.displayValue }}</strong>\n                    {{/if}}\n\n                    {{#if subItem.optimalValue }}\n                      <small>(target: {{ subItem.optimalValue }})</small>\n                    {{/if}}\n\n                    {{#if subItem.comingSoon}}\n                      <small class=\"subitem__tease\">(Coming soon)</small>\n                    {{/if}}\n\n                    {{#if subItem.helpText }}\n                      <input type=\"checkbox\" class=\"subitem__help-toggle\" title=\"Toggle help text\"  {{#if (shouldShowHelpText subItem.score)}}checked{{/if}}>\n                      <span class=\"subitem__help\">\n                        {{ sanitize subItem.helpText }}\n                      </span>\n                    {{/if}}\n                  </p>\n\n                  {{#if subItem.debugString }}\n                    <div class=\"subitem__debug\">\n                      {{ subItem.debugString }}\n                    </div>\n                  {{/if}}\n\n                  <div class=\"subitem-result\">\n                    {{#if subItem.comingSoon}}\n                          <span class=\"subitem-result__unknown score-unknown-bg\">N/A</span>\n                    {{else}}\n                      {{#if (is-bool subItem.score)}}\n                        {{#if subItem.score}}\n                          <span class=\"subitem-result__good score-good-bg\">Pass</span>\n                        {{else}}\n                          <span class=\"subitem-result__poor score-poor-bg\">Fail</span>\n                        {{/if}}\n                      {{else}}\n                        <span class=\"subitem-result__points score-{{ getItemRating subItem.score }}-bg\">\n                          {{ subItem.score }}\n                        </span>\n                      {{/if}}\n                    {{/if}}\n                  </div>\n\n                  {{#if subItem.extendedInfo.value}}\n                    {{> (lookup . 'name') subItem.extendedInfo.value }}\n                  {{/if}}\n                </li>\n              {{/each}}\n            </ul>\n          </section>\n          {{/each}}\n        </div>\n      </section>\n      {{/each}}\n      </div>\n    </div>\n\n    <footer class=\"footer\">\n      Generated by <b>Lighthouse</b> {{lighthouseVersion}} on {{generatedTime}} | <a href=\"https://github.com/GoogleChrome/Lighthouse/issues\" target=\"_blank\">File an issue</a>\n    </footer>\n  </section>\n</div>\n";}
getExceptionTemplate(){return"<!--\n\nCopyright 2016 Google Inc. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\n-->\n<!doctype html>\n<html>\n<head>\n  <meta charset=\"utf-8\">\n  <meta name=\"viewport\" content=\"width=device-width\">\n  <title>Lighthouse report - error</title>\n  <style>{{{ css }}}</style>\n</head>\n<body>\n\n  <div class=\"js-report report\">\n    <section class=\"report-body\">\n      <div class=\"report-body__header\"></div>\n\n      <div class=\"report-body__content\">\n\n        <div class=\"report-error\">\n          <h1 class=\"error-message\">⚠️ Error: {{{ errMessage }}}</h1>\n          <p class=\"error-stack\"> {{{ errStack }}}</p>\n          <big>\n            ➡ <a target=\"_blank\" href=\"https://github.com/GoogleChrome/lighthouse/issues\">Please report this bug</a>\n          </big>\n          <div class=\"error-results\"><pre>{{{ results }}}</pre></div>\n        </div>\n\n      </div>\n\n    </section>\n    <footer class=\"footer\">\n      Generated by <b>Lighthouse</b> on {{generatedTime}} | <a href=\"https://github.com/GoogleChrome/Lighthouse/issues\" target=\"_blank\">File an issue</a>\n    </footer>\n  </div>\n\n</body>\n</html>\n";}
getReportCSS(){return"/**\n * Copyright 2016 Google Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n* {\n  box-sizing: border-box;\n}\n\nspan, div, p, section, header, h1, h2, li, ul {\n  margin: 0;\n  padding: 0;\n  line-height: inherit;\n}\n\n:root {\n  --text-font-family: \"Roboto\", -apple-system, BlinkMacSystemFont,  \"Segoe UI\", \"Oxygen\", \"Ubuntu\", \"Cantarell\", \"Fira Sans\", \"Droid Sans\", \"Helvetica Neue\", sans-serif;\n  --text-color: #212121;\n  --secondary-text-color: #757575;\n  --accent-color: #719EA8;\n  --poor-color: #eb211e;\n  --good-color: #1ac123;\n  --average-color: #ffae00;\n  --unknown-color: #b3b3b3;\n  --gutter-gap: 12px;\n  --gutter-width: 40px;\n  --body-font-size: 14px;\n  --body-line-height: 20px;\n  --subitem-font-size: 14px;\n  --subitem-line-height: 20px;\n  --subheading-font-size: 16px;\n  --subheading-line-height: 24px;\n  --subheading-color: var(--accent-color);\n  --heading-font-size: 24px;\n  --heading-line-height: 32px;\n  --subitem-indent: 24px;\n  --max-line-length: none;\n\n  --report-width: 1280px;\n  --report-menu-width: 280px;\n  --report-header-height: 58px;\n}\n\n:root[data-report-context=\"devtools\"] {\n  --text-font-family: '.SFNSDisplay-Regular', 'Helvetica Neue', 'Lucida Grande', sans-serif;\n  --text-color: #222;\n  --secondary-text-color: #606060;\n  --accent-color: #3879d9;\n  --body-font-size: 13px;\n  --body-line-height: 17px;\n  --subitem-font-size: 14px;\n  --subitem-line-height: 18px;\n  --subheading-font-size: 16px;\n  --subheading-line-height: 20px;\n  --subheading-color: inherit;\n  --report-header-height: 0;\n  --heading-font-size: 20px;\n  --heading-line-height: 24px;\n  --subitem-indent: 24px;\n  --max-line-length: calc(60 * var(--body-font-size));\n}\n\nhtml {\n  font-family: var(--text-font-family);\n  font-size: var(--body-font-size);\n  line-height: 1;\n  margin: 0;\n  padding: 0;\n}\n\nhtml, body {\n  height: 100%;\n}\n\n/* When deep linking to a section, bump the heading down so it's not covered by the top nav. */\n:target.aggregations {\n  padding-top: calc(var(--report-header-height) + var(--heading-line-height)) !important;\n}\n\na {\n  color: #15c;\n}\n\nbody {\n  display: flex;\n  flex-direction: column;\n  align-items: stretch;\n  margin: 0;\n  background: #f5f5f5;\n}\n\n.report-error {\n  font-family: consolas, monospace;\n}\n\n.error-stack {\n  white-space: pre-wrap;\n}\n\n.error-results {\n  background: #dedede;\n  max-height: 600px;\n  overflow: auto;\n  border-radius: 2px;\n}\n\n.report {\n  width: 100%;\n  margin: 0 auto;\n  max-width: var(--report-width);\n  background: #FFF;\n  box-shadow: 0 0 6px 0 rgba(0,0,0,0.26);\n}\n\n.report-body__icon {\n  width: 24px;\n  height: 24px;\n  border: none;\n  cursor: pointer;\n  flex: 0 0 auto;\n  background-repeat: no-repeat;\n  background-position: center center;\n  background-size: contain;\n  background-color: transparent;\n  margin-left: 8px;\n}\n\n.report-body__icon.print {\n  background-image: url('data:image/svg+xml;utf8,<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path d=\"M19 8H5c-1.66 0-3 1.34-3 3v6h4v4h12v-4h4v-6c0-1.66-1.34-3-3-3zm-3 11H8v-5h8v5zm3-7c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm-1-9H6v4h12V3z\"/><path fill=\"none\" d=\"M0 0h24v24H0z\"/></svg>');\n}\n\n.report-body__icon.share {\n  background-image: url('data:image/svg+xml;utf8,<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0z\"/><path d=\"M18 16.08c-.76 0-1.44.3-1.96.77L8.91 12.7c.05-.23.09-.46.09-.7s-.04-.47-.09-.7l7.05-4.11c.54.5 1.25.81 2.04.81 1.66 0 3-1.34 3-3s-1.34-3-3-3-3 1.34-3 3c0 .24.04.47.09.7L8.04 9.81C7.5 9.31 6.79 9 6 9c-1.66 0-3 1.34-3 3s1.34 3 3 3c.79 0 1.5-.31 2.04-.81l7.12 4.16c-.05.21-.08.43-.08.65 0 1.61 1.31 2.92 2.92 2.92 1.61 0 2.92-1.31 2.92-2.92s-1.31-2.92-2.92-2.92z\"/></svg>');\n  display: none;\n}\n\n.report-body__icon.copy {\n  background-image: url('data:image/svg+xml;utf8,<svg height=\"24\" viewBox=\"0 0 24 24\" width=\"24\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M0 0h24v24H0z\" fill=\"none\"/><path d=\"M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z\"/></svg>');\n  display: none;\n}\n\n.report-body__icon.rerun-button {\n  background-image: url('data:image/svg+xml;utf8,<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24px\" height=\"24px\" viewBox=\"0 0 24 24\" fill=\"#000000\"><path d=\"M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z\"/><path d=\"M0 0h24v24H0z\" fill=\"none\"/></svg>');\n  display: none;\n}\n\n.rerun-button[status=running] {\n  animation: rotate 1000ms infinite;\n}\n\n@keyframes rotate {\n  from {\n    transform: none;\n  }\n  to {\n    transform: rotate(360deg);\n  }\n}\n\n.score-container__overall-score {\n  color: #FFF;\n  font-size: 92px;\n  font-weight: 100;\n  position: relative;\n  display: inline-block;\n  text-align: center;\n  min-width: 70px;\n}\n\n.score-container__overall-score::after {\n  content: 'Your score';\n  position: absolute;\n  bottom: -4px;\n  font-size: 14px;\n  font-weight: 500;\n  text-align: center;\n  width: 100%;\n  left: 0;\n  opacity: 0.5;\n}\n\n.score-container__max-score {\n  color: #57A0A8;\n  font-size: 28px;\n  font-weight: 500;\n}\n\n.report-body {\n  position: relative;\n}\n\n.report-body__content {\n  margin-left: var(--report-menu-width);\n  position: relative;\n}\n\n.report-body__aggregations-container {\n  padding-top: var(--report-header-height);\n  will-change: transform;\n}\n\n.report-body__menu-container {\n  height: 100%;\n  width: 100%;\n  min-width: 230px;\n  max-width: var(--report-width);\n  position: fixed;\n  will-change: transform;\n  left: 50%;\n  transform: translateX(-50%);\n  top: 0;\n  pointer-events: none;\n}\n\n.menu {\n  width: var(--report-menu-width);\n  background: #FFFFFF;\n  height: 100%;\n  top: 0;\n  left: 0;\n  pointer-events: auto;\n  border-right: 1px solid #DFDFDF;\n}\n\n.menu__header {\n  background: #2238b3;\n  padding: 0 20px;\n  height: 115px;\n  line-height: 54px;\n  color: #FFF;\n  font-family: var(--text-font-family);\n  font-size: 18px;\n  position: relative;\n  display: flex;\n  flex-direction: column;\n  align-self: center;\n  justify-content: center;\n}\n\n.menu__header::after {\n  content: '';\n  display: block;\n  width: 90px;\n  height: 90px;\n  position: absolute;\n  top: 0;\n  right: 0;\n  background: url('data:image/svg+xml;utf-8,<svg width=\"86\" height=\"86\" viewBox=\"0 0 86 86\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\"><title>Beta</title><defs><path id=\"b\" d=\"M-11.704 13.144H125.58v30H-11.703z\"/><filter x=\"-50%\" y=\"-50%\" width=\"200%\" height=\"200%\" filterUnits=\"objectBoundingBox\" id=\"a\"><feOffset dy=\"1\" in=\"SourceAlpha\" result=\"shadowOffsetOuter1\"/><feGaussianBlur stdDeviation=\"1\" in=\"shadowOffsetOuter1\" result=\"shadowBlurOuter1\"/><feColorMatrix values=\"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.5 0\" in=\"shadowBlurOuter1\"/></filter><path id=\"d\" d=\"M.4 16.972h119v28.4H.4z\"/><filter x=\"-50%\" y=\"-50%\" width=\"200%\" height=\"200%\" filterUnits=\"objectBoundingBox\" id=\"c\"><feGaussianBlur stdDeviation=\"3.5\" in=\"SourceAlpha\" result=\"shadowBlurInner1\"/><feOffset in=\"shadowBlurInner1\" result=\"shadowOffsetInner1\"/><feComposite in=\"shadowOffsetInner1\" in2=\"SourceAlpha\" operator=\"arithmetic\" k2=\"-1\" k3=\"1\" result=\"shadowInnerInner1\"/><feColorMatrix values=\"0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0.689509737 0\" in=\"shadowInnerInner1\"/></filter><text id=\"f\" font-family=\"Arial-BoldMT, Arial\" font-size=\"13\" font-weight=\"bold\" fill=\"#FFF\"><tspan x=\"37.556\" y=\"34.556\">BETA</tspan></text><filter x=\"-50%\" y=\"-50%\" width=\"200%\" height=\"200%\" filterUnits=\"objectBoundingBox\" id=\"e\"><feOffset dy=\"1\" in=\"SourceAlpha\" result=\"shadowOffsetOuter1\"/><feGaussianBlur stdDeviation=\".5\" in=\"shadowOffsetOuter1\" result=\"shadowBlurOuter1\"/><feColorMatrix values=\"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.140964674 0\" in=\"shadowBlurOuter1\"/></filter></defs><g fill=\"none\" fill-rule=\"evenodd\"><g mask=\"url(#mask-2)\" transform=\"rotate(45 55.44 24.523)\"><use fill=\"#000\" filter=\"url(#a)\" xlink:href=\"#b\"/><use fill=\"#CF3A3C\" xlink:href=\"#b\"/></g><use filter=\"url(#c)\" xlink:href=\"#d\" mask=\"url(#mask-2)\" transform=\"rotate(45 58.4 27.55)\" fill=\"#000\"/><g mask=\"url(#mask-2)\" transform=\"rotate(45 52.556 36.435)\" fill=\"#FFF\"><use filter=\"url(#e)\" xlink:href=\"#f\"/><use xlink:href=\"#f\"/></g><path d=\"M8.5-.5l88.204 88.204M8.5-39.5l88.204 88.204\" stroke=\"#FFF\" stroke-linecap=\"square\" stroke-dasharray=\"1,2\" opacity=\".386\" mask=\"url(#mask-2)\" transform=\"translate(-3)\"/></g></svg>') top right no-repeat;\n}\n\n.menu__header-title {\n  font-family: var(--text-font-family);\n  font-weight: 300;\n  color: #fff;\n  margin: 0;\n  padding: 0;\n  line-height: 1.5;\n}\n\n.menu__header-version {\n  opacity: 0.4;\n  color: #fff;\n  font-family: var(--text-font-family);\n  font-size: 14px;\n  line-height: 1.5;\n}\n\n.menu__nav {\n  list-style: none;\n  margin: 0;\n  padding: 0;\n}\n\n.menu__nav-item {\n  height: 40px;\n  line-height: 40px;\n  border-top: 1px solid #EBEBEB;\n}\n\n.menu__link {\n  padding: 0 20px;\n  text-decoration: none;\n  color: #777;\n  display: flex;\n}\n\n.menu__link:hover {\n  background-color: #448aff;\n  color: #FFF;\n}\n\n.menu__link-label {\n  flex: 1;\n  color: #49525F;\n  font-weight: 500;\n  overflow: hidden;\n  white-space: nowrap;\n  text-overflow: ellipsis;\n}\n\n.menu__link-score {\n  padding-left: 20px;\n}\n\n.report-body__metadata {\n  flex: 1 1 0;\n  white-space: nowrap;\n}\n\n.report-body__buttons {\n  display: flex;\n  align-items: center;\n  flex-shrink: 0;\n}\n\n.report-body__url {\n  font-family: var(--text-font-family);\n  white-space: nowrap;\n  font-size: 13px;\n  font-weight: 400;\n  color: var(--secondary-text-color);\n  line-height: 20px;\n  overflow: hidden;\n  text-overflow: ellipsis;\n}\n\n.report-body__url a {\n  color: currentColor;\n}\n\n.report-body__breakdown {\n  flex: 1;\n  max-width: 100%;\n}\n\n.report-body__breakdown-item {\n  padding-bottom: 6px;\n}\n\n.report-body__breakdown-item:last-of-type {\n  border: none;\n}\n\n.report-body__header {\n  height: var(--report-header-height);\n  border-bottom: 1px solid #EBEBEB;\n  background: #FAFAFA;\n  margin-left: var(--report-menu-width);\n  display: flex;\n  flex-direction: row;\n  align-items: center;\n  justify-content: flex-start;\n  padding: 0 var(--heading-line-height);\n  position: fixed;\n  will-change: transform;\n  z-index: 1;\n  max-width: calc( var(--report-width) - var(--report-menu-width));\n  width: calc(100vw - var(--report-menu-width));\n}\n\n.report-section__title {\n  -webkit-font-smoothing: antialiased;\n  font-family: var(--text-font-family);\n  font-size: 28px;\n  font-weight: 500;\n  color: #49525F;\n  display: flex;\n  margin: 0.4em 0 0.3em 0;\n}\n\n.report-section__title-main {\n  flex: 1;\n}\n\n.report-section__title-score-total {\n  font-weight: 500;\n}\n\n.report-section__title-score-max {\n  font-weight: 400;\n  font-size: 18px;\n  margin-left: -4px;\n}\n\n.report-section__subtitle {\n  -webkit-font-smoothing: antialiased;\n  font-family: var(--text-font-family);\n  font-size: 18px;\n  font-weight: 500;\n  color: #719EA8;\n  display: flex;\n  margin: 24px 0 16px 0;\n}\n\n.report-section__description {\n  color: #5F6875;\n  font-size: 16px;\n  margin: 0 0 1em 0;\n  line-height: 1.4;\n  max-width: 750px;\n}\n.report-section__description:empty {\n  margin: 0;\n}\n\n.report-section__aggregation-description {\n  font-style: italic;\n  color: #777;\n  font-size: 14px;\n  margin: 0.6em 0 0.8em 0;\n  line-height: 1.4;\n  max-width: 750px;\n}\n\n.report-section__label {\n  flex: 1;\n}\n\n.report-section__individual-results {\n  list-style: none;\n  padding: 0;\n  margin: 0;\n}\n\n.report-section__item {\n  padding-left: 32px;\n  background: url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNXB4IiBoZWlnaHQ9IjVweCIgdmlld0JveD0iMCAwIDUgNSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KICAgIDxjaXJjbGUgaWQ9Ik92YWwtNzAiIHN0cm9rZT0ibm9uZSIgZmlsbD0iIzY0NjQ2NCIgZmlsbC1ydWxlPSJldmVub2RkIiBjeD0iMi41IiBjeT0iMi41IiByPSIyLjUiPjwvY2lyY2xlPgo8L3N2Zz4K') 14px 8px no-repeat;\n  line-height: 24px;\n}\n\n.report-section__item-details {\n  display: flex;\n}\n\n.report-section__item-category {\n  font-weight: 700;\n}\n\n.report-section__item-extended-info {\n  font-size: 15px;\n  color: #555;\n  font-style: italic;\n  margin: 0px 0px 16px 24px;\n  max-width: 90%;\n}\n\n.report-section__item-extended-info:empty {\n  margin: 0;\n}\n\n.report-section__item-helptext {\n  font-size: 14px;\n  color: #999;\n  font-style: italic;\n  padding: 8px 0px 16px 24px;\n  max-width: 90%;\n}\n\n.report-section__item-help-toggle {\n  color: currentColor;\n  border-radius: 50%;\n  width: 21px;\n  height: 21px;\n  display: inline-flex;\n  justify-content: center;\n  align-items: center;\n  cursor: pointer;\n  transition: all 0.2s cubic-bezier(0,0,0.3,1);\n  font-size: 90%;\n  font-weight: 600;\n  margin-left: 8px;\n  vertical-align: top;\n  opacity: 0.6;\n  box-shadow: 0 1px 2px rgba(0,0,0,0.5);\n}\n\n.report-section__item-help-toggle:hover {\n  opacity: 1;\n  box-shadow: 0 1px 2px rgba(0,0,0,0.7);\n}\n\n.report-section__item-raw-value {\n  color: #777;\n}\n\n.report-section__item-description {\n  flex: 1;\n}\n\n.footer {\n  margin-top: 40px;\n  margin-left: var(--report-menu-width);\n  height: 130px;\n  line-height: 90px;\n  text-align: center;\n  font-size: 12px;\n  border-top: 1px solid #EBEBEB;\n  color: #999;\n}\n\n.coming-soon, .coming-soon * {\n  color: #AAA;\n}\n\n.coming-soon .report-section__item-value {\n  font-size: 70%;\n}\n\n.devtabs {\n  flex: 0 1 auto;\n  background: right 0 / auto 27px no-repeat url(tabs_right.png),\n              0 0 / auto 27px no-repeat url(tabs_left.png),\n              0 0 / auto 27px repeat-x url(tabs_center.png);\n  height: 27px;\n}\n\n.aggregations__header {\n  position: relative;\n}\n\n.aggregations__header > h1 {\n  font-size: var(--heading-font-size);\n  font-weight: normal;\n  line-height: var(--heading-line-height);\n}\n\n.aggregations {\n  padding: var(--heading-line-height);\n  padding-left: calc(var(--heading-line-height) + var(--gutter-width) + var(--gutter-gap));\n}\n\n.aggregations:not(:first-child) {\n  border-top: 1px solid #ccc;\n}\n\n.aggregations__desc {\n  font-size: var(--body-font-size);\n  line-height: var(--body-line-height);\n  margin-top: calc(var(--body-line-height) / 2);\n}\n\n.section-result {\n  position: absolute;\n  top: 0;\n  left: calc((var(--gutter-width) + var(--gutter-gap)) * -1);\n  width: var(--gutter-width);\n\n  display: flex;\n  flex-direction: column;\n  align-items: flex-end;\n}\n\n.section-result__score {\n  display: flex;\n  flex-direction: column;\n  align-items: stretch;\n  background: #000;\n  color: #fff;\n  text-align: center;\n  padding: 4px 8px;\n  border-radius: 2px;\n}\n\n.section-result__points {\n  font-size: var(--heading-font-size);\n}\n\n.section-result__divider {\n  display: none;\n}\n\n.section-result__total {\n  font-size: var(--body-font-size);\n  margin-top: 2px;\n  border-top: 1px solid #fff;\n  padding-top: 4px;\n}\n\n.aggregation__header {\n  max-width: var(--max-line-length);\n}\n\n.aggregation__header > h2 {\n  font-size: var(--subheading-font-size);\n  font-weight: normal;\n  line-height: var(--subheading-line-height);\n  color: var(--subheading-color);\n}\n\n.aggregation {\n  margin-top: var(--subheading-line-height);\n  max-width: var(--max-line-length);\n}\n\n.aggregation__desc {\n  font-size: var(--body-font-size);\n  line-height: var(--body-line-height);\n  margin-top: calc(var(--body-line-height) / 2);\n}\n\n.subitems {\n  list-style: none;\n  margin-top: var(--subitem-line-height);\n}\n\n.subitem {\n  position: relative;\n  font-size: var(--subitem-font-size);\n  padding-left: calc(var(--subitem-indent) + var(--gutter-width) + var(--gutter-gap));\n  margin-top: calc(var(--subitem-line-height) / 2);\n}\n\n.subitem.--coming-soon {\n  color: var(--secondary-text-color);\n}\n\n.subitem strong {\n  font-weight: bold;\n}\n\n.subitem small {\n  font-size: var(--body-font-size);\n}\n\n.subitem__desc {\n  line-height: var(--subitem-line-height);\n}\n\n.subitem-result {\n  position: absolute;\n  top: 0;\n  left: var(--subitem-indent);\n  width: var(--gutter-width);\n  display: flex;\n  flex-direction: column;\n  align-items: flex-end;\n}\n\n.subitem-result__good, .subitem-result__poor, .subitem-result__unknown {\n  position: relative;\n  display: block;\n  overflow: hidden;\n  margin-top: calc((var(--subitem-line-height) - 16px) / 2);\n  width: 16px;\n  height: 16px;\n  border-radius: 50%;\n  color: transparent;\n  background-color: #000;\n}\n\n.subitem-result__good::after, .subitem-result__poor::after, .subitem-result__unknown::after {\n  content: '';\n  position: absolute;\n  left: 0;\n  right: 0;\n  top: 0;\n  bottom: 0;\n  -webkit-mask: center center / 12px 12px no-repeat;\n  background-color: #fff;\n}\n\n.subitem-result__good::after { -webkit-mask-image: url('data:image/svg+xml;utf8,<svg width=\"12\" height=\"12\" viewBox=\"0 0 12 12\" xmlns=\"http://www.w3.org/2000/svg\"><title>good</title><path d=\"M9.17 2.33L4.5 7 2.83 5.33 1.5 6.66l3 3 6-6z\" fill=\"#FFF\" fill-rule=\"evenodd\"/></svg>'); }\n.subitem-result__poor::after { -webkit-mask-image: url('data:image/svg+xml;utf8,<svg width=\"12\" height=\"12\" viewBox=\"0 0 12 12\" xmlns=\"http://www.w3.org/2000/svg\"><title>poor</title><path d=\"M8.33 2.33l1.33 1.33-2.335 2.335L9.66 8.33 8.33 9.66 5.995 7.325 3.66 9.66 2.33 8.33l2.335-2.335L2.33 3.66l1.33-1.33 2.335 2.335z\" fill=\"#FFF\" fill-rule=\"evenodd\"/></svg>'); }\n.subitem-result__unknown::after { -webkit-mask-image: url('data:image/svg+xml;utf8,<svg width=\"12\" height=\"12\" viewBox=\"0 0 12 12\" xmlns=\"http://www.w3.org/2000/svg\"><title>neutral</title><path d=\"M2 5h8v2H2z\" fill=\"#FFF\" fill-rule=\"evenodd\"/></svg>'); }\n\n.subitem-result__points {\n  margin-top: calc((var(--subitem-line-height) - var(--subitem-font-size) - 4px) / 2);\n  background: #000;\n  padding: 2px 4px;\n  border-radius: 1px;\n  color: #fff;\n  border-radius: 2px;\n}\n\n.subitem__details {\n  list-style: none;\n  margin: 0;\n  padding: 0;\n  margin-left: var(--subitem-indent);\n}\n\n.subitem__detail {\n  font-size: var(--body-font-size);\n  line-height: var(--body-line-height);\n  margin-top: calc(var(--body-line-height) / 2);\n}\n\n.subitem__help-toggle {\n  -webkit-appearance: none;\n  position: relative;\n  display: inline-block;\n  width: 16px;\n  height: 16px;\n  border-radius: 50%;\n  border: 1px solid #ccc;\n  vertical-align: middle;\n  margin-left: .5em;\n  outline: 0;\n}\n\n.subitem__help-toggle::after {\n  content: '';\n  position: absolute;\n  left: 0;\n  right: 0;\n  top: 0;\n  bottom: 0;\n  -webkit-mask: 1px 1px / 12px 12px no-repeat;\n  -webkit-mask-image: url('data:image/svg+xml;utf8,<svg width=\"12\" height=\"12\" viewBox=\"0 0 12 12\" xmlns=\"http://www.w3.org/2000/svg\"><title>help</title><path d=\"M5.216 7.457c0-.237.011-.452.033-.645.021-.194.058-.372.11-.535a1.918 1.918 0 0 1 .55-.847 3.65 3.65 0 0 0 .545-.597c.133-.19.2-.398.2-.623 0-.28-.053-.485-.16-.616-.107-.13-.268-.196-.482-.196a.583.583 0 0 0-.457.207.834.834 0 0 0-.15.271c-.04.111-.062.244-.065.398H3.67c.003-.401.067-.745.19-1.032a1.96 1.96 0 0 1 .5-.707c.208-.185.455-.32.738-.406A3.13 3.13 0 0 1 6.012 2c.359 0 .682.046.968.137.287.091.53.227.729.406.2.18.352.401.457.667.105.265.158.571.158.919 0 .233-.03.44-.091.624-.061.182-.145.353-.252.51-.107.158-.233.311-.378.46-.145.149-.3.306-.465.47a2.084 2.084 0 0 0-.24.275c-.063.09-.115.183-.152.282a1.57 1.57 0 0 0-.084.323 2.966 2.966 0 0 0-.033.384H5.216zm-.202 1.634a.96.96 0 0 1 .067-.36.828.828 0 0 1 .19-.287.913.913 0 0 1 .291-.191.969.969 0 0 1 .376-.07c.138 0 .263.023.375.07.112.046.21.11.292.19.082.081.146.177.19.288a.96.96 0 0 1 .067.36.96.96 0 0 1-.067.36.828.828 0 0 1-.19.288.913.913 0 0 1-.292.191.969.969 0 0 1-.375.07.969.969 0 0 1-.376-.07.913.913 0 0 1-.291-.19.828.828 0 0 1-.19-.288.96.96 0 0 1-.067-.36z\" fill=\"#000\" fill-rule=\"evenodd\"/></svg>');\n  background-color: var(--secondary-text-color);\n  cursor: pointer;\n}\n\n.subitem__help-toggle:hover {\n  border-color: var(--secondary-text-color);\n}\n\n.subitem__help-toggle:checked {\n  background-color: var(--accent-color);\n  border-color: var(--accent-color);\n}\n\n.subitem__help-toggle:checked::after {\n  background-color: #fff;\n}\n\n.subitem__help {\n  display: none;\n  font-size: var(--body-font-size);\n  line-height: var(--body-line-height);\n  margin-top: calc(var(--body-line-height) / 2);\n  margin-left: var(--subitem-indent);\n}\n\n.subitem__help-toggle:checked + .subitem__help {\n  display: block;\n}\n\n.subitem__debug {\n  font-size: var(--body-font-size);\n  line-height: var(--body-line-height);\n  margin-top: calc(var(--body-line-height) / 2);\n  margin-left: var(--subitem-indent);\n  color: var(--poor-color);\n}\n\n.score-good-bg {\n  background-color: var(--good-color);\n}\n.score-average-bg {\n  background-color: var(--average-color);\n}\n.score-poor-bg {\n  background-color: var(--poor-color);\n}\n.score-unknown-bg {\n  background-color: var(--unknown-color);\n}\n\n.export-section {\n  position: relative;\n}\n\n.export-button {\n  display: inline-flex;\n  background-color: #fff;\n  border: 1px solid #ccc;\n  box-sizing: border-box;\n  min-width: 5.14em;\n  padding: 0.7em 1.1em;\n  letter-spacing: 0.02em;\n  border-radius: 3px;\n  cursor: pointer;\n  color: var(--secondary-text-color);\n  outline: 0;\n  font-weight: 500;\n  display: none;\n}\n\n.export-dropdown {\n  position: absolute;\n  background-color: #fafafa;\n  border: 1px solid #ccc;\n  border-radius: 3px;\n  margin: 0;\n  padding: 8px 0;\n  cursor: pointer;\n  top: 36px;\n  left: 0;\n  z-index: 1;\n  box-shadow: 1px 1px 3px #ccc;\n  min-width: 125px;\n  list-style: none;\n  line-height: 1.5em;\n  visibility: hidden;\n  clip: rect(0, 140px, 0, 0);\n  opacity: 0;\n  transition: all 200ms cubic-bezier(0,0,0.2,1);\n}\n\n.export-button:focus,\n.export-button.active {\n  box-shadow: 1px 1px 3px #ccc;\n}\n\n.export-button.active + .export-dropdown {\n  visibility: visible;\n  opacity: 1;\n  clip: rect(0, 140px, 200px, 0);\n}\n\n.export-dropdown a {\n  display: block;\n  color: currentColor;\n  text-decoration: none;\n  white-space: nowrap;\n  padding: 0 12px;\n}\n\n.export-dropdown a:hover,\n.export-dropdown a:focus {\n  background-color: rgb(239,239,239);\n  outline: 0;\n}\n\n@media print {\n  body {\n    -webkit-print-color-adjust: exact; /* print background colors */\n  }\n\n  .report {\n    box-shadow: none;\n  }\n\n  .report-body__header,\n  .report-body__menu-container {\n    display: none;\n  }\n\n  .report-body__content {\n    margin-left: 0;\n  }\n}\n\n\n@media screen and (max-width: 400px) {\n  .report-body__metadata {\n    margin-right: 8px;\n    max-width: 65%;\n  }\n}\n\n@media screen and (max-width: 767px) {\n  :root {\n    --subitem-indent: 8px;\n    --gutter-width: 16px;\n  }\n  .aggregations {\n    padding-right: 8px;\n  }\n  .report-body__menu-container {\n    display: none;\n  }\n  .report-body__content,\n  .report-body__header {\n    margin-left: 0;\n  }\n  .report-body__header {\n    width: 100%;\n    padding: 8px;\n  }\n  .export-dropdown {\n    right: 0;\n    left: initial;\n  }\n  .footer {\n    margin-top: 0;\n    margin-left: 0;\n    height: auto;\n  }\n}\n\n:root[data-report-context=\"devtools\"] .report {\n  margin: 10px 10px;\n  padding: 10px;\n  box-shadow: none;\n  max-width: none;\n  width: auto;\n}\n\n:root[data-report-context=\"devtools\"] .report-body__aggregations-container > section:first-child {\n  padding-top: calc(var(--heading-line-height) / 3);\n}\n:root[data-report-context=\"devtools\"] .report-body__menu-container {\n  display: none;\n}\n\n:root[data-report-context=\"devtools\"] .report-body__header {\n  display: none;\n}\n\n:root[data-report-context=\"devtools\"] .report-body__content {\n  margin-left: 0;\n}\n\n:root[data-report-context=\"devtools\"] .footer {\n  display: none;\n}\n\n:root[data-report-context=\"viewer\"] .share,\n:root[data-report-context=\"viewer\"] .export-button {\n  display: initial;\n}\n";}
getReportJS(reportContext){if(reportContext==='devtools'){return[];}else{return["/**\n * @license\n * Copyright 2016 Google Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/* global window, document */\n\n'use strict';\n\nwindow.addEventListener('DOMContentLoaded', _ => {\n  const printButton = document.querySelector('.js-print');\n  printButton.addEventListener('click', _ => {\n    window.print();\n  });\n});\n"];}}
_createPWAAuditsByCategory(aggregations){const items={};aggregations.forEach(aggregation=>{if(!aggregation.categorizable){return;}
aggregation.score.forEach(score=>{score.subItems.forEach(subItem=>{if(!items[subItem.category]){items[subItem.category]={};}
if(!items[subItem.category][subItem.name]){items[subItem.category][subItem.name]=subItem;}});});});return items;}
renderException(err,results){const template=Handlebars.compile(this.getExceptionTemplate());return template({errMessage:err.message,errStack:err.stack,css:this.getReportCSS(),results:JSON.stringify(results,null,2)});}
generateHTML(results,reportContext){reportContext=reportContext||'extension';Object.keys(results.audits).forEach(audit=>{audit=results.audits[audit];if(!audit.extendedInfo){return;}
if(!audit.extendedInfo.formatter){return;}
const formatter=Formatter.getByName(audit.extendedInfo.formatter);const helpers=formatter.getHelpers();if(helpers){Handlebars.registerHelper(helpers);}
Handlebars.registerPartial(audit.name,formatter.getFormatter('html'));});results.aggregations.forEach(aggregation=>{aggregation.score.forEach(score=>{score.subItems=score.subItems.map(subItem=>results.audits[subItem]||subItem);});});const template=Handlebars.compile(this.getReportTemplate());return template({url:results.url,lighthouseVersion:results.lighthouseVersion,generatedTime:this._formatTime(results.generatedTime),lhresults:this._escapeScriptTags(JSON.stringify(results,null,2)),css:this.getReportCSS(),reportContext:reportContext,scripts:this.getReportJS(reportContext),aggregations:results.aggregations,auditsByCategory:this._createPWAAuditsByCategory(results.aggregations)});}}
module.exports=ReportGenerator;},{"../formatters/formatter":8,"handlebars":276,"marked":281,"path":204}],33:[function(require,module,exports){(function(process,__dirname){'use strict';const Driver=require('./gather/driver.js');const GatherRunner=require('./gather/gather-runner');const Aggregate=require('./aggregator/aggregate');const Audit=require('./audits/audit');const log=require('./lib/log');const path=require('path');const URL=require('./lib/url-shim');class Runner{static run(connection,opts){opts.flags=opts.flags||{};const config=opts.config;opts.initialUrl=opts.url;if(typeof opts.initialUrl!=='string'||opts.initialUrl.length===0){return Promise.reject(new Error('You must provide a url to the driver'));}
let parsedURL;try{parsedURL=new URL(opts.url);}catch(e){const err=new Error('The url provided should have a proper protocol and hostname.');return Promise.reject(err);}
if(parsedURL.protocol!=='https:'&&parsedURL.hostname!=='localhost'){log.warn('Lighthouse','The URL provided should be on HTTPS');log.warn('Lighthouse','Performance stats will be skewed redirecting from HTTP to HTTPS.');}
opts.url=parsedURL.href;const validPassesAndAudits=config.passes&&config.audits;const validArtifactsAndAudits=config.artifacts&&config.audits;let run=Promise.resolve();if(validPassesAndAudits||validArtifactsAndAudits){if(validPassesAndAudits){opts.driver=opts.driverMock||new Driver(connection);run=run.then(_=>GatherRunner.run(config.passes,opts));}else if(validArtifactsAndAudits){run=run.then(_=>{return Object.assign(GatherRunner.instantiateComputedArtifacts(),config.artifacts);});}
run=run.then(artifacts=>{for(const passName of Object.keys(artifacts.traces||{})){const trace=artifacts.traces[passName];if(!Array.isArray(trace.traceEvents)){throw new Error(passName+' trace was invalid. `traceEvents` was not an array.');}}
return artifacts;});const auditResults=[];for(const audit of config.audits){run=run.then(artifacts=>{return Runner._runAudit(audit,artifacts).then(ret=>auditResults.push(ret)).then(_=>artifacts);});}
run=run.then(artifacts=>{return{artifacts,auditResults};});}else if(config.auditResults){const artifacts=Object.assign(GatherRunner.instantiateComputedArtifacts(),config.artifacts||{});run=run.then(_=>{return{artifacts,auditResults:config.auditResults};});}else{const err=Error('The config must provide passes and audits, artifacts and audits, or auditResults');return Promise.reject(err);}
run=run.then(runResults=>{const formattedAudits=runResults.auditResults.reduce((formatted,audit)=>{formatted[audit.name]=audit;return formatted;},{});let aggregations=[];if(config.aggregations){aggregations=config.aggregations.map(a=>Aggregate.aggregate(a,runResults.auditResults));}
return{lighthouseVersion:require('../package').version,generatedTime:(new Date()).toJSON(),initialUrl:opts.initialUrl,url:opts.url,audits:formattedAudits,artifacts:runResults.artifacts,aggregations};});return run;}
static _runAudit(audit,artifacts){const status=`Evaluating: ${audit.meta.description}`;return Promise.resolve().then(_=>{log.log('status',status);for(const artifactName of audit.meta.requiredArtifacts){const noArtifact=typeof artifacts[artifactName]==='undefined';const noTrace=artifactName==='traces'&&!artifacts.traces[Audit.DEFAULT_PASS];if(noArtifact||noTrace){log.warn('Runner',`${artifactName} gatherer, required by audit ${audit.meta.name}, did not run.`);return audit.generateAuditResult({rawValue:-1,debugString:`Required ${artifactName} gatherer did not run.`});}}
return audit.audit(artifacts);}).then(result=>{log.verbose('statusEnd',status);return result;});}
static getAuditList(){const fileList=[...["accessibility","audit.js","cache-start-url.js","content-width.js","critical-request-chains.js","dobetterweb","estimated-input-latency.js","first-meaningful-paint.js","is-on-https.js","manifest-background-color.js","manifest-display.js","manifest-exists.js","manifest-icons-min-144.js","manifest-icons-min-192.js","manifest-name.js","manifest-short-name-length.js","manifest-short-name.js","manifest-start-url.js","manifest-theme-color.js","redirects-http.js","screenshots.js","service-worker.js","speed-index-metric.js","theme-color-meta.js","time-to-interactive.js","unused-css-rules.js","user-timings.js","viewport.js","without-javascript.js","works-offline.js"],...["appcache-manifest.js","external-anchors-use-rel-noopener.js","geolocation-on-start.js","link-blocking-first-paint.js","no-console-time.js","no-datenow.js","no-document-write.js","no-mutation-events.js","no-old-flexbox.js","no-websql.js","notification-on-start.js","script-blocking-first-paint.js","uses-http2.js","uses-passive-event-listeners.js"].map(f=>`dobetterweb/${f}`),...["aria-allowed-attr.js","aria-required-attr.js","aria-valid-attr-value.js","aria-valid-attr.js","axe-audit.js","color-contrast.js","image-alt.js","label.js","tabindex.js"].map(f=>`accessibility/${f}`)];return fileList.filter(f=>{return/\.js$/.test(f)&&f!=='audit.js'&&f!=='accessibility/axe-audit.js';}).sort();}
static getGathererList(){const fileList=[...["accessibility.js","cache-contents.js","content-width.js","css-usage.js","dobetterweb","gatherer.js","html-without-javascript.js","html.js","http-redirect.js","https.js","manifest.js","offline.js","service-worker.js","styles.js","theme-color.js","url.js","viewport.js"],...["all-event-listeners.js","anchors-with-no-rel-noopener.js","appcache.js","console-time-usage.js","datenow.js","document-write.js","geolocation-on-start.js","notification-on-start.js","tags-blocking-first-paint.js","websql.js"].map(f=>`dobetterweb/${f}`)];return fileList.filter(f=>/\.js$/.test(f)&&f!=='gatherer.js').sort();}
static resolvePlugin(plugin,configDir,category){try{return require.resolve(plugin);}catch(e){}
const cwdPath=path.resolve(process.cwd(),plugin);try{return require.resolve(cwdPath);}catch(e){}
const errorString='Unable to locate '+
(category?`${category}: `:'')+`${plugin} (tried to require() from '${__dirname}' and load from '${cwdPath}'`;if(!configDir){throw new Error(errorString+')');}
const relativePath=path.resolve(configDir,plugin);try{return require.resolve(relativePath);}catch(requireError){}
throw new Error(errorString+` and '${relativePath}')`);}}
module.exports=Runner;}).call(this,require('_process'),"/../lighthouse-core")},{"../package":286,"./aggregator/aggregate":1,"./audits/audit":3,"./gather/driver.js":16,"./gather/gather-runner":17,"./lib/log":24,"./lib/url-shim":30,"_process":205,"path":204}],34:[function(require,module,exports){(function(global){"use strict";'use strict';global.tr=function(){if(global.tr){console.warn('Base was multiply initialized. First init wins.');return global.tr;}function exportPath(name){var parts=name.split('.');var cur=global;for(var part;parts.length&&(part=parts.shift());){if(part in cur){cur=cur[part];}else{cur=cur[part]={};}}return cur;};function isExported(name){var parts=name.split('.');var cur=global;for(var part;parts.length&&(part=parts.shift());){if(part in cur){cur=cur[part];}else{return false;}}return true;}function isDefined(name){var parts=name.split('.');var curObject=global;for(var i=0;i<parts.length;i++){var partName=parts[i];var nextObject=curObject[partName];if(nextObject===undefined)return false;curObject=nextObject;}return true;}var panicElement=undefined;var rawPanicMessages=[];function showPanicElementIfNeeded(){if(panicElement)return;var panicOverlay=document.createElement('div');panicOverlay.style.backgroundColor='white';panicOverlay.style.border='3px solid red';panicOverlay.style.boxSizing='border-box';panicOverlay.style.color='black';panicOverlay.style.display='-webkit-flex';panicOverlay.style.height='100%';panicOverlay.style.left=0;panicOverlay.style.padding='8px';panicOverlay.style.position='fixed';panicOverlay.style.top=0;panicOverlay.style.webkitFlexDirection='column';panicOverlay.style.width='100%';panicElement=document.createElement('div');panicElement.style.webkitFlex='1 1 auto';panicElement.style.overflow='auto';panicOverlay.appendChild(panicElement);if(!document.body){setTimeout(function(){document.body.appendChild(panicOverlay);},150);}else{document.body.appendChild(panicOverlay);}}function showPanic(panicTitle,panicDetails){if(tr.isHeadless){if(panicDetails instanceof Error)throw panicDetails;throw new Error('Panic: '+panicTitle+':\n'+panicDetails);}if(panicDetails instanceof Error)panicDetails=panicDetails.stack;showPanicElementIfNeeded();var panicMessageEl=document.createElement('div');panicMessageEl.innerHTML='<h2 id="message"></h2>'+'<pre id="details"></pre>';panicMessageEl.querySelector('#message').textContent=panicTitle;panicMessageEl.querySelector('#details').textContent=panicDetails;panicElement.appendChild(panicMessageEl);rawPanicMessages.push({title:panicTitle,details:panicDetails});}function hasPanic(){return rawPanicMessages.length!==0;}function getPanicText(){return rawPanicMessages.map(function(msg){return msg.title;}).join(', ');}function exportTo(namespace,fn){var obj=exportPath(namespace);var exports=fn();for(var propertyName in exports){var propertyDescriptor=Object.getOwnPropertyDescriptor(exports,propertyName);if(propertyDescriptor)Object.defineProperty(obj,propertyName,propertyDescriptor);}};function initialize(){if(global.isVinn){tr.isVinn=true;}else if(global.process&&global.process.versions.node){tr.isNode=true;}else{tr.isVinn=false;tr.isNode=false;tr.doc=document;tr.isMac=/Mac/.test(navigator.platform);tr.isWindows=/Win/.test(navigator.platform);tr.isChromeOS=/CrOS/.test(navigator.userAgent);tr.isLinux=/Linux/.test(navigator.userAgent);}tr.isHeadless=tr.isVinn||tr.isNode;}return{initialize:initialize,exportTo:exportTo,isExported:isExported,isDefined:isDefined,showPanic:showPanic,hasPanic:hasPanic,getPanicText:getPanicText};}();tr.initialize();}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],35:[function(require,module,exports){(function(global){"use strict";require("./base.js");'use strict';global.tr.exportTo('tr.b',function(){function Base64(){}function b64ToUint6(nChr){if(nChr>64&&nChr<91)return nChr-65;if(nChr>96&&nChr<123)return nChr-71;if(nChr>47&&nChr<58)return nChr+4;if(nChr===43)return 62;if(nChr===47)return 63;return 0;}Base64.getDecodedBufferLength=function(input){return input.length*3+1>>2;};Base64.EncodeArrayBufferToString=function(input){var binary='';var bytes=new Uint8Array(input);var len=bytes.byteLength;for(var i=0;i<len;i++)binary+=String.fromCharCode(bytes[i]);return btoa(binary);};Base64.DecodeToTypedArray=function(input,output){var nInLen=input.length;var nOutLen=nInLen*3+1>>2;var nMod3=0;var nMod4=0;var nUint24=0;var nOutIdx=0;if(nOutLen>output.byteLength)throw new Error('Output buffer too small to decode.');for(var nInIdx=0;nInIdx<nInLen;nInIdx++){nMod4=nInIdx&3;nUint24|=b64ToUint6(input.charCodeAt(nInIdx))<<18-6*nMod4;if(nMod4===3||nInLen-nInIdx===1){for(nMod3=0;nMod3<3&&nOutIdx<nOutLen;nMod3++,nOutIdx++){output.setUint8(nOutIdx,nUint24>>>(16>>>nMod3&24)&255);}nUint24=0;}}return nOutIdx-1;};Base64.btoa=function(input){return btoa(input);};Base64.atob=function(input){return atob(input);};return{Base64:Base64};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./base.js":34}],36:[function(require,module,exports){(function(global){"use strict";require("./base.js");'use strict';global.tr.exportTo('tr.b',function(){var categoryPartsFor={};function getCategoryParts(category){var parts=categoryPartsFor[category];if(parts!==undefined)return parts;parts=category.split(',');categoryPartsFor[category]=parts;return parts;}return{getCategoryParts:getCategoryParts};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./base.js":34}],37:[function(require,module,exports){(function(global){"use strict";require("./base.js");'use strict';global.tr.exportTo('tr.b',function(){function clamp01(value){return Math.max(0,Math.min(1,value));}function Color(opt_r,opt_g,opt_b,opt_a){this.r=Math.floor(opt_r)||0;this.g=Math.floor(opt_g)||0;this.b=Math.floor(opt_b)||0;this.a=opt_a;}Color.fromString=function(str){var tmp;var values;if(str.substr(0,4)=='rgb('){tmp=str.substr(4,str.length-5);values=tmp.split(',').map(function(v){return v.replace(/^\s+/,'','g');});if(values.length!=3)throw new Error('Malformatted rgb-expression');return new Color(parseInt(values[0]),parseInt(values[1]),parseInt(values[2]));}else if(str.substr(0,5)=='rgba('){tmp=str.substr(5,str.length-6);values=tmp.split(',').map(function(v){return v.replace(/^\s+/,'','g');});if(values.length!=4)throw new Error('Malformatted rgb-expression');return new Color(parseInt(values[0]),parseInt(values[1]),parseInt(values[2]),parseFloat(values[3]));}else if(str[0]=='#'&&str.length==7){return new Color(parseInt(str.substr(1,2),16),parseInt(str.substr(3,2),16),parseInt(str.substr(5,2),16));}else{throw new Error('Unrecognized string format.');}};Color.lerp=function(a,b,percent){if(a.a!==undefined&&b.a!==undefined)return Color.lerpRGBA(a,b,percent);return Color.lerpRGB(a,b,percent);};Color.lerpRGB=function(a,b,percent){return new Color((b.r-a.r)*percent+a.r,(b.g-a.g)*percent+a.g,(b.b-a.b)*percent+a.b);};Color.lerpRGBA=function(a,b,percent){return new Color((b.r-a.r)*percent+a.r,(b.g-a.g)*percent+a.g,(b.b-a.b)*percent+a.b,(b.a-a.a)*percent+a.a);};Color.fromDict=function(dict){return new Color(dict.r,dict.g,dict.b,dict.a);};Color.fromHSLExplicit=function(h,s,l,a){var r,g,b;function hue2rgb(p,q,t){if(t<0)t+=1;if(t>1)t-=1;if(t<1/6)return p+(q-p)*6*t;if(t<1/2)return q;if(t<2/3)return p+(q-p)*(2/3-t)*6;return p;}if(s===0){r=g=b=l;}else{var q=l<0.5?l*(1+s):l+s-l*s;var p=2*l-q;r=hue2rgb(p,q,h+1/3);g=hue2rgb(p,q,h);b=hue2rgb(p,q,h-1/3);}return new Color(Math.floor(r*255),Math.floor(g*255),Math.floor(b*255),a);};Color.fromHSL=function(hsl){return Color.fromHSLExplicit(hsl.h,hsl.s,hsl.l,hsl.a);};Color.prototype={clone:function(){var c=new Color();c.r=this.r;c.g=this.g;c.b=this.b;c.a=this.a;return c;},blendOver:function(bgColor){var oneMinusThisAlpha=1-this.a;var outA=this.a+bgColor.a*oneMinusThisAlpha;var bgBlend=bgColor.a*oneMinusThisAlpha/bgColor.a;return new Color(this.r*this.a+bgColor.r*bgBlend,this.g*this.a+bgColor.g*bgBlend,this.b*this.a+bgColor.b*bgBlend,outA);},brighten:function(opt_k){var k;k=opt_k||0.45;return new Color(Math.min(255,this.r+Math.floor(this.r*k)),Math.min(255,this.g+Math.floor(this.g*k)),Math.min(255,this.b+Math.floor(this.b*k)),this.a);},lighten:function(k,opt_maxL){var maxL=opt_maxL!==undefined?opt_maxL:1.0;var hsl=this.toHSL();hsl.l=clamp01(hsl.l+k);return Color.fromHSL(hsl);},darken:function(opt_k){var k;if(opt_k!==undefined)k=opt_k;else k=0.45;return new Color(Math.min(255,this.r-Math.floor(this.r*k)),Math.min(255,this.g-Math.floor(this.g*k)),Math.min(255,this.b-Math.floor(this.b*k)),this.a);},desaturate:function(opt_desaturateFactor){var desaturateFactor;if(opt_desaturateFactor!==undefined)desaturateFactor=opt_desaturateFactor;else desaturateFactor=1;var hsl=this.toHSL();hsl.s=clamp01(hsl.s*(1-desaturateFactor));return Color.fromHSL(hsl);},withAlpha:function(a){return new Color(this.r,this.g,this.b,a);},toString:function(){if(this.a!==undefined){return'rgba('+this.r+','+this.g+','+this.b+','+this.a+')';}return'rgb('+this.r+','+this.g+','+this.b+')';},toHSL:function(){var r=this.r/255;var g=this.g/255;var b=this.b/255;var max=Math.max(r,g,b);var min=Math.min(r,g,b);var h,s;var l=(max+min)/2;if(min===max){h=0;s=0;}else{var delta=max-min;if(l>0.5)s=delta/(2-max-min);else s=delta/(max+min);if(r===max){h=(g-b)/delta;if(g<b)h+=6;}else if(g===max){h=2+(b-r)/delta;}else{h=4+(r-g)/delta;}h/=6;}return{h:h,s:s,l:l,a:this.a};},toStringWithAlphaOverride:function(alpha){return'rgba('+this.r+','+this.g+','+this.b+','+alpha+')';}};return{Color:Color};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./base.js":34}],38:[function(require,module,exports){(function(global){"use strict";require("./base.js");require("./color.js");require("./iteration_helpers.js");'use strict';global.tr.exportTo('tr.b',function(){var generalPurposeColors=[new tr.b.Color(122,98,135),new tr.b.Color(150,83,105),new tr.b.Color(44,56,189),new tr.b.Color(99,86,147),new tr.b.Color(104,129,107),new tr.b.Color(130,178,55),new tr.b.Color(87,109,147),new tr.b.Color(111,145,88),new tr.b.Color(81,152,131),new tr.b.Color(142,91,111),new tr.b.Color(81,163,70),new tr.b.Color(148,94,86),new tr.b.Color(144,89,118),new tr.b.Color(83,150,97),new tr.b.Color(105,94,139),new tr.b.Color(89,144,122),new tr.b.Color(105,119,128),new tr.b.Color(96,128,137),new tr.b.Color(145,88,145),new tr.b.Color(88,145,144),new tr.b.Color(90,100,143),new tr.b.Color(121,97,136),new tr.b.Color(111,160,73),new tr.b.Color(112,91,142),new tr.b.Color(86,147,86),new tr.b.Color(63,100,170),new tr.b.Color(81,152,107),new tr.b.Color(60,164,173),new tr.b.Color(143,72,161),new tr.b.Color(159,74,86)];var reservedColorsByName={thread_state_uninterruptible:new tr.b.Color(182,125,143),thread_state_iowait:new tr.b.Color(255,140,0),thread_state_running:new tr.b.Color(126,200,148),thread_state_runnable:new tr.b.Color(133,160,210),thread_state_sleeping:new tr.b.Color(240,240,240),thread_state_unknown:new tr.b.Color(199,155,125),background_memory_dump:new tr.b.Color(0,180,180),light_memory_dump:new tr.b.Color(0,0,180),detailed_memory_dump:new tr.b.Color(180,0,180),generic_work:new tr.b.Color(125,125,125),good:new tr.b.Color(0,125,0),bad:new tr.b.Color(180,125,0),terrible:new tr.b.Color(180,0,0),black:new tr.b.Color(0,0,0),rail_response:new tr.b.Color(67,135,253),rail_animation:new tr.b.Color(244,74,63),rail_idle:new tr.b.Color(238,142,0),rail_load:new tr.b.Color(13,168,97),startup:new tr.b.Color(230,230,0),used_memory_column:new tr.b.Color(0,0,255),older_used_memory_column:new tr.b.Color(153,204,255),tracing_memory_column:new tr.b.Color(153,153,153),heap_dump_stack_frame:new tr.b.Color(128,128,128),heap_dump_object_type:new tr.b.Color(0,0,255),heap_dump_child_node_arrow:new tr.b.Color(204,102,0),cq_build_running:new tr.b.Color(255,255,119),cq_build_passed:new tr.b.Color(153,238,102),cq_build_failed:new tr.b.Color(238,136,136),cq_build_abandoned:new tr.b.Color(187,187,187),cq_build_attempt_runnig:new tr.b.Color(222,222,75),cq_build_attempt_passed:new tr.b.Color(103,218,35),cq_build_attempt_failed:new tr.b.Color(197,81,81)};var numGeneralPurposeColorIds=generalPurposeColors.length;var numReservedColorIds=tr.b.dictionaryLength(reservedColorsByName);var numColorsPerVariant=numGeneralPurposeColorIds+numReservedColorIds;function ColorScheme(){}var paletteBase=[];paletteBase.push.apply(paletteBase,generalPurposeColors);paletteBase.push.apply(paletteBase,tr.b.dictionaryValues(reservedColorsByName));ColorScheme.colors=[];ColorScheme.properties={};ColorScheme.properties={numColorsPerVariant:numColorsPerVariant};function pushVariant(func){var variantColors=paletteBase.map(func);ColorScheme.colors.push.apply(ColorScheme.colors,variantColors);}pushVariant(function(c){return c;});ColorScheme.properties.brightenedOffsets=[];ColorScheme.properties.brightenedOffsets.push(ColorScheme.colors.length);pushVariant(function(c){return c.lighten(0.3,0.9);});ColorScheme.properties.brightenedOffsets.push(ColorScheme.colors.length);pushVariant(function(c){return c.lighten(0.48,0.9);});ColorScheme.properties.brightenedOffsets.push(ColorScheme.colors.length);pushVariant(function(c){return c.lighten(0.65,0.9);});ColorScheme.properties.dimmedOffsets=[];ColorScheme.properties.dimmedOffsets.push(ColorScheme.colors.length);pushVariant(function(c){return c.desaturate();});ColorScheme.properties.dimmedOffsets.push(ColorScheme.colors.length);pushVariant(function(c){return c.desaturate(0.5);});ColorScheme.properties.dimmedOffsets.push(ColorScheme.colors.length);pushVariant(function(c){return c.desaturate(0.3);});ColorScheme.colorsAsStrings=ColorScheme.colors.map(function(c){return c.toString();});var reservedColorNameToIdMap=function(){var m=new Map();var i=generalPurposeColors.length;tr.b.iterItems(reservedColorsByName,function(key,value){m.set(key,i++);});return m;}();ColorScheme.getColorIdForReservedName=function(name){var id=reservedColorNameToIdMap.get(name);if(id===undefined)throw new Error('Unrecognized color ')+name;return id;};ColorScheme.getColorForReservedNameAsString=function(reservedName){var id=ColorScheme.getColorIdForReservedName(reservedName);return ColorScheme.colorsAsStrings[id];};ColorScheme.getStringHash=function(name){var hash=0;for(var i=0;i<name.length;++i)hash=(hash+37*hash+11*name.charCodeAt(i))%0xFFFFFFFF;return hash;};var stringColorIdCache=new Map();ColorScheme.getColorIdForGeneralPurposeString=function(string){if(stringColorIdCache.get(string)===undefined){var hash=ColorScheme.getStringHash(string);stringColorIdCache.set(string,hash%numGeneralPurposeColorIds);}return stringColorIdCache.get(string);};return{ColorScheme:ColorScheme};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./base.js":34,"./color.js":37,"./iteration_helpers.js":47}],39:[function(require,module,exports){(function(global){"use strict";require("./event_target.js");'use strict';global.tr.exportTo('tr.b',function(){var Event;if(tr.isHeadless){function HeadlessEvent(type,opt_bubbles,opt_preventable){this.type=type;this.bubbles=opt_bubbles!==undefined?!!opt_bubbles:false;this.cancelable=opt_preventable!==undefined?!!opt_preventable:false;this.defaultPrevented=false;this.cancelBubble=false;};HeadlessEvent.prototype={preventDefault:function(){this.defaultPrevented=true;},stopPropagation:function(){this.cancelBubble=true;}};Event=HeadlessEvent;}else{function TrEvent(type,opt_bubbles,opt_preventable){var e=tr.doc.createEvent('Event');e.initEvent(type,!!opt_bubbles,!!opt_preventable);e.__proto__=global.Event.prototype;return e;};TrEvent.prototype={__proto__:global.Event.prototype};Event=TrEvent;}function dispatchSimpleEvent(target,type,opt_bubbles,opt_cancelable,opt_fields){var e=new tr.b.Event(type,opt_bubbles,opt_cancelable);if(opt_fields){tr.b.iterItems(opt_fields,function(name,value){e[name]=value;});}return target.dispatchEvent(e);}return{Event:Event,dispatchSimpleEvent:dispatchSimpleEvent};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./event_target.js":40}],40:[function(require,module,exports){(function(global){"use strict";require("./base.js");'use strict';global.tr.exportTo('tr.b',function(){function EventTarget(){}EventTarget.decorate=function(target){for(var k in EventTarget.prototype){if(k=='decorate')continue;var v=EventTarget.prototype[k];if(typeof v!=='function')continue;target[k]=v;}};EventTarget.prototype={addEventListener:function(type,handler){if(!this.listeners_)this.listeners_=Object.create(null);if(!(type in this.listeners_)){this.listeners_[type]=[handler];}else{var handlers=this.listeners_[type];if(handlers.indexOf(handler)<0)handlers.push(handler);}},removeEventListener:function(type,handler){if(!this.listeners_)return;if(type in this.listeners_){var handlers=this.listeners_[type];var index=handlers.indexOf(handler);if(index>=0){if(handlers.length==1)delete this.listeners_[type];else handlers.splice(index,1);}}},dispatchEvent:function(event){if(!this.listeners_)return true;var self=this;event.__defineGetter__('target',function(){return self;});var realPreventDefault=event.preventDefault;event.preventDefault=function(){realPreventDefault.call(this);this.rawReturnValue=false;};var type=event.type;var prevented=0;if(type in this.listeners_){var handlers=this.listeners_[type].concat();for(var i=0,handler;handler=handlers[i];i++){if(handler.handleEvent)prevented|=handler.handleEvent.call(handler,event)===false;else prevented|=handler.call(this,event)===false;}}return!prevented&&event.rawReturnValue;},hasEventListener:function(type){return this.listeners_[type]!==undefined;}};var EventTargetHelper={decorate:function(target){for(var k in EventTargetHelper){if(k=='decorate')continue;var v=EventTargetHelper[k];if(typeof v!=='function')continue;target[k]=v;}target.listenerCounts_={};},addEventListener:function(type,listener,useCapture){this.__proto__.addEventListener.call(this,type,listener,useCapture);if(this.listenerCounts_[type]===undefined)this.listenerCounts_[type]=0;this.listenerCounts_[type]++;},removeEventListener:function(type,listener,useCapture){this.__proto__.removeEventListener.call(this,type,listener,useCapture);this.listenerCounts_[type]--;},hasEventListener:function(type){return this.listenerCounts_[type]>0;}};return{EventTarget:EventTarget,EventTargetHelper:EventTargetHelper};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./base.js":34}],41:[function(require,module,exports){(function(global){"use strict";require("./event_target.js");require("./extension_registry_base.js");require("./extension_registry_basic.js");require("./extension_registry_type_based.js");require("./iteration_helpers.js");'use strict';global.tr.exportTo('tr.b',function(){function decorateExtensionRegistry(registry,registryOptions){if(registry.register)throw new Error('Already has registry');registryOptions.freeze();if(registryOptions.mode==tr.b.BASIC_REGISTRY_MODE){tr.b._decorateBasicExtensionRegistry(registry,registryOptions);}else if(registryOptions.mode==tr.b.TYPE_BASED_REGISTRY_MODE){tr.b._decorateTypeBasedExtensionRegistry(registry,registryOptions);}else{throw new Error('Unrecognized mode');}if(registry.addEventListener===undefined)tr.b.EventTarget.decorate(registry);}return{decorateExtensionRegistry:decorateExtensionRegistry};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./event_target.js":40,"./extension_registry_base.js":42,"./extension_registry_basic.js":43,"./extension_registry_type_based.js":44,"./iteration_helpers.js":47}],42:[function(require,module,exports){(function(global){"use strict";require("./base.js");'use strict';global.tr.exportTo('tr.b',function(){function RegisteredTypeInfo(constructor,metadata){this.constructor=constructor;this.metadata=metadata;};var BASIC_REGISTRY_MODE='BASIC_REGISTRY_MODE';var TYPE_BASED_REGISTRY_MODE='TYPE_BASED_REGISTRY_MODE';var ALL_MODES={BASIC_REGISTRY_MODE:true,TYPE_BASED_REGISTRY_MODE:true};function ExtensionRegistryOptions(mode){if(mode===undefined)throw new Error('Mode is required');if(!ALL_MODES[mode])throw new Error('Not a mode.');this.mode_=mode;this.defaultMetadata_={};this.defaultConstructor_=undefined;this.defaultTypeInfo_=undefined;this.frozen_=false;}ExtensionRegistryOptions.prototype={freeze:function(){if(this.frozen_)throw new Error('Frozen');this.frozen_=true;},get mode(){return this.mode_;},get defaultMetadata(){return this.defaultMetadata_;},set defaultMetadata(defaultMetadata){if(this.frozen_)throw new Error('Frozen');this.defaultMetadata_=defaultMetadata;this.defaultTypeInfo_=undefined;},get defaultConstructor(){return this.defaultConstructor_;},set defaultConstructor(defaultConstructor){if(this.frozen_)throw new Error('Frozen');this.defaultConstructor_=defaultConstructor;this.defaultTypeInfo_=undefined;},get defaultTypeInfo(){if(this.defaultTypeInfo_===undefined&&this.defaultConstructor_){this.defaultTypeInfo_=new RegisteredTypeInfo(this.defaultConstructor,this.defaultMetadata);}return this.defaultTypeInfo_;},validateConstructor:function(constructor){if(!this.mandatoryBaseClass)return;var curProto=constructor.prototype.__proto__;var ok=false;while(curProto){if(curProto===this.mandatoryBaseClass.prototype){ok=true;break;}curProto=curProto.__proto__;}if(!ok)throw new Error(constructor+'must be subclass of '+registry);}};return{BASIC_REGISTRY_MODE:BASIC_REGISTRY_MODE,TYPE_BASED_REGISTRY_MODE:TYPE_BASED_REGISTRY_MODE,ExtensionRegistryOptions:ExtensionRegistryOptions,RegisteredTypeInfo:RegisteredTypeInfo};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./base.js":34}],43:[function(require,module,exports){(function(global){"use strict";require("./event.js");require("./extension_registry_base.js");'use strict';global.tr.exportTo('tr.b',function(){var RegisteredTypeInfo=tr.b.RegisteredTypeInfo;var ExtensionRegistryOptions=tr.b.ExtensionRegistryOptions;function decorateBasicExtensionRegistry(registry,extensionRegistryOptions){var savedStateStack=[];registry.registeredTypeInfos_=[];registry.register=function(constructor,opt_metadata){if(registry.findIndexOfRegisteredConstructor(constructor)!==undefined)throw new Error('Handler already registered for '+constructor);extensionRegistryOptions.validateConstructor(constructor);var metadata={};for(var k in extensionRegistryOptions.defaultMetadata)metadata[k]=extensionRegistryOptions.defaultMetadata[k];if(opt_metadata){for(var k in opt_metadata)metadata[k]=opt_metadata[k];}var typeInfo=new RegisteredTypeInfo(constructor,metadata);var e=new tr.b.Event('will-register');e.typeInfo=typeInfo;registry.dispatchEvent(e);registry.registeredTypeInfos_.push(typeInfo);e=new tr.b.Event('registry-changed');registry.dispatchEvent(e);};registry.pushCleanStateBeforeTest=function(){savedStateStack.push(registry.registeredTypeInfos_);registry.registeredTypeInfos_=[];var e=new tr.b.Event('registry-changed');registry.dispatchEvent(e);};registry.popCleanStateAfterTest=function(){registry.registeredTypeInfos_=savedStateStack[0];savedStateStack.splice(0,1);var e=new tr.b.Event('registry-changed');registry.dispatchEvent(e);};registry.findIndexOfRegisteredConstructor=function(constructor){for(var i=0;i<registry.registeredTypeInfos_.length;i++)if(registry.registeredTypeInfos_[i].constructor==constructor)return i;return undefined;};registry.unregister=function(constructor){var foundIndex=registry.findIndexOfRegisteredConstructor(constructor);if(foundIndex===undefined)throw new Error(constructor+' not registered');registry.registeredTypeInfos_.splice(foundIndex,1);var e=new tr.b.Event('registry-changed');registry.dispatchEvent(e);};registry.getAllRegisteredTypeInfos=function(){return registry.registeredTypeInfos_;};registry.findTypeInfo=function(constructor){var foundIndex=this.findIndexOfRegisteredConstructor(constructor);if(foundIndex!==undefined)return this.registeredTypeInfos_[foundIndex];return undefined;};registry.findTypeInfoMatching=function(predicate,opt_this){opt_this=opt_this?opt_this:undefined;for(var i=0;i<registry.registeredTypeInfos_.length;++i){var typeInfo=registry.registeredTypeInfos_[i];if(predicate.call(opt_this,typeInfo))return typeInfo;}return extensionRegistryOptions.defaultTypeInfo;};registry.findTypeInfoWithName=function(name){if(typeof name!=='string')throw new Error('Name is not a string.');var typeInfo=registry.findTypeInfoMatching(function(ti){return ti.constructor.name===name;});if(typeInfo)return typeInfo;return undefined;};}return{_decorateBasicExtensionRegistry:decorateBasicExtensionRegistry};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./event.js":39,"./extension_registry_base.js":42}],44:[function(require,module,exports){(function(global){"use strict";require("./category_util.js");require("./event.js");require("./extension_registry_base.js");'use strict';global.tr.exportTo('tr.b',function(){var getCategoryParts=tr.b.getCategoryParts;var RegisteredTypeInfo=tr.b.RegisteredTypeInfo;var ExtensionRegistryOptions=tr.b.ExtensionRegistryOptions;function decorateTypeBasedExtensionRegistry(registry,extensionRegistryOptions){var savedStateStack=[];registry.registeredTypeInfos_=[];registry.categoryPartToTypeInfoMap_=new Map();registry.typeNameToTypeInfoMap_=new Map();registry.register=function(constructor,metadata){extensionRegistryOptions.validateConstructor(constructor);var typeInfo=new RegisteredTypeInfo(constructor,metadata||extensionRegistryOptions.defaultMetadata);typeInfo.typeNames=[];typeInfo.categoryParts=[];if(metadata&&metadata.typeName)typeInfo.typeNames.push(metadata.typeName);if(metadata&&metadata.typeNames){typeInfo.typeNames.push.apply(typeInfo.typeNames,metadata.typeNames);}if(metadata&&metadata.categoryParts){typeInfo.categoryParts.push.apply(typeInfo.categoryParts,metadata.categoryParts);}if(typeInfo.typeNames.length===0&&typeInfo.categoryParts.length===0)throw new Error('typeName or typeNames must be provided');typeInfo.typeNames.forEach(function(typeName){if(registry.typeNameToTypeInfoMap_.has(typeName))throw new Error('typeName '+typeName+' already registered');});typeInfo.categoryParts.forEach(function(categoryPart){if(registry.categoryPartToTypeInfoMap_.has(categoryPart)){throw new Error('categoryPart '+categoryPart+' already registered');}});var e=new tr.b.Event('will-register');e.typeInfo=typeInfo;registry.dispatchEvent(e);typeInfo.typeNames.forEach(function(typeName){registry.typeNameToTypeInfoMap_.set(typeName,typeInfo);});typeInfo.categoryParts.forEach(function(categoryPart){registry.categoryPartToTypeInfoMap_.set(categoryPart,typeInfo);});registry.registeredTypeInfos_.push(typeInfo);var e=new tr.b.Event('registry-changed');registry.dispatchEvent(e);};registry.pushCleanStateBeforeTest=function(){savedStateStack.push({registeredTypeInfos:registry.registeredTypeInfos_,typeNameToTypeInfoMap:registry.typeNameToTypeInfoMap_,categoryPartToTypeInfoMap:registry.categoryPartToTypeInfoMap_});registry.registeredTypeInfos_=[];registry.typeNameToTypeInfoMap_=new Map();registry.categoryPartToTypeInfoMap_=new Map();var e=new tr.b.Event('registry-changed');registry.dispatchEvent(e);};registry.popCleanStateAfterTest=function(){var state=savedStateStack[0];savedStateStack.splice(0,1);registry.registeredTypeInfos_=state.registeredTypeInfos;registry.typeNameToTypeInfoMap_=state.typeNameToTypeInfoMap;registry.categoryPartToTypeInfoMap_=state.categoryPartToTypeInfoMap;var e=new tr.b.Event('registry-changed');registry.dispatchEvent(e);};registry.unregister=function(constructor){var typeInfoIndex=-1;for(var i=0;i<registry.registeredTypeInfos_.length;i++){if(registry.registeredTypeInfos_[i].constructor==constructor){typeInfoIndex=i;break;}}if(typeInfoIndex===-1)throw new Error(constructor+' not registered');var typeInfo=registry.registeredTypeInfos_[typeInfoIndex];registry.registeredTypeInfos_.splice(typeInfoIndex,1);typeInfo.typeNames.forEach(function(typeName){registry.typeNameToTypeInfoMap_.delete(typeName);});typeInfo.categoryParts.forEach(function(categoryPart){registry.categoryPartToTypeInfoMap_.delete(categoryPart);});var e=new tr.b.Event('registry-changed');registry.dispatchEvent(e);};registry.getTypeInfo=function(category,typeName){if(category){var categoryParts=getCategoryParts(category);for(var i=0;i<categoryParts.length;i++){var categoryPart=categoryParts[i];var typeInfo=registry.categoryPartToTypeInfoMap_.get(categoryPart);if(typeInfo!==undefined)return typeInfo;}}var typeInfo=registry.typeNameToTypeInfoMap_.get(typeName);if(typeInfo!==undefined)return typeInfo;return extensionRegistryOptions.defaultTypeInfo;};registry.getConstructor=function(category,typeName){var typeInfo=registry.getTypeInfo(category,typeName);if(typeInfo)return typeInfo.constructor;return undefined;};}return{_decorateTypeBasedExtensionRegistry:decorateTypeBasedExtensionRegistry};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./category_util.js":36,"./event.js":39,"./extension_registry_base.js":42}],45:[function(require,module,exports){(function(global){"use strict";require("./base.js");'use strict';global.tr.exportTo('tr.b',function(){var nextGUID=1;var UUID4_PATTERN='xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx';var GUID={allocateSimple:function(){return nextGUID++;},getLastSimpleGuid:function(){return nextGUID-1;},allocateUUID4:function(){return UUID4_PATTERN.replace(/[xy]/g,function(c){var r=parseInt(Math.random()*16);if(c==='y')r=(r&3)+8;return r.toString(16);});}};return{GUID:GUID};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./base.js":34}],46:[function(require,module,exports){(function(global){"use strict";require("./base.js");'use strict';global.tr.exportTo('tr.b',function(){function max(a,b){if(a===undefined)return b;if(b===undefined)return a;return Math.max(a,b);}function IntervalTree(beginPositionCb,endPositionCb){this.beginPositionCb_=beginPositionCb;this.endPositionCb_=endPositionCb;this.root_=undefined;this.size_=0;}IntervalTree.prototype={insert:function(datum){var startPosition=this.beginPositionCb_(datum);var endPosition=this.endPositionCb_(datum);var node=new IntervalTreeNode(datum,startPosition,endPosition);this.size_++;this.root_=this.insertNode_(this.root_,node);this.root_.colour=Colour.BLACK;return datum;},insertNode_:function(root,node){if(root===undefined)return node;if(root.leftNode&&root.leftNode.isRed&&root.rightNode&&root.rightNode.isRed)this.flipNodeColour_(root);if(node.key<root.key)root.leftNode=this.insertNode_(root.leftNode,node);else if(node.key===root.key)root.merge(node);else root.rightNode=this.insertNode_(root.rightNode,node);if(root.rightNode&&root.rightNode.isRed&&(root.leftNode===undefined||!root.leftNode.isRed))root=this.rotateLeft_(root);if(root.leftNode&&root.leftNode.isRed&&root.leftNode.leftNode&&root.leftNode.leftNode.isRed)root=this.rotateRight_(root);return root;},rotateRight_:function(node){var sibling=node.leftNode;node.leftNode=sibling.rightNode;sibling.rightNode=node;sibling.colour=node.colour;node.colour=Colour.RED;return sibling;},rotateLeft_:function(node){var sibling=node.rightNode;node.rightNode=sibling.leftNode;sibling.leftNode=node;sibling.colour=node.colour;node.colour=Colour.RED;return sibling;},flipNodeColour_:function(node){node.colour=this.flipColour_(node.colour);node.leftNode.colour=this.flipColour_(node.leftNode.colour);node.rightNode.colour=this.flipColour_(node.rightNode.colour);},flipColour_:function(colour){return colour===Colour.RED?Colour.BLACK:Colour.RED;},updateHighValues:function(){this.updateHighValues_(this.root_);},updateHighValues_:function(node){if(node===undefined)return undefined;node.maxHighLeft=this.updateHighValues_(node.leftNode);node.maxHighRight=this.updateHighValues_(node.rightNode);return max(max(node.maxHighLeft,node.highValue),node.maxHighRight);},validateFindArguments_:function(queryLow,queryHigh){if(queryLow===undefined||queryHigh===undefined)throw new Error('queryLow and queryHigh must be defined');if(typeof queryLow!=='number'||typeof queryHigh!=='number')throw new Error('queryLow and queryHigh must be numbers');},findIntersection:function(queryLow,queryHigh){this.validateFindArguments_(queryLow,queryHigh);if(this.root_===undefined)return[];var ret=[];this.root_.appendIntersectionsInto_(ret,queryLow,queryHigh);return ret;},get size(){return this.size_;},get root(){return this.root_;},dump_:function(){if(this.root_===undefined)return[];return this.root_.dump();}};var Colour={RED:'red',BLACK:'black'};function IntervalTreeNode(datum,lowValue,highValue){this.lowValue_=lowValue;this.data_=[{datum:datum,high:highValue,low:lowValue}];this.colour_=Colour.RED;this.parentNode_=undefined;this.leftNode_=undefined;this.rightNode_=undefined;this.maxHighLeft_=undefined;this.maxHighRight_=undefined;}IntervalTreeNode.prototype={appendIntersectionsInto_:function(ret,queryLow,queryHigh){if(this.lowValue_>=queryHigh){if(!this.leftNode_)return;return this.leftNode_.appendIntersectionsInto_(ret,queryLow,queryHigh);}if(this.maxHighLeft_>queryLow){this.leftNode_.appendIntersectionsInto_(ret,queryLow,queryHigh);}if(this.highValue>queryLow){for(var i=this.data.length-1;i>=0;--i){if(this.data[i].high<queryLow)break;ret.push(this.data[i].datum);}}if(this.rightNode_){this.rightNode_.appendIntersectionsInto_(ret,queryLow,queryHigh);}},get colour(){return this.colour_;},set colour(colour){this.colour_=colour;},get key(){return this.lowValue_;},get lowValue(){return this.lowValue_;},get highValue(){return this.data_[this.data_.length-1].high;},set leftNode(left){this.leftNode_=left;},get leftNode(){return this.leftNode_;},get hasLeftNode(){return this.leftNode_!==undefined;},set rightNode(right){this.rightNode_=right;},get rightNode(){return this.rightNode_;},get hasRightNode(){return this.rightNode_!==undefined;},set parentNode(parent){this.parentNode_=parent;},get parentNode(){return this.parentNode_;},get isRootNode(){return this.parentNode_===undefined;},set maxHighLeft(high){this.maxHighLeft_=high;},get maxHighLeft(){return this.maxHighLeft_;},set maxHighRight(high){this.maxHighRight_=high;},get maxHighRight(){return this.maxHighRight_;},get data(){return this.data_;},get isRed(){return this.colour_===Colour.RED;},merge:function(node){for(var i=0;i<node.data.length;i++)this.data_.push(node.data[i]);this.data_.sort(function(a,b){return a.high-b.high;});},dump:function(){var ret={};if(this.leftNode_)ret['left']=this.leftNode_.dump();ret['data']=this.data_.map(function(d){return[d.low,d.high];});if(this.rightNode_)ret['right']=this.rightNode_.dump();return ret;}};return{IntervalTree:IntervalTree};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./base.js":34}],47:[function(require,module,exports){(function(global){"use strict";require("./base.js");'use strict';global.tr.exportTo('tr.b',function(){function asArray(x){var values=[];if(x[Symbol.iterator])for(var value of x)values.push(value);else for(var i=0;i<x.length;i++)values.push(x[i]);return values;}function getOnlyElement(iterable){var iterator=iterable[Symbol.iterator]();var firstIteration=iterator.next();if(firstIteration.done)throw new Error('getOnlyElement was passed an empty iterable.');var secondIteration=iterator.next();if(!secondIteration.done)throw new Error('getOnlyElement was passed an iterable with multiple elements.');return firstIteration.value;}function getFirstElement(iterable){var iterator=iterable[Symbol.iterator]();var result=iterator.next();if(result.done)throw new Error('getFirstElement was passed an empty iterable.');return result.value;}function compareArrays(x,y,elementCmp){var minLength=Math.min(x.length,y.length);for(var i=0;i<minLength;i++){var tmp=elementCmp(x[i],y[i]);if(tmp)return tmp;}if(x.length==y.length)return 0;if(x[i]===undefined)return-1;return 1;}function comparePossiblyUndefinedValues(x,y,cmp,opt_this){if(x!==undefined&&y!==undefined)return cmp.call(opt_this,x,y);if(x!==undefined)return-1;if(y!==undefined)return 1;return 0;}function compareNumericWithNaNs(x,y){if(!isNaN(x)&&!isNaN(y))return x-y;if(isNaN(x))return 1;if(isNaN(y))return-1;return 0;}function concatenateArrays(){var values=[];for(var i=0;i<arguments.length;i++){if(!(arguments[i]instanceof Array))throw new Error('Arguments '+i+'is not an array');values.push.apply(values,arguments[i]);}return values;}function concatenateObjects(){var result={};for(var i=0;i<arguments.length;i++){var object=arguments[i];for(var j in object){result[j]=object[j];}}return result;}function cloneDictionary(dict){var clone={};for(var k in dict){clone[k]=dict[k];}return clone;}function dictionaryKeys(dict){var keys=[];for(var key in dict)keys.push(key);return keys;}function dictionaryValues(dict){var values=[];for(var key in dict)values.push(dict[key]);return values;}function dictionaryLength(dict){var n=0;for(var key in dict)n++;return n;}function dictionaryContainsValue(dict,value){for(var key in dict)if(dict[key]===value)return true;return false;}function every(iterable,predicate){for(var x of iterable)if(!predicate(x))return false;return true;}function group(ary,callback,opt_this,opt_arrayConstructor){var arrayConstructor=opt_arrayConstructor||Array;var results={};for(var element of ary){var key=callback.call(opt_this,element);if(!(key in results))results[key]=new arrayConstructor();results[key].push(element);}return results;}function groupIntoMap(ary,callback,opt_this,opt_arrayConstructor){var arrayConstructor=opt_arrayConstructor||Array;var results=new Map();for(var element of ary){var key=callback.call(opt_this,element);var items=results.get(key);if(items===undefined){items=new arrayConstructor();results.set(key,items);}items.push(element);}return results;}function iterItems(dict,fn,opt_this){opt_this=opt_this||this;var keys=Object.keys(dict);for(var i=0;i<keys.length;i++){var key=keys[i];fn.call(opt_this,key,dict[key]);}}function mapItems(dict,fn,opt_this){opt_this=opt_this||this;var result={};var keys=Object.keys(dict);for(var i=0;i<keys.length;i++){var key=keys[i];result[key]=fn.call(opt_this,key,dict[key]);}return result;}function filterItems(dict,predicate,opt_this){opt_this=opt_this||this;var result={};var keys=Object.keys(dict);for(var i=0;i<keys.length;i++){var key=keys[i];var value=dict[key];if(predicate.call(opt_this,key,value))result[key]=value;}return result;}function iterObjectFieldsRecursively(object,func){if(!(object instanceof Object))return;if(object instanceof Array){for(var i=0;i<object.length;i++){func(object,i,object[i]);iterObjectFieldsRecursively(object[i],func);}return;}for(var key in object){var value=object[key];func(object,key,value);iterObjectFieldsRecursively(value,func);}}function invertArrayOfDicts(array,opt_dictGetter,opt_this){opt_this=opt_this||this;var result={};for(var i=0;i<array.length;i++){var item=array[i];if(item===undefined)continue;var dict=opt_dictGetter?opt_dictGetter.call(opt_this,item):item;if(dict===undefined)continue;for(var key in dict){var valueList=result[key];if(valueList===undefined)result[key]=valueList=new Array(array.length);valueList[i]=dict[key];}}return result;}function arrayToDict(array,valueToKeyFn,opt_this){opt_this=opt_this||this;var result={};var length=array.length;for(var i=0;i<length;i++){var value=array[i];var key=valueToKeyFn.call(opt_this,value);result[key]=value;}return result;}function identity(d){return d;}function findFirstIndexInArray(ary,opt_func,opt_this){var func=opt_func||identity;for(var i=0;i<ary.length;i++){if(func.call(opt_this,ary[i],i))return i;}return-1;}function findFirstInArray(ary,opt_func,opt_this){var i=findFirstIndexInArray(ary,opt_func,opt_func);if(i===-1)return undefined;return ary[i];}function findFirstKeyInDictMatching(dict,opt_func,opt_this){var func=opt_func||identity;for(var key in dict){if(func.call(opt_this,key,dict[key]))return key;}return undefined;}function mapValues(map){var values=[];for(var value of map.values())values.push(value);return values;}function iterMapItems(map,fn,opt_this){opt_this=opt_this||this;for(var key of map.keys())fn.call(opt_this,key,map.get(key));}return{asArray:asArray,concatenateArrays:concatenateArrays,concatenateObjects:concatenateObjects,compareArrays:compareArrays,comparePossiblyUndefinedValues:comparePossiblyUndefinedValues,compareNumericWithNaNs:compareNumericWithNaNs,cloneDictionary:cloneDictionary,dictionaryLength:dictionaryLength,dictionaryKeys:dictionaryKeys,dictionaryValues:dictionaryValues,dictionaryContainsValue:dictionaryContainsValue,every:every,getOnlyElement:getOnlyElement,getFirstElement:getFirstElement,group:group,groupIntoMap:groupIntoMap,iterItems:iterItems,mapItems:mapItems,filterItems:filterItems,iterObjectFieldsRecursively:iterObjectFieldsRecursively,invertArrayOfDicts:invertArrayOfDicts,arrayToDict:arrayToDict,identity:identity,findFirstIndexInArray:findFirstIndexInArray,findFirstInArray:findFirstInArray,findFirstKeyInDictMatching:findFirstKeyInDictMatching,mapValues:mapValues,iterMapItems:iterMapItems};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./base.js":34}],48:[function(require,module,exports){(function(global){"use strict";require("./base.js");'use strict';(function(){if(tr.isNode){var glMatrixAbsPath=HTMLImportsLoader.hrefToAbsolutePath('/gl-matrix-min.js');var glMatrixModule=require(glMatrixAbsPath);for(var exportName in glMatrixModule){global[exportName]=glMatrixModule[exportName];}}})(this);'use strict';global.tr.exportTo('tr.b',function(){function approximately(x,y,delta){if(delta===undefined)delta=1e-9;return Math.abs(x-y)<delta;}function clamp(x,lo,hi){return Math.min(Math.max(x,lo),hi);}function lerp(percentage,lo,hi){var range=hi-lo;return lo+percentage*range;}function normalize(value,lo,hi){return(value-lo)/(hi-lo);}function deg2rad(deg){return Math.PI*deg/180.0;}function erf(x){var sign=x>=0?1:-1;x=Math.abs(x);var a1=0.254829592;var a2=-0.284496736;var a3=1.421413741;var a4=-1.453152027;var a5=1.061405429;var p=0.3275911;var t=1.0/(1.0+p*x);var y=1.0-((((a5*t+a4)*t+a3)*t+a2)*t+a1)*t*Math.exp(-x*x);return sign*y;}var tmpVec2=vec2.create();var tmpVec2b=vec2.create();var tmpVec4=vec4.create();var tmpMat2d=mat2d.create();vec2.createFromArray=function(arr){if(arr.length!=2)throw new Error('Should be length 2');var v=vec2.create();vec2.set(v,arr[0],arr[1]);return v;};vec2.createXY=function(x,y){var v=vec2.create();vec2.set(v,x,y);return v;};vec2.toString=function(a){return'['+a[0]+', '+a[1]+']';};vec2.addTwoScaledUnitVectors=function(out,u1,scale1,u2,scale2){vec2.scale(tmpVec2,u1,scale1);vec2.scale(tmpVec2b,u2,scale2);vec2.add(out,tmpVec2,tmpVec2b);};vec2.interpolatePiecewiseFunction=function(points,x){if(x<points[0][0])return points[0][1];for(var i=1;i<points.length;++i){if(x<points[i][0]){var percent=normalize(x,points[i-1][0],points[i][0]);return lerp(percent,points[i-1][1],points[i][1]);}}return points[points.length-1][1];};vec3.createXYZ=function(x,y,z){var v=vec3.create();vec3.set(v,x,y,z);return v;};vec3.toString=function(a){return'vec3('+a[0]+', '+a[1]+', '+a[2]+')';};mat2d.translateXY=function(out,x,y){vec2.set(tmpVec2,x,y);mat2d.translate(out,out,tmpVec2);};mat2d.scaleXY=function(out,x,y){vec2.set(tmpVec2,x,y);mat2d.scale(out,out,tmpVec2);};vec4.unitize=function(out,a){out[0]=a[0]/a[3];out[1]=a[1]/a[3];out[2]=a[2]/a[3];out[3]=1;return out;};vec2.copyFromVec4=function(out,a){vec4.unitize(tmpVec4,a);vec2.copy(out,tmpVec4);};return{approximately:approximately,clamp:clamp,lerp:lerp,normalize:normalize,deg2rad:deg2rad,erf:erf};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./base.js":34}],49:[function(require,module,exports){(function(global){"use strict";require("./base.js");'use strict';global.tr.exportTo('tr.b',function(){function MultiDimensionalViewNode(title,valueCount){this.title=title;var dimensions=title.length;this.children=new Array(dimensions);for(var i=0;i<dimensions;i++)this.children[i]=new Map();this.values=new Array(valueCount);for(var v=0;v<valueCount;v++)this.values[v]={self:0,total:0,totalState:NOT_PROVIDED};}MultiDimensionalViewNode.TotalState={NOT_PROVIDED:0,LOWER_BOUND:1,EXACT:2};var NOT_PROVIDED=MultiDimensionalViewNode.TotalState.NOT_PROVIDED;var LOWER_BOUND=MultiDimensionalViewNode.TotalState.LOWER_BOUND;var EXACT=MultiDimensionalViewNode.TotalState.EXACT;MultiDimensionalViewNode.prototype={get subRows(){return tr.b.mapValues(this.children[0]);}};function MultiDimensionalViewBuilder(dimensions,valueCount){if(typeof dimensions!=='number'||dimensions<0)throw new Error('Dimensions must be a non-negative number');this.dimensions_=dimensions;if(typeof valueCount!=='number'||valueCount<0)throw new Error('Number of values must be a non-negative number');this.valueCount_=valueCount;this.buildRoot_=this.createRootNode_();this.topDownTreeViewRoot_=undefined;this.topDownHeavyViewRoot_=undefined;this.bottomUpHeavyViewNode_=undefined;this.maxDimensionDepths_=new Array(dimensions);for(var d=0;d<dimensions;d++)this.maxDimensionDepths_[d]=0;}MultiDimensionalViewBuilder.ValueKind={SELF:0,TOTAL:1};MultiDimensionalViewBuilder.ViewType={TOP_DOWN_TREE_VIEW:0,TOP_DOWN_HEAVY_VIEW:1,BOTTOM_UP_HEAVY_VIEW:2};MultiDimensionalViewBuilder.prototype={addPath:function(path,values,valueKind){if(this.buildRoot_===undefined){throw new Error('Paths cannot be added after either view has been built');}if(path.length!==this.dimensions_)throw new Error('Path must be '+this.dimensions_+'-dimensional');if(values.length!==this.valueCount_)throw new Error('Must provide '+this.valueCount_+' values');var isTotal;switch(valueKind){case MultiDimensionalViewBuilder.ValueKind.SELF:isTotal=false;break;case MultiDimensionalViewBuilder.ValueKind.TOTAL:isTotal=true;break;default:throw new Error('Invalid value kind: '+valueKind);}var node=this.buildRoot_;for(var d=0;d<path.length;d++){var singleDimensionPath=path[d];var singleDimensionPathLength=singleDimensionPath.length;this.maxDimensionDepths_[d]=Math.max(this.maxDimensionDepths_[d],singleDimensionPathLength);for(var i=0;i<singleDimensionPathLength;i++)node=this.getOrCreateChildNode_(node,d,singleDimensionPath[i]);}for(var v=0;v<this.valueCount_;v++){var addedValue=values[v];if(addedValue===undefined)continue;var nodeValue=node.values[v];if(isTotal){nodeValue.total+=addedValue;nodeValue.totalState=EXACT;}else{nodeValue.self+=addedValue;nodeValue.totalState=Math.max(nodeValue.totalState,LOWER_BOUND);}}},buildView:function(viewType){switch(viewType){case MultiDimensionalViewBuilder.ViewType.TOP_DOWN_TREE_VIEW:return this.buildTopDownTreeView();case MultiDimensionalViewBuilder.ViewType.TOP_DOWN_HEAVY_VIEW:return this.buildTopDownHeavyView();case MultiDimensionalViewBuilder.ViewType.BOTTOM_UP_HEAVY_VIEW:return this.buildBottomUpHeavyView();default:throw new Error('Unknown multi-dimensional view type: '+viewType);}},buildTopDownTreeView:function(){if(this.topDownTreeViewRoot_===undefined){var treeViewRoot=this.buildRoot_;this.buildRoot_=undefined;this.setUpMissingChildRelationships_(treeViewRoot,0);this.finalizeTotalValues_(treeViewRoot,0,new WeakMap());this.topDownTreeViewRoot_=treeViewRoot;}return this.topDownTreeViewRoot_;},buildTopDownHeavyView:function(){if(this.topDownHeavyViewRoot_===undefined){this.topDownHeavyViewRoot_=this.buildGenericHeavyView_(this.addDimensionToTopDownHeavyViewNode_.bind(this));}return this.topDownHeavyViewRoot_;},buildBottomUpHeavyView:function(){if(this.bottomUpHeavyViewNode_===undefined){this.bottomUpHeavyViewNode_=this.buildGenericHeavyView_(this.addDimensionToBottomUpHeavyViewNode_.bind(this));}return this.bottomUpHeavyViewNode_;},createRootNode_:function(){return new MultiDimensionalViewNode(new Array(this.dimensions_),this.valueCount_);},getOrCreateChildNode_:function(parentNode,dimension,childDimensionTitle){if(dimension<0||dimension>=this.dimensions_)throw new Error('Invalid dimension');var dimensionChildren=parentNode.children[dimension];var childNode=dimensionChildren.get(childDimensionTitle);if(childNode!==undefined)return childNode;var childTitle=parentNode.title.slice();childTitle[dimension]=childDimensionTitle;childNode=new MultiDimensionalViewNode(childTitle,this.valueCount_);dimensionChildren.set(childDimensionTitle,childNode);return childNode;},setUpMissingChildRelationships_:function(node,firstDimensionToSetUp){for(var d=firstDimensionToSetUp;d<this.dimensions_;d++){var currentDimensionChildTitles=new Set(node.children[d].keys());for(var i=0;i<d;i++){for(var previousDimensionChildNode of node.children[i].values()){for(var previousDimensionGrandChildTitle of previousDimensionChildNode.children[d].keys()){currentDimensionChildTitles.add(previousDimensionGrandChildTitle);}}}for(var currentDimensionChildTitle of currentDimensionChildTitles){var currentDimensionChildNode=this.getOrCreateChildNode_(node,d,currentDimensionChildTitle);for(var i=0;i<d;i++){for(var previousDimensionChildNode of node.children[i].values()){var previousDimensionGrandChildNode=previousDimensionChildNode.children[d].get(currentDimensionChildTitle);if(previousDimensionGrandChildNode!==undefined){currentDimensionChildNode.children[i].set(previousDimensionChildNode.title[i],previousDimensionGrandChildNode);}}}this.setUpMissingChildRelationships_(currentDimensionChildNode,d);}}},finalizeTotalValues_:function(node,firstDimensionToFinalize,dimensionalSelfSumsMap){var dimensionalSelfSums=new Array(this.dimensions_);var minResidual=new Array(this.valueCount_);for(var v=0;v<this.valueCount_;v++)minResidual[v]=0;var nodeValues=node.values;var nodeSelfSums=new Array(this.valueCount_);for(var v=0;v<this.valueCount_;v++)nodeSelfSums[v]=nodeValues[v].self;for(var d=0;d<this.dimensions_;d++){var childResidualSums=new Array(this.valueCount_);for(var v=0;v<this.valueCount_;v++)childResidualSums[v]=0;for(var childNode of node.children[d].values()){if(d>=firstDimensionToFinalize)this.finalizeTotalValues_(childNode,d,dimensionalSelfSumsMap);var childNodeSelfSums=dimensionalSelfSumsMap.get(childNode);var childNodeValues=childNode.values;for(var v=0;v<this.valueCount_;v++){nodeSelfSums[v]+=childNodeSelfSums[d][v];var residual=childNodeValues[v].total-childNodeSelfSums[this.dimensions_-1][v];childResidualSums[v]+=residual;if(childNodeValues[v].totalState>NOT_PROVIDED){nodeValues[v].totalState=Math.max(nodeValues[v].totalState,LOWER_BOUND);}}}dimensionalSelfSums[d]=nodeSelfSums.slice();for(var v=0;v<this.valueCount_;v++)minResidual[v]=Math.max(minResidual[v],childResidualSums[v]);}for(var v=0;v<this.valueCount_;v++){nodeValues[v].total=Math.max(nodeValues[v].total,nodeSelfSums[v]+minResidual[v]);}if(dimensionalSelfSumsMap.has(node))throw new Error('Internal error: Node finalized more than once');dimensionalSelfSumsMap.set(node,dimensionalSelfSums);},buildGenericHeavyView_:function(treeViewNodeHandler){var treeViewRoot=this.buildTopDownTreeView();var heavyViewRoot=this.createRootNode_();heavyViewRoot.values=treeViewRoot.values;var recursionDepthTrackers=new Array(this.dimensions_);for(var d=0;d<this.dimensions_;d++){recursionDepthTrackers[d]=new RecursionDepthTracker(this.maxDimensionDepths_[d],d);}this.addDimensionsToGenericHeavyViewNode_(treeViewRoot,heavyViewRoot,0,recursionDepthTrackers,false,treeViewNodeHandler);this.setUpMissingChildRelationships_(heavyViewRoot,0);return heavyViewRoot;},addDimensionsToGenericHeavyViewNode_:function(treeViewParentNode,heavyViewParentNode,startDimension,recursionDepthTrackers,previousDimensionsRecursive,treeViewNodeHandler){for(var d=startDimension;d<this.dimensions_;d++){this.addDimensionDescendantsToGenericHeavyViewNode_(treeViewParentNode,heavyViewParentNode,d,recursionDepthTrackers,previousDimensionsRecursive,treeViewNodeHandler);}},addDimensionDescendantsToGenericHeavyViewNode_:function(treeViewParentNode,heavyViewParentNode,currentDimension,recursionDepthTrackers,previousDimensionsRecursive,treeViewNodeHandler){var treeViewChildren=treeViewParentNode.children[currentDimension];var recursionDepthTracker=recursionDepthTrackers[currentDimension];for(var treeViewChildNode of treeViewChildren.values()){recursionDepthTracker.push(treeViewChildNode);treeViewNodeHandler(treeViewChildNode,heavyViewParentNode,currentDimension,recursionDepthTrackers,previousDimensionsRecursive);this.addDimensionDescendantsToGenericHeavyViewNode_(treeViewChildNode,heavyViewParentNode,currentDimension,recursionDepthTrackers,previousDimensionsRecursive,treeViewNodeHandler);recursionDepthTracker.pop();}},addDimensionToTopDownHeavyViewNode_:function(treeViewChildNode,heavyViewParentNode,currentDimension,recursionDepthTrackers,previousDimensionsRecursive){this.addDimensionToTopDownHeavyViewNodeRecursively_(treeViewChildNode,heavyViewParentNode,currentDimension,recursionDepthTrackers,previousDimensionsRecursive,1);},addDimensionToTopDownHeavyViewNodeRecursively_:function(treeViewChildNode,heavyViewParentNode,currentDimension,recursionDepthTrackers,previousDimensionsRecursive,subTreeDepth){var recursionDepthTracker=recursionDepthTrackers[currentDimension];var currentDimensionRecursive=subTreeDepth<=recursionDepthTracker.recursionDepth;var currentOrPreviousDimensionsRecursive=currentDimensionRecursive||previousDimensionsRecursive;var dimensionTitle=treeViewChildNode.title[currentDimension];var heavyViewChildNode=this.getOrCreateChildNode_(heavyViewParentNode,currentDimension,dimensionTitle);this.addNodeValues_(treeViewChildNode,heavyViewChildNode,!currentOrPreviousDimensionsRecursive);this.addDimensionsToGenericHeavyViewNode_(treeViewChildNode,heavyViewChildNode,currentDimension+1,recursionDepthTrackers,currentOrPreviousDimensionsRecursive,this.addDimensionToTopDownHeavyViewNode_.bind(this));for(var treeViewGrandChildNode of treeViewChildNode.children[currentDimension].values()){recursionDepthTracker.push(treeViewGrandChildNode);this.addDimensionToTopDownHeavyViewNodeRecursively_(treeViewGrandChildNode,heavyViewChildNode,currentDimension,recursionDepthTrackers,previousDimensionsRecursive,subTreeDepth+1);recursionDepthTracker.pop();}},addDimensionToBottomUpHeavyViewNode_:function(treeViewChildNode,heavyViewParentNode,currentDimension,recursionDepthTrackers,previousDimensionsRecursive){var recursionDepthTracker=recursionDepthTrackers[currentDimension];var bottomIndex=recursionDepthTracker.bottomIndex;var topIndex=recursionDepthTracker.topIndex;var firstNonRecursiveIndex=bottomIndex+recursionDepthTracker.recursionDepth;var viewNodePath=recursionDepthTracker.viewNodePath;var trackerAncestorNode=recursionDepthTracker.trackerAncestorNode;var heavyViewDescendantNode=heavyViewParentNode;for(var i=bottomIndex;i<topIndex;i++){var treeViewAncestorNode=viewNodePath[i];var dimensionTitle=treeViewAncestorNode.title[currentDimension];heavyViewDescendantNode=this.getOrCreateChildNode_(heavyViewDescendantNode,currentDimension,dimensionTitle);var currentDimensionRecursive=i<firstNonRecursiveIndex;var currentOrPreviousDimensionsRecursive=currentDimensionRecursive||previousDimensionsRecursive;this.addNodeValues_(treeViewChildNode,heavyViewDescendantNode,!currentOrPreviousDimensionsRecursive);this.addDimensionsToGenericHeavyViewNode_(treeViewChildNode,heavyViewDescendantNode,currentDimension+1,recursionDepthTrackers,currentOrPreviousDimensionsRecursive,this.addDimensionToBottomUpHeavyViewNode_.bind(this));}},addNodeValues_:function(sourceNode,targetNode,addTotal){var targetNodeValues=targetNode.values;var sourceNodeValues=sourceNode.values;for(var v=0;v<this.valueCount_;v++){var targetNodeValue=targetNodeValues[v];var sourceNodeValue=sourceNodeValues[v];targetNodeValue.self+=sourceNodeValue.self;if(addTotal){targetNodeValue.total+=sourceNodeValue.total;if(sourceNodeValue.totalState>NOT_PROVIDED){targetNodeValue.totalState=Math.max(targetNodeValue.totalState,LOWER_BOUND);}}}}};function RecursionDepthTracker(maxDepth,dimension){this.titlePath=new Array(maxDepth);this.viewNodePath=new Array(maxDepth);this.bottomIndex=this.topIndex=maxDepth;this.dimension_=dimension;this.currentTrackerNode_=this.createNode_(0,undefined);}RecursionDepthTracker.prototype={push:function(viewNode){if(this.bottomIndex===0)throw new Error('Cannot push to a full tracker');var title=viewNode.title[this.dimension_];this.bottomIndex--;this.titlePath[this.bottomIndex]=title;this.viewNodePath[this.bottomIndex]=viewNode;var childTrackerNode=this.currentTrackerNode_.children.get(title);if(childTrackerNode!==undefined){this.currentTrackerNode_=childTrackerNode;return;}var maxLengths=zFunction(this.titlePath,this.bottomIndex);var recursionDepth=0;for(var i=0;i<maxLengths.length;i++)recursionDepth=Math.max(recursionDepth,maxLengths[i]);childTrackerNode=this.createNode_(recursionDepth,this.currentTrackerNode_);this.currentTrackerNode_.children.set(title,childTrackerNode);this.currentTrackerNode_=childTrackerNode;},pop:function(){if(this.bottomIndex===this.topIndex)throw new Error('Cannot pop from an empty tracker');this.titlePath[this.bottomIndex]=undefined;this.viewNodePath[this.bottomIndex]=undefined;this.bottomIndex++;this.currentTrackerNode_=this.currentTrackerNode_.parent;},get recursionDepth(){return this.currentTrackerNode_.recursionDepth;},createNode_:function(recursionDepth,parent){return{recursionDepth:recursionDepth,parent:parent,children:new Map()};}};function zFunction(list,startIndex){var n=list.length-startIndex;if(n===0)return[];var z=new Array(n);z[0]=0;for(var i=1,left=0,right=0;i<n;++i){var maxLength;if(i<=right)maxLength=Math.min(right-i+1,z[i-left]);else maxLength=0;while(i+maxLength<n&&list[startIndex+maxLength]===list[startIndex+i+maxLength]){++maxLength;}if(i+maxLength-1>right){left=i;right=i+maxLength-1;}z[i]=maxLength;}return z;}return{MultiDimensionalViewBuilder:MultiDimensionalViewBuilder,MultiDimensionalViewNode:MultiDimensionalViewNode,RecursionDepthTracker:RecursionDepthTracker,zFunction:zFunction};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./base.js":34}],50:[function(require,module,exports){(function(global){"use strict";require("./base.js");'use strict';global.tr.exportTo('tr.b',function(){var PERCENTILE_PRECISION=1e-7;function PiecewiseLinearFunction(){this.pieces=[];}PiecewiseLinearFunction.prototype={push:function(x1,y1,x2,y2){if(x1>=x2)throw new Error('Invalid segment');if(this.pieces.length>0&&this.pieces[this.pieces.length-1].x2>x1){throw new Error('Potentially overlapping segments');}if(x1<x2)this.pieces.push(new Piece(x1,y1,x2,y2));},partBelow:function(y){return this.pieces.reduce((acc,p)=>acc+p.partBelow(y),0);},get min(){return this.pieces.reduce((acc,p)=>Math.min(acc,p.min),Infinity);},get max(){return this.pieces.reduce((acc,p)=>Math.max(acc,p.max),-Infinity);},get average(){var weightedSum=0;var totalWeight=0;this.pieces.forEach(function(piece){weightedSum+=piece.width*piece.average;totalWeight+=piece.width;});if(totalWeight===0)return 0;return weightedSum/totalWeight;},percentile:function(percent){if(!(percent>=0&&percent<=1))throw new Error('percent must be [0,1]');var lower=this.min;var upper=this.max;var total=this.partBelow(upper);if(total===0)return 0;while(upper-lower>PERCENTILE_PRECISION){var middle=(lower+upper)/2;var below=this.partBelow(middle);if(below/total<percent)lower=middle;else upper=middle;}return(lower+upper)/2;}};function Piece(x1,y1,x2,y2){this.x1=x1;this.y1=y1;this.x2=x2;this.y2=y2;}Piece.prototype={partBelow:function(y){var width=this.width;if(width===0)return 0;var minY=this.min;var maxY=this.max;if(y>=maxY)return width;if(y<minY)return 0;return(y-minY)/(maxY-minY)*width;},get min(){return Math.min(this.y1,this.y2);},get max(){return Math.max(this.y1,this.y2);},get average(){return(this.y1+this.y2)/2;},get width(){return this.x2-this.x1;}};return{PiecewiseLinearFunction:PiecewiseLinearFunction};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./base.js":34}],51:[function(require,module,exports){(function(global){"use strict";require("./base.js");require("./math.js");'use strict';global.tr.exportTo('tr.b',function(){var tmpVec2s=[];for(var i=0;i<8;i++)tmpVec2s[i]=vec2.create();var tmpVec2a=vec4.create();var tmpVec4a=vec4.create();var tmpVec4b=vec4.create();var tmpMat4=mat4.create();var tmpMat4b=mat4.create();var p00=vec2.createXY(0,0);var p10=vec2.createXY(1,0);var p01=vec2.createXY(0,1);var p11=vec2.createXY(1,1);var lerpingVecA=vec2.create();var lerpingVecB=vec2.create();function lerpVec2(out,a,b,amt){vec2.scale(lerpingVecA,a,amt);vec2.scale(lerpingVecB,b,1-amt);vec2.add(out,lerpingVecA,lerpingVecB);vec2.normalize(out,out);return out;}function Quad(){this.p1=vec2.create();this.p2=vec2.create();this.p3=vec2.create();this.p4=vec2.create();}Quad.fromXYWH=function(x,y,w,h){var q=new Quad();vec2.set(q.p1,x,y);vec2.set(q.p2,x+w,y);vec2.set(q.p3,x+w,y+h);vec2.set(q.p4,x,y+h);return q;};Quad.fromRect=function(r){return new Quad.fromXYWH(r.x,r.y,r.width,r.height);};Quad.from4Vecs=function(p1,p2,p3,p4){var q=new Quad();vec2.set(q.p1,p1[0],p1[1]);vec2.set(q.p2,p2[0],p2[1]);vec2.set(q.p3,p3[0],p3[1]);vec2.set(q.p4,p4[0],p4[1]);return q;};Quad.from8Array=function(arr){if(arr.length!=8)throw new Error('Array must be 8 long');var q=new Quad();q.p1[0]=arr[0];q.p1[1]=arr[1];q.p2[0]=arr[2];q.p2[1]=arr[3];q.p3[0]=arr[4];q.p3[1]=arr[5];q.p4[0]=arr[6];q.p4[1]=arr[7];return q;};Quad.prototype={pointInside:function(point){return pointInImplicitQuad(point,this.p1,this.p2,this.p3,this.p4);},boundingRect:function(){var x0=Math.min(this.p1[0],this.p2[0],this.p3[0],this.p4[0]);var y0=Math.min(this.p1[1],this.p2[1],this.p3[1],this.p4[1]);var x1=Math.max(this.p1[0],this.p2[0],this.p3[0],this.p4[0]);var y1=Math.max(this.p1[1],this.p2[1],this.p3[1],this.p4[1]);return new tr.b.Rect.fromXYWH(x0,y0,x1-x0,y1-y0);},clone:function(){var q=new Quad();vec2.copy(q.p1,this.p1);vec2.copy(q.p2,this.p2);vec2.copy(q.p3,this.p3);vec2.copy(q.p4,this.p4);return q;},scale:function(s){var q=new Quad();this.scaleFast(q,s);return q;},scaleFast:function(dstQuad,s){vec2.copy(dstQuad.p1,this.p1,s);vec2.copy(dstQuad.p2,this.p2,s);vec2.copy(dstQuad.p3,this.p3,s);vec2.copy(dstQuad.p3,this.p3,s);},isRectangle:function(){var bounds=this.boundingRect();return bounds.x==this.p1[0]&&bounds.y==this.p1[1]&&bounds.width==this.p2[0]-this.p1[0]&&bounds.y==this.p2[1]&&bounds.width==this.p3[0]-this.p1[0]&&bounds.height==this.p3[1]-this.p2[1]&&bounds.x==this.p4[0]&&bounds.height==this.p4[1]-this.p2[1];},projectUnitRect:function(rect){var q=new Quad();this.projectUnitRectFast(q,rect);return q;},projectUnitRectFast:function(dstQuad,rect){var v12=tmpVec2s[0];var v14=tmpVec2s[1];var v23=tmpVec2s[2];var v43=tmpVec2s[3];var l12,l14,l23,l43;vec2.sub(v12,this.p2,this.p1);l12=vec2.length(v12);vec2.scale(v12,v12,1/l12);vec2.sub(v14,this.p4,this.p1);l14=vec2.length(v14);vec2.scale(v14,v14,1/l14);vec2.sub(v23,this.p3,this.p2);l23=vec2.length(v23);vec2.scale(v23,v23,1/l23);vec2.sub(v43,this.p3,this.p4);l43=vec2.length(v43);vec2.scale(v43,v43,1/l43);var b12=tmpVec2s[0];var b14=tmpVec2s[1];var b23=tmpVec2s[2];var b43=tmpVec2s[3];lerpVec2(b12,v12,v43,rect.y);lerpVec2(b43,v12,v43,1-rect.bottom);lerpVec2(b14,v14,v23,rect.x);lerpVec2(b23,v14,v23,1-rect.right);vec2.addTwoScaledUnitVectors(tmpVec2a,b12,l12*rect.x,b14,l14*rect.y);vec2.add(dstQuad.p1,this.p1,tmpVec2a);vec2.addTwoScaledUnitVectors(tmpVec2a,b12,l12*-(1.0-rect.right),b23,l23*rect.y);vec2.add(dstQuad.p2,this.p2,tmpVec2a);vec2.addTwoScaledUnitVectors(tmpVec2a,b43,l43*-(1.0-rect.right),b23,l23*-(1.0-rect.bottom));vec2.add(dstQuad.p3,this.p3,tmpVec2a);vec2.addTwoScaledUnitVectors(tmpVec2a,b43,l43*rect.left,b14,l14*-(1.0-rect.bottom));vec2.add(dstQuad.p4,this.p4,tmpVec2a);},toString:function(){return'Quad('+vec2.toString(this.p1)+', '+vec2.toString(this.p2)+', '+vec2.toString(this.p3)+', '+vec2.toString(this.p4)+')';}};function sign(p1,p2,p3){return(p1[0]-p3[0])*(p2[1]-p3[1])-(p2[0]-p3[0])*(p1[1]-p3[1]);}function pointInTriangle2(pt,p1,p2,p3){var b1=sign(pt,p1,p2)<0.0;var b2=sign(pt,p2,p3)<0.0;var b3=sign(pt,p3,p1)<0.0;return b1==b2&&b2==b3;}function pointInImplicitQuad(point,p1,p2,p3,p4){return pointInTriangle2(point,p1,p2,p3)||pointInTriangle2(point,p1,p3,p4);}return{pointInTriangle2:pointInTriangle2,pointInImplicitQuad:pointInImplicitQuad,Quad:Quad};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./base.js":34,"./math.js":48}],52:[function(require,module,exports){(function(global){"use strict";require("./utils.js");'use strict';global.tr.exportTo('tr.b',function(){var ESTIMATED_IDLE_PERIOD_LENGTH_MILLISECONDS=10;var REQUEST_IDLE_CALLBACK_TIMEOUT_MILLISECONDS=100;var recordRAFStacks=false;var pendingPreAFs=[];var pendingRAFs=[];var pendingIdleCallbacks=[];var currentRAFDispatchList=undefined;var rafScheduled=false;var idleWorkScheduled=false;function scheduleRAF(){if(rafScheduled)return;rafScheduled=true;if(tr.isHeadless){Promise.resolve().then(function(){processRequests(false,0);},function(e){console.log(e.stack);throw e;});}else{if(window.requestAnimationFrame){window.requestAnimationFrame(processRequests.bind(this,false));}else{var delta=Date.now()-window.performance.now();window.webkitRequestAnimationFrame(function(domTimeStamp){processRequests(false,domTimeStamp-delta);});}}}function nativeRequestIdleCallbackSupported(){return!tr.isHeadless&&window.requestIdleCallback;}function scheduleIdleWork(){if(idleWorkScheduled)return;if(!nativeRequestIdleCallbackSupported()){scheduleRAF();return;}idleWorkScheduled=true;window.requestIdleCallback(function(deadline,didTimeout){processIdleWork(false,deadline);},{timeout:REQUEST_IDLE_CALLBACK_TIMEOUT_MILLISECONDS});}function onAnimationFrameError(e,opt_stack){console.log(e.stack);if(tr.isHeadless)throw e;if(opt_stack)console.log(opt_stack);if(e.message)console.error(e.message,e.stack);else console.error(e);}function runTask(task,frameBeginTime){try{task.callback.call(task.context,frameBeginTime);}catch(e){tr.b.onAnimationFrameError(e,task.stack);}}function processRequests(forceAllTasksToRun,frameBeginTime){rafScheduled=false;var currentPreAFs=pendingPreAFs;currentRAFDispatchList=pendingRAFs;pendingPreAFs=[];pendingRAFs=[];var hasRAFTasks=currentPreAFs.length||currentRAFDispatchList.length;for(var i=0;i<currentPreAFs.length;i++)runTask(currentPreAFs[i],frameBeginTime);while(currentRAFDispatchList.length>0)runTask(currentRAFDispatchList.shift(),frameBeginTime);currentRAFDispatchList=undefined;if(!hasRAFTasks&&!nativeRequestIdleCallbackSupported()||forceAllTasksToRun){var rafCompletionDeadline=frameBeginTime+ESTIMATED_IDLE_PERIOD_LENGTH_MILLISECONDS;processIdleWork(forceAllTasksToRun,{timeRemaining:function(){return rafCompletionDeadline-window.performance.now();}});}if(pendingIdleCallbacks.length>0)scheduleIdleWork();}function processIdleWork(forceAllTasksToRun,deadline){idleWorkScheduled=false;while(pendingIdleCallbacks.length>0){runTask(pendingIdleCallbacks.shift());if(!forceAllTasksToRun&&(tr.isHeadless||deadline.timeRemaining()<=0)){break;}}if(pendingIdleCallbacks.length>0)scheduleIdleWork();}function getStack_(){if(!recordRAFStacks)return'';var stackLines=tr.b.stackTrace();stackLines.shift();return stackLines.join('\n');}function requestPreAnimationFrame(callback,opt_this){pendingPreAFs.push({callback:callback,context:opt_this||global,stack:getStack_()});scheduleRAF();}function requestAnimationFrameInThisFrameIfPossible(callback,opt_this){if(!currentRAFDispatchList){requestAnimationFrame(callback,opt_this);return;}currentRAFDispatchList.push({callback:callback,context:opt_this||global,stack:getStack_()});return;}function requestAnimationFrame(callback,opt_this){pendingRAFs.push({callback:callback,context:opt_this||global,stack:getStack_()});scheduleRAF();}function requestIdleCallback(callback,opt_this){pendingIdleCallbacks.push({callback:callback,context:opt_this||global,stack:getStack_()});scheduleIdleWork();}function forcePendingRAFTasksToRun(frameBeginTime){if(!rafScheduled)return;processRequests(false,frameBeginTime);}function forceAllPendingTasksToRunForTest(){if(!rafScheduled&&!idleWorkScheduled)return;processRequests(true,0);}return{onAnimationFrameError:onAnimationFrameError,requestPreAnimationFrame:requestPreAnimationFrame,requestAnimationFrame:requestAnimationFrame,requestAnimationFrameInThisFrameIfPossible:requestAnimationFrameInThisFrameIfPossible,requestIdleCallback:requestIdleCallback,forcePendingRAFTasksToRun:forcePendingRAFTasksToRun,forceAllPendingTasksToRunForTest:forceAllPendingTasksToRunForTest};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./utils.js":65}],53:[function(require,module,exports){(function(global){"use strict";require("./base.js");require("./iteration_helpers.js");require("./math.js");'use strict';global.tr.exportTo('tr.b',function(){function Range(){this.isEmpty_=true;this.min_=undefined;this.max_=undefined;}Range.prototype={__proto__:Object.prototype,reset:function(){this.isEmpty_=true;this.min_=undefined;this.max_=undefined;},get isEmpty(){return this.isEmpty_;},addRange:function(range){if(range.isEmpty)return;this.addValue(range.min);this.addValue(range.max);},addValue:function(value){if(this.isEmpty_){this.max_=value;this.min_=value;this.isEmpty_=false;return;}this.max_=Math.max(this.max_,value);this.min_=Math.min(this.min_,value);},set min(min){this.isEmpty_=false;this.min_=min;},get min(){if(this.isEmpty_)return undefined;return this.min_;},get max(){if(this.isEmpty_)return undefined;return this.max_;},set max(max){this.isEmpty_=false;this.max_=max;},get range(){if(this.isEmpty_)return undefined;return this.max_-this.min_;},get center(){return(this.min_+this.max_)*0.5;},get duration(){if(this.isEmpty_)return 0;return this.max_-this.min_;},normalize:function(x){return tr.b.normalize(x,this.min,this.max);},lerp:function(x){return tr.b.lerp(x,this.min,this.max);},equals:function(that){if(this.isEmpty&&that.isEmpty)return true;if(this.isEmpty!=that.isEmpty)return false;return tr.b.approximately(this.min,that.min)&&tr.b.approximately(this.max,that.max);},containsExplicitRangeInclusive:function(min,max){if(this.isEmpty)return false;return this.min_<=min&&max<=this.max_;},containsExplicitRangeExclusive:function(min,max){if(this.isEmpty)return false;return this.min_<min&&max<this.max_;},intersectsExplicitRangeInclusive:function(min,max){if(this.isEmpty)return false;return this.min_<=max&&min<=this.max_;},intersectsExplicitRangeExclusive:function(min,max){if(this.isEmpty)return false;return this.min_<max&&min<this.max_;},containsRangeInclusive:function(range){if(range.isEmpty)return false;return this.containsExplicitRangeInclusive(range.min_,range.max_);},containsRangeExclusive:function(range){if(range.isEmpty)return false;return this.containsExplicitRangeExclusive(range.min_,range.max_);},intersectsRangeInclusive:function(range){if(range.isEmpty)return false;return this.intersectsExplicitRangeInclusive(range.min_,range.max_);},intersectsRangeExclusive:function(range){if(range.isEmpty)return false;return this.intersectsExplicitRangeExclusive(range.min_,range.max_);},findExplicitIntersectionDuration:function(min,max){var min=Math.max(this.min,min);var max=Math.min(this.max,max);if(max<min)return 0;return max-min;},findIntersection:function(range){if(this.isEmpty||range.isEmpty)return new Range();var min=Math.max(this.min,range.min);var max=Math.min(this.max,range.max);if(max<min)return new Range();return Range.fromExplicitRange(min,max);},toJSON:function(){if(this.isEmpty_)return{isEmpty:true};return{isEmpty:false,max:this.max,min:this.min};},filterArray:function(array,opt_keyFunc,opt_this){if(this.isEmpty_)return[];function binSearch(test){var i0=0;var i1=array.length;while(i0<i1){var i=Math.trunc((i0+i1)/2);if(test(i))i1=i;else i0=i+1;}return i1;}var keyFunc=opt_keyFunc||tr.b.identity;function getValue(index){return keyFunc.call(opt_this,array[index]);}var first=binSearch(function(i){return this.min_===undefined||this.min_<=getValue(i);}.bind(this));var last=binSearch(function(i){return this.max_!==undefined&&this.max_<getValue(i);}.bind(this));return array.slice(first,last);}};Range.fromDict=function(d){if(d.isEmpty===true){return new Range();}else if(d.isEmpty===false){var range=new Range();range.min=d.min;range.max=d.max;return range;}else{throw new Error('Not a range');}};Range.fromExplicitRange=function(min,max){var range=new Range();range.min=min;range.max=max;return range;};Range.compareByMinTimes=function(a,b){if(!a.isEmpty&&!b.isEmpty)return a.min_-b.min_;if(a.isEmpty&&!b.isEmpty)return-1;if(!a.isEmpty&&b.isEmpty)return 1;return 0;};Range.PERCENT_RANGE=Range.fromExplicitRange(0,1);Object.freeze(Range.PERCENT_RANGE);return{Range:Range};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./base.js":34,"./iteration_helpers.js":47,"./math.js":48}],54:[function(require,module,exports){(function(global){"use strict";require("./base.js");require("./iteration_helpers.js");'use strict';global.tr.exportTo('tr.b',function(){function convertEventsToRanges(events){return events.map(function(event){return tr.b.Range.fromExplicitRange(event.start,event.end);});}function mergeRanges(inRanges,mergeThreshold,mergeFunction){var remainingEvents=inRanges.slice();remainingEvents.sort(function(x,y){return x.min-y.min;});if(remainingEvents.length<=1){var merged=[];if(remainingEvents.length==1){merged.push(mergeFunction(remainingEvents));}return merged;}var mergedEvents=[];var currentMergeBuffer=[];var rightEdge;function beginMerging(){currentMergeBuffer.push(remainingEvents[0]);remainingEvents.splice(0,1);rightEdge=currentMergeBuffer[0].max;}function flushCurrentMergeBuffer(){if(currentMergeBuffer.length==0)return;mergedEvents.push(mergeFunction(currentMergeBuffer));currentMergeBuffer=[];if(remainingEvents.length!=0)beginMerging();}beginMerging();while(remainingEvents.length){var currentEvent=remainingEvents[0];var distanceFromRightEdge=currentEvent.min-rightEdge;if(distanceFromRightEdge<mergeThreshold){rightEdge=Math.max(rightEdge,currentEvent.max);remainingEvents.splice(0,1);currentMergeBuffer.push(currentEvent);continue;}flushCurrentMergeBuffer();}flushCurrentMergeBuffer();return mergedEvents;}function findEmptyRangesBetweenRanges(inRanges,opt_totalRange){if(opt_totalRange&&opt_totalRange.isEmpty)opt_totalRange=undefined;var emptyRanges=[];if(!inRanges.length){if(opt_totalRange)emptyRanges.push(opt_totalRange);return emptyRanges;}inRanges=inRanges.slice();inRanges.sort(function(x,y){return x.min-y.min;});if(opt_totalRange&&opt_totalRange.min<inRanges[0].min){emptyRanges.push(tr.b.Range.fromExplicitRange(opt_totalRange.min,inRanges[0].min));}inRanges.forEach(function(range,index){for(var otherIndex=0;otherIndex<inRanges.length;++otherIndex){if(index===otherIndex)continue;var other=inRanges[otherIndex];if(other.min>range.max){emptyRanges.push(tr.b.Range.fromExplicitRange(range.max,other.min));return;}if(other.max>range.max){return;}}if(opt_totalRange&&range.max<opt_totalRange.max){emptyRanges.push(tr.b.Range.fromExplicitRange(range.max,opt_totalRange.max));}});return emptyRanges;}return{convertEventsToRanges:convertEventsToRanges,findEmptyRangesBetweenRanges:findEmptyRangesBetweenRanges,mergeRanges:mergeRanges};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./base.js":34,"./iteration_helpers.js":47}],55:[function(require,module,exports){(function(global){"use strict";require("./base.js");require("./math.js");'use strict';global.tr.exportTo('tr.b',function(){function Rect(){this.x=0;this.y=0;this.width=0;this.height=0;};Rect.fromXYWH=function(x,y,w,h){var rect=new Rect();rect.x=x;rect.y=y;rect.width=w;rect.height=h;return rect;};Rect.fromArray=function(ary){if(ary.length!=4)throw new Error('ary.length must be 4');var rect=new Rect();rect.x=ary[0];rect.y=ary[1];rect.width=ary[2];rect.height=ary[3];return rect;};Rect.prototype={__proto__:Object.prototype,get left(){return this.x;},get top(){return this.y;},get right(){return this.x+this.width;},get bottom(){return this.y+this.height;},toString:function(){return'Rect('+this.x+', '+this.y+', '+this.width+', '+this.height+')';},toArray:function(){return[this.x,this.y,this.width,this.height];},clone:function(){var rect=new Rect();rect.x=this.x;rect.y=this.y;rect.width=this.width;rect.height=this.height;return rect;},enlarge:function(pad){var rect=new Rect();this.enlargeFast(rect,pad);return rect;},enlargeFast:function(out,pad){out.x=this.x-pad;out.y=this.y-pad;out.width=this.width+2*pad;out.height=this.height+2*pad;return out;},size:function(){return{width:this.width,height:this.height};},scale:function(s){var rect=new Rect();this.scaleFast(rect,s);return rect;},scaleSize:function(s){return Rect.fromXYWH(this.x,this.y,this.width*s,this.height*s);},scaleFast:function(out,s){out.x=this.x*s;out.y=this.y*s;out.width=this.width*s;out.height=this.height*s;return out;},translate:function(v){var rect=new Rect();this.translateFast(rect,v);return rect;},translateFast:function(out,v){out.x=this.x+v[0];out.y=this.x+v[1];out.width=this.width;out.height=this.height;return out;},asUVRectInside:function(containingRect){var rect=new Rect();rect.x=(this.x-containingRect.x)/containingRect.width;rect.y=(this.y-containingRect.y)/containingRect.height;rect.width=this.width/containingRect.width;rect.height=this.height/containingRect.height;return rect;},intersects:function(that){var ok=true;ok&=this.x<that.right;ok&=this.right>that.x;ok&=this.y<that.bottom;ok&=this.bottom>that.y;return ok;},equalTo:function(rect){return rect&&this.x===rect.x&&this.y===rect.y&&this.width===rect.width&&this.height===rect.height;}};return{Rect:Rect};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./base.js":34,"./math.js":48}],56:[function(require,module,exports){(function(global){"use strict";var _slicedToArray=function(){function sliceIterator(arr,i){var _arr=[];var _n=true;var _d=false;var _e=undefined;try{for(var _i=arr[Symbol.iterator](),_s;!(_n=(_s=_i.next()).done);_n=true){_arr.push(_s.value);if(i&&_arr.length===i)break;}}catch(err){_d=true;_e=err;}finally{try{if(!_n&&_i["return"])_i["return"]();}finally{if(_d)throw _e;}}return _arr;}return function(arr,i){if(Array.isArray(arr)){return arr;}else if(Symbol.iterator in Object(arr)){return sliceIterator(arr,i);}else{throw new TypeError("Invalid attempt to destructure non-iterable instance");}};}();require("./base.js");'use strict';global.tr.exportTo('tr.b',function(){class RunningStatistics{constructor(){this.mean_=0;this.count_=0;this.max_=-Infinity;this.min_=Infinity;this.sum_=0;this.variance_=0;this.meanlogs_=0;}get count(){return this.count_;}get geometricMean(){if(this.meanlogs_===undefined)return 0;return Math.exp(this.meanlogs_);}get mean(){if(this.count_==0)return undefined;return this.mean_;}get max(){return this.max_;}get min(){return this.min_;}get sum(){return this.sum_;}get variance(){if(this.count_==0)return undefined;if(this.count_==1)return 0;return this.variance_/(this.count_-1);}get stddev(){if(this.count_==0)return undefined;return Math.sqrt(this.variance);}add(x){this.count_++;this.max_=Math.max(this.max_,x);this.min_=Math.min(this.min_,x);this.sum_+=x;if(x<=0)this.meanlogs_=undefined;else if(this.meanlogs_!==undefined)this.meanlogs_+=(Math.log(Math.abs(x))-this.meanlogs_)/this.count;if(this.count_===1){this.mean_=x;this.variance_=0;}else{var oldMean=this.mean_;var oldVariance=this.variance_;if(oldMean===Infinity||oldMean===-Infinity){this.mean_=this.sum_/this.count_;}else{this.mean_=oldMean+(x-oldMean)/this.count_;}this.variance_=oldVariance+(x-oldMean)*(x-this.mean_);}}merge(other){var result=new RunningStatistics();result.count_=this.count_+other.count_;result.sum_=this.sum_+other.sum_;result.min_=Math.min(this.min_,other.min_);result.max_=Math.max(this.max_,other.max_);if(result.count===0){result.mean_=0;result.variance_=0;result.meanlogs_=0;}else{result.mean_=result.sum/result.count;var deltaMean=(this.mean||0)-(other.mean||0);result.variance_=this.variance_+other.variance_+this.count*other.count*deltaMean*deltaMean/result.count;if(this.meanlogs_===undefined||other.meanlogs_===undefined){result.meanlogs_=undefined;}else{result.meanlogs_=(this.count*this.meanlogs_+other.count*other.meanlogs_)/result.count;}}return result;}asDict(){if(!this.count){return[];}return[this.count_,this.max_,this.meanlogs_,this.mean_,this.min_,this.sum_,this.variance_];}static fromDict(dict){var result=new RunningStatistics();if(dict.length!=7){return result;}var _dict=_slicedToArray(dict,7);result.count_=_dict[0];result.max_=_dict[1];result.meanlogs_=_dict[2];result.mean_=_dict[3];result.min_=_dict[4];result.sum_=_dict[5];result.variance_=_dict[6];return result;}}return{RunningStatistics:RunningStatistics};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./base.js":34}],57:[function(require,module,exports){(function(global){"use strict";require("./color.js");require("./iteration_helpers.js");require("./math.js");'use strict';global.tr.exportTo('tr.b',function(){function SinebowColorGenerator(opt_a,opt_brightness){this.a_=opt_a===undefined?1:opt_a;this.brightness_=opt_brightness===undefined?1:opt_brightness;this.colorIndex_=0;this.keyToColor={};}SinebowColorGenerator.prototype={colorForKey:function(key){if(!this.keyToColor[key])this.keyToColor[key]=this.nextColor();return this.keyToColor[key];},nextColor:function(){var components=SinebowColorGenerator.nthColor(this.colorIndex_++);return tr.b.Color.fromString(SinebowColorGenerator.calculateColor(components[0],components[1],components[2],this.a_,this.brightness_));}};SinebowColorGenerator.PHI=(1+Math.sqrt(5))/2;SinebowColorGenerator.sinebow_=function(h){h+=0.5;h=-h;var r=Math.sin(Math.PI*h);var g=Math.sin(Math.PI*(h+1/3));var b=Math.sin(Math.PI*(h+2/3));r*=r;g*=g;b*=b;var y=2*(0.2989*r+0.5870*g+0.1140*b);r/=y;g/=y;b/=y;return[256*r,256*g,256*b];};SinebowColorGenerator.nthColor=function(n){return SinebowColorGenerator.sinebow_(n*this.PHI);};SinebowColorGenerator.calculateColor=function(r,g,b,a,brightness){if(brightness<=1){r*=brightness;g*=brightness;b*=brightness;}else{r=tr.b.lerp(tr.b.normalize(brightness,1,2),r,255);g=tr.b.lerp(tr.b.normalize(brightness,1,2),g,255);b=tr.b.lerp(tr.b.normalize(brightness,1,2),b,255);}r=Math.round(r);g=Math.round(g);b=Math.round(b);return'rgba('+r+','+g+','+b+', '+a+')';};return{SinebowColorGenerator:SinebowColorGenerator};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./color.js":37,"./iteration_helpers.js":47,"./math.js":48}],58:[function(require,module,exports){(function(global){"use strict";require("./base.js");'use strict';global.tr.exportTo('tr.b',function(){function findLowIndexInSortedArray(ary,mapFn,loVal){if(ary.length==0)return 1;var low=0;var high=ary.length-1;var i,comparison;var hitPos=-1;while(low<=high){i=Math.floor((low+high)/2);comparison=mapFn(ary[i])-loVal;if(comparison<0){low=i+1;continue;}else if(comparison>0){high=i-1;continue;}else{hitPos=i;high=i-1;}}return hitPos!=-1?hitPos:low;}function findHighIndexInSortedArray(ary,mapFn,loVal,hiVal){var lo=loVal||0;var hi=hiVal!==undefined?hiVal:ary.length;while(lo<hi){var mid=lo+hi>>1;if(mapFn(ary[mid])>=0)lo=mid+1;else hi=mid;}return hi;}function findIndexInSortedIntervals(ary,mapLoFn,mapWidthFn,loVal){var first=findLowIndexInSortedArray(ary,mapLoFn,loVal);if(first==0){if(loVal>=mapLoFn(ary[0])&&loVal<mapLoFn(ary[0])+mapWidthFn(ary[0],0)){return 0;}else{return-1;}}else if(first<ary.length){if(loVal>=mapLoFn(ary[first])&&loVal<mapLoFn(ary[first])+mapWidthFn(ary[first],first)){return first;}else if(loVal>=mapLoFn(ary[first-1])&&loVal<mapLoFn(ary[first-1])+mapWidthFn(ary[first-1],first-1)){return first-1;}else{return ary.length;}}else if(first==ary.length){if(loVal>=mapLoFn(ary[first-1])&&loVal<mapLoFn(ary[first-1])+mapWidthFn(ary[first-1],first-1)){return first-1;}else{return ary.length;}}else{return ary.length;}}function findIndexInSortedClosedIntervals(ary,mapLoFn,mapHiFn,val){var i=findLowIndexInSortedArray(ary,mapLoFn,val);if(i===0){if(val>=mapLoFn(ary[0],0)&&val<=mapHiFn(ary[0],0)){return 0;}else{return-1;}}else if(i<ary.length){if(val>=mapLoFn(ary[i-1],i-1)&&val<=mapHiFn(ary[i-1],i-1)){return i-1;}else if(val>=mapLoFn(ary[i],i)&&val<=mapHiFn(ary[i],i)){return i;}else{return ary.length;}}else if(i==ary.length){if(val>=mapLoFn(ary[i-1],i-1)&&val<=mapHiFn(ary[i-1],i-1)){return i-1;}else{return ary.length;}}else{return ary.length;}}function iterateOverIntersectingIntervals(ary,mapLoFn,mapWidthFn,loVal,hiVal,cb){if(ary.length==0)return;if(loVal>hiVal)return;var i=findLowIndexInSortedArray(ary,mapLoFn,loVal);if(i==-1){return;}if(i>0){var hi=mapLoFn(ary[i-1])+mapWidthFn(ary[i-1],i-1);if(hi>=loVal){cb(ary[i-1],i-1);}}if(i==ary.length){return;}for(var n=ary.length;i<n;i++){var lo=mapLoFn(ary[i]);if(lo>=hiVal)break;cb(ary[i],i);}}function getIntersectingIntervals(ary,mapLoFn,mapWidthFn,loVal,hiVal){var tmp=[];iterateOverIntersectingIntervals(ary,mapLoFn,mapWidthFn,loVal,hiVal,function(d){tmp.push(d);});return tmp;}function findClosestElementInSortedArray(ary,mapFn,val,maxDiff){if(ary.length===0)return null;var aftIdx=findLowIndexInSortedArray(ary,mapFn,val);var befIdx=aftIdx>0?aftIdx-1:0;if(aftIdx===ary.length)aftIdx-=1;var befDiff=Math.abs(val-mapFn(ary[befIdx]));var aftDiff=Math.abs(val-mapFn(ary[aftIdx]));if(befDiff>maxDiff&&aftDiff>maxDiff)return null;var idx=befDiff<aftDiff?befIdx:aftIdx;return ary[idx];}function findClosestIntervalInSortedIntervals(ary,mapLoFn,mapHiFn,val,maxDiff){if(ary.length===0)return null;var idx=findLowIndexInSortedArray(ary,mapLoFn,val);if(idx>0)idx-=1;var hiInt=ary[idx];var loInt=hiInt;if(val>mapHiFn(hiInt)&&idx+1<ary.length)loInt=ary[idx+1];var loDiff=Math.abs(val-mapLoFn(loInt));var hiDiff=Math.abs(val-mapHiFn(hiInt));if(loDiff>maxDiff&&hiDiff>maxDiff)return null;if(loDiff<hiDiff)return loInt;else return hiInt;}return{findLowIndexInSortedArray:findLowIndexInSortedArray,findHighIndexInSortedArray:findHighIndexInSortedArray,findIndexInSortedIntervals:findIndexInSortedIntervals,findIndexInSortedClosedIntervals:findIndexInSortedClosedIntervals,iterateOverIntersectingIntervals:iterateOverIntersectingIntervals,getIntersectingIntervals:getIntersectingIntervals,findClosestElementInSortedArray:findClosestElementInSortedArray,findClosestIntervalInSortedIntervals:findClosestIntervalInSortedIntervals};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./base.js":34}],59:[function(require,module,exports){(function(global){"use strict";require("./math.js");require("./range.js");'use strict';(function(){if(tr.isNode){var mwuAbsPath=HTMLImportsLoader.hrefToAbsolutePath('/mannwhitneyu.js');var mwuModule=require(mwuAbsPath);for(var exportName in mwuModule){global[exportName]=mwuModule[exportName];}}})(this);'use strict';global.tr.exportTo('tr.b',function(){var identity=x=>x;var Statistics={};Statistics.divideIfPossibleOrZero=function(numerator,denominator){if(denominator===0)return 0;return numerator/denominator;};Statistics.sum=function(ary,opt_func,opt_this){var func=opt_func||identity;var ret=0;var i=0;for(var elt of ary)ret+=func.call(opt_this,elt,i++);return ret;};Statistics.mean=function(ary,opt_func,opt_this){var func=opt_func||identity;var sum=0;var i=0;for(var elt of ary)sum+=func.call(opt_this,elt,i++);if(i===0)return undefined;return sum/i;};Statistics.geometricMean=function(ary,opt_func,opt_this){var func=opt_func||identity;var i=0;var logsum=0;for(var elt of ary){var x=func.call(opt_this,elt,i++);if(x<=0)return 0;logsum+=Math.log(Math.abs(x));}if(i===0)return 1;return Math.exp(logsum/i);};Statistics.weightedMean=function(ary,weightCallback,opt_valueCallback,opt_this){var valueCallback=opt_valueCallback||identity;var numerator=0;var denominator=0;var i=-1;for(var elt of ary){i++;var value=valueCallback.call(opt_this,elt,i);if(value===undefined)continue;var weight=weightCallback.call(opt_this,elt,i,value);numerator+=weight*value;denominator+=weight;}if(denominator===0)return undefined;return numerator/denominator;};Statistics.variance=function(ary,opt_func,opt_this){if(ary.length===0)return undefined;if(ary.length===1)return 0;var func=opt_func||identity;var mean=Statistics.mean(ary,func,opt_this);var sumOfSquaredDistances=Statistics.sum(ary,function(d,i){var v=func.call(this,d,i)-mean;return v*v;},opt_this);return sumOfSquaredDistances/(ary.length-1);};Statistics.stddev=function(ary,opt_func,opt_this){if(ary.length==0)return undefined;return Math.sqrt(Statistics.variance(ary,opt_func,opt_this));};Statistics.max=function(ary,opt_func,opt_this){var func=opt_func||identity;var ret=-Infinity;var i=0;for(var elt of ary)ret=Math.max(ret,func.call(opt_this,elt,i++));return ret;};Statistics.min=function(ary,opt_func,opt_this){var func=opt_func||identity;var ret=Infinity;var i=0;for(var elt of ary)ret=Math.min(ret,func.call(opt_this,elt,i++));return ret;};Statistics.range=function(ary,opt_func,opt_this){var func=opt_func||identity;var ret=new tr.b.Range();var i=0;for(var elt of ary)ret.addValue(func.call(opt_this,elt,i++));return ret;};Statistics.percentile=function(ary,percent,opt_func,opt_this){if(!(percent>=0&&percent<=1))throw new Error('percent must be [0,1]');var func=opt_func||identity;var tmp=new Array(ary.length);var i=0;for(var elt of ary)tmp[i]=func.call(opt_this,elt,i++);tmp.sort((a,b)=>a-b);var idx=Math.floor((ary.length-1)*percent);return tmp[idx];};Statistics.normalizeSamples=function(samples){if(samples.length===0){return{normalized_samples:samples,scale:1.0};}samples=samples.slice().sort(function(a,b){return a-b;});var low=Math.min.apply(null,samples);var high=Math.max.apply(null,samples);var newLow=0.5/samples.length;var newHigh=(samples.length-0.5)/samples.length;if(high-low===0.0){samples=Array.apply(null,new Array(samples.length)).map(function(){return 0.5;});return{normalized_samples:samples,scale:1.0};}var scale=(newHigh-newLow)/(high-low);for(var i=0;i<samples.length;i++){samples[i]=(samples[i]-low)*scale+newLow;}return{normalized_samples:samples,scale:scale};};Statistics.discrepancy=function(samples,opt_locationCount){if(samples.length===0)return 0.0;var maxLocalDiscrepancy=0;var invSampleCount=1.0/samples.length;var locations=[];var countLess=[];var countLessEqual=[];if(opt_locationCount!==undefined){var sampleIndex=0;for(var i=0;i<opt_locationCount;i++){var location=i/(opt_locationCount-1);locations.push(location);while(sampleIndex<samples.length&&samples[sampleIndex]<location){sampleIndex+=1;}countLess.push(sampleIndex);while(sampleIndex<samples.length&&samples[sampleIndex]<=location){sampleIndex+=1;}countLessEqual.push(sampleIndex);}}else{if(samples[0]>0.0){locations.push(0.0);countLess.push(0);countLessEqual.push(0);}for(var i=0;i<samples.length;i++){locations.push(samples[i]);countLess.push(i);countLessEqual.push(i+1);}if(samples[-1]<1.0){locations.push(1.0);countLess.push(samples.length);countLessEqual.push(samples.length);}}var maxDiff=0;var minDiff=0;for(var i=1;i<locations.length;i++){var length=locations[i]-locations[i-1];var countClosed=countLessEqual[i]-countLess[i-1];var countOpen=countLess[i]-countLessEqual[i-1];var countClosedIncrement=countLessEqual[i]-countLessEqual[i-1];var countOpenIncrement=countLess[i]-countLess[i-1];maxDiff=Math.max(countClosedIncrement*invSampleCount-length+maxDiff,countClosed*invSampleCount-length);minDiff=Math.min(countOpenIncrement*invSampleCount-length+minDiff,countOpen*invSampleCount-length);maxLocalDiscrepancy=Math.max(maxDiff,-minDiff,maxLocalDiscrepancy);}return maxLocalDiscrepancy;};Statistics.timestampsDiscrepancy=function(timestamps,opt_absolute,opt_locationCount){if(timestamps.length===0)return 0.0;if(opt_absolute===undefined)opt_absolute=true;if(Array.isArray(timestamps[0])){var rangeDiscrepancies=timestamps.map(function(r){return Statistics.timestampsDiscrepancy(r);});return Math.max.apply(null,rangeDiscrepancies);}var s=Statistics.normalizeSamples(timestamps);var samples=s.normalized_samples;var sampleScale=s.scale;var discrepancy=Statistics.discrepancy(samples,opt_locationCount);var invSampleCount=1.0/samples.length;if(opt_absolute===true){discrepancy/=sampleScale;}else{discrepancy=tr.b.clamp((discrepancy-invSampleCount)/(1.0-invSampleCount),0.0,1.0);}return discrepancy;};Statistics.durationsDiscrepancy=function(durations,opt_absolute,opt_locationCount){if(durations.length===0)return 0.0;var timestamps=durations.reduce(function(prev,curr,index,array){prev.push(prev[prev.length-1]+curr);return prev;},[0]);return Statistics.timestampsDiscrepancy(timestamps,opt_absolute,opt_locationCount);};Statistics.uniformlySampleArray=function(samples,count){if(samples.length<=count){return samples;}while(samples.length>count){var i=parseInt(Math.random()*samples.length);samples.splice(i,1);}return samples;};Statistics.uniformlySampleStream=function(samples,streamLength,newElement,numSamples){if(streamLength<=numSamples){if(samples.length>=streamLength)samples[streamLength-1]=newElement;else samples.push(newElement);return;}var probToKeep=numSamples/streamLength;if(Math.random()>probToKeep)return;var index=Math.floor(Math.random()*numSamples);samples[index]=newElement;};Statistics.mergeSampledStreams=function(samplesA,streamLengthA,samplesB,streamLengthB,numSamples){if(streamLengthB<numSamples){var nbElements=Math.min(streamLengthB,samplesB.length);for(var i=0;i<nbElements;++i){Statistics.uniformlySampleStream(samplesA,streamLengthA+i+1,samplesB[i],numSamples);}return;}if(streamLengthA<numSamples){var nbElements=Math.min(streamLengthA,samplesA.length);var tempSamples=samplesB.slice();for(var i=0;i<nbElements;++i){Statistics.uniformlySampleStream(tempSamples,streamLengthB+i+1,samplesA[i],numSamples);}for(var i=0;i<tempSamples.length;++i){samplesA[i]=tempSamples[i];}return;}var nbElements=Math.min(numSamples,samplesB.length);var probOfSwapping=streamLengthB/(streamLengthA+streamLengthB);for(var i=0;i<nbElements;++i){if(Math.random()<probOfSwapping){samplesA[i]=samplesB[i];}}};function Distribution(){}Distribution.prototype={computeDensity:function(x){throw Error('Not implemented');},computePercentile:function(x){throw Error('Not implemented');},computeComplementaryPercentile:function(x){return 1-this.computePercentile(x);},get mean(){throw Error('Not implemented');},get mode(){throw Error('Not implemented');},get median(){throw Error('Not implemented');},get standardDeviation(){throw Error('Not implemented');},get variance(){throw Error('Not implemented');}};Statistics.UniformDistribution=function(opt_range){if(!opt_range)opt_range=tr.b.Range.fromExplicitRange(0,1);this.range=opt_range;};Statistics.UniformDistribution.prototype={__proto__:Distribution.prototype,computeDensity:function(x){return 1/this.range.range;},computePercentile:function(x){return tr.b.normalize(x,this.range.min,this.range.max);},get mean(){return this.range.center;},get mode(){return undefined;},get median(){return this.mean;},get standardDeviation(){return Math.sqrt(this.variance);},get variance(){return Math.pow(this.range.range,2)/12;}};Statistics.NormalDistribution=function(opt_mean,opt_variance){this.mean_=opt_mean||0;this.variance_=opt_variance||1;this.standardDeviation_=Math.sqrt(this.variance_);};Statistics.NormalDistribution.prototype={__proto__:Distribution.prototype,computeDensity:function(x){var scale=1.0/(this.standardDeviation*Math.sqrt(2.0*Math.PI));var exponent=-Math.pow(x-this.mean,2)/(2.0*this.variance);return scale*Math.exp(exponent);},computePercentile:function(x){var standardizedX=(x-this.mean)/Math.sqrt(2.0*this.variance);return(1.0+tr.b.erf(standardizedX))/2.0;},get mean(){return this.mean_;},get median(){return this.mean;},get mode(){return this.mean;},get standardDeviation(){return this.standardDeviation_;},get variance(){return this.variance_;}};Statistics.LogNormalDistribution=function(opt_location,opt_shape){this.normalDistribution_=new Statistics.NormalDistribution(opt_location,Math.pow(opt_shape||1,2));};Statistics.LogNormalDistribution.prototype={__proto__:Statistics.NormalDistribution.prototype,computeDensity:function(x){return this.normalDistribution_.computeDensity(Math.log(x))/x;},computePercentile:function(x){return this.normalDistribution_.computePercentile(Math.log(x));},get mean(){return Math.exp(this.normalDistribution_.mean+this.normalDistribution_.variance/2);},get variance(){var nm=this.normalDistribution_.mean;var nv=this.normalDistribution_.variance;return Math.exp(2*(nm+nv))-Math.exp(2*nm+nv);},get standardDeviation(){return Math.sqrt(this.variance);},get median(){return Math.exp(this.normalDistribution_.mean);},get mode(){return Math.exp(this.normalDistribution_.mean-this.normalDistribution_.variance);}};Statistics.LogNormalDistribution.fromMedianAndDiminishingReturns=function(median,diminishingReturns){diminishingReturns=Math.log(diminishingReturns/median);var shape=Math.sqrt(1-3*diminishingReturns-Math.sqrt(Math.pow(diminishingReturns-3,2)-8))/2;var location=Math.log(median);return new Statistics.LogNormalDistribution(location,shape);};Statistics.DEFAULT_ALPHA=0.05;Statistics.Significance={INSIGNIFICANT:-1,DONT_CARE:0,SIGNIFICANT:1};Statistics.mwu=function(a,b,opt_alpha){var result=mannwhitneyu.test(a,b);var alpha=opt_alpha||Statistics.DEFAULT_ALPHA;result.significance=result.p<alpha?Statistics.Significance.SIGNIFICANT:Statistics.Significance.INSIGNIFICANT;return result;};return{Statistics:Statistics};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./math.js":48,"./range.js":53}],60:[function(require,module,exports){(function(global){"use strict";require("./raf.js");require("./timing.js");'use strict';global.tr.exportTo('tr.b',function(){var Timing=tr.b.Timing;function Task(runCb,thisArg){if(runCb!==undefined&&thisArg===undefined)throw new Error('Almost certainly, you meant to pass a thisArg.');this.runCb_=runCb;this.thisArg_=thisArg;this.afterTask_=undefined;this.subTasks_=[];}Task.prototype={get name(){return this.runCb_.name;},subTask:function(cb,thisArg){if(cb instanceof Task)this.subTasks_.push(cb);else this.subTasks_.push(new Task(cb,thisArg));return this.subTasks_[this.subTasks_.length-1];},run:function(){if(this.runCb_!==undefined)this.runCb_.call(this.thisArg_,this);var subTasks=this.subTasks_;this.subTasks_=undefined;if(!subTasks.length)return this.afterTask_;for(var i=1;i<subTasks.length;i++)subTasks[i-1].afterTask_=subTasks[i];subTasks[subTasks.length-1].afterTask_=this.afterTask_;return subTasks[0];},after:function(cb,thisArg){if(this.afterTask_)throw new Error('Has an after task already');if(cb instanceof Task)this.afterTask_=cb;else this.afterTask_=new Task(cb,thisArg);return this.afterTask_;},timedAfter:function(groupName,cb,thisArg,opt_args){if(cb.name==='')throw new Error('Anonymous Task is not allowed');return this.namedTimedAfter(groupName,cb.name,cb,thisArg,opt_args);},namedTimedAfter:function(groupName,name,cb,thisArg,opt_args){if(this.afterTask_)throw new Error('Has an after task already');var realTask;if(cb instanceof Task)realTask=cb;else realTask=new Task(cb,thisArg);this.afterTask_=new Task(function(task){var markedTask=Timing.mark(groupName,name,opt_args);task.subTask(realTask,thisArg);task.subTask(function(){markedTask.end();},thisArg);},thisArg);return this.afterTask_;},enqueue:function(cb,thisArg){var lastTask=this;while(lastTask.afterTask_)lastTask=lastTask.afterTask_;return lastTask.after(cb,thisArg);}};Task.RunSynchronously=function(task){var curTask=task;while(curTask)curTask=curTask.run();};Task.RunWhenIdle=function(task){return new Promise(function(resolve,reject){var curTask=task;function runAnother(){try{curTask=curTask.run();}catch(e){reject(e);console.error(e.stack);return;}if(curTask){tr.b.requestIdleCallback(runAnother);return;}resolve();}tr.b.requestIdleCallback(runAnother);});};return{Task:Task};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./raf.js":52,"./timing.js":62}],61:[function(require,module,exports){(function(global){"use strict";require("./unit_scale.js");'use strict';global.tr.exportTo('tr.b',function(){var msDisplayMode={scale:1e-3,suffix:'ms',roundedLess:function(a,b){return Math.round(a*1000)<Math.round(b*1000);},formatSpec:{unit:'s',unitPrefix:tr.b.UnitScale.Metric.MILLI,minimumFractionDigits:3}};var nsDisplayMode={scale:1e-9,suffix:'ns',roundedLess:function(a,b){return Math.round(a*1000000)<Math.round(b*1000000);},formatSpec:{unit:'s',unitPrefix:tr.b.UnitScale.Metric.NANO,maximumFractionDigits:0}};var TimeDisplayModes={ns:nsDisplayMode,ms:msDisplayMode};return{TimeDisplayModes:TimeDisplayModes};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./unit_scale.js":64}],62:[function(require,module,exports){(function(global){"use strict";require("./base.js");require("./base64.js");'use strict';global.tr.exportTo('tr.b',function(){var Base64=tr.b.Base64;function computeUserTimingMarkName(groupName,functionName,opt_args){if(groupName===undefined)throw new Error('getMeasureString should have group name');if(functionName===undefined)throw new Error('getMeasureString should have function name');var userTimingMarkName=groupName+':'+functionName;if(opt_args!==undefined){userTimingMarkName+='/';userTimingMarkName+=Base64.btoa(JSON.stringify(opt_args));}return userTimingMarkName;}function Timing(){}Timing.nextMarkNumber=0;Timing.mark=function(groupName,functionName,opt_args){if(tr.isHeadless){return{end:function(){}};}var userTimingMarkName=computeUserTimingMarkName(groupName,functionName,opt_args);var markBeginName='tvcm.mark'+Timing.nextMarkNumber++;var markEndName='tvcm.mark'+Timing.nextMarkNumber++;window.performance.mark(markBeginName);return{end:function(){window.performance.mark(markEndName);window.performance.measure(userTimingMarkName,markBeginName,markEndName);}};};Timing.wrap=function(groupName,callback,opt_args){if(groupName===undefined)throw new Error('Timing.wrap should have group name');if(callback.name==='')throw new Error('Anonymous function is not allowed');return Timing.wrapNamedFunction(groupName,callback.name,callback,opt_args);};Timing.wrapNamedFunction=function(groupName,functionName,callback,opt_args){function timedNamedFunction(){var markedTime=Timing.mark(groupName,functionName,opt_args);try{callback.apply(this,arguments);}finally{markedTime.end();}}return timedNamedFunction;};function TimedNamedPromise(groupName,name,executor,opt_args){var markedTime=Timing.mark(groupName,name,opt_args);var promise=new Promise(executor);promise.then(function(result){markedTime.end();return result;},function(e){markedTime.end();throw e;});return promise;}return{_computeUserTimingMarkName:computeUserTimingMarkName,TimedNamedPromise:TimedNamedPromise,Timing:Timing};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./base.js":34,"./base64.js":35}],63:[function(require,module,exports){(function(global){"use strict";require("./event.js");require("./event_target.js");require("./iteration_helpers.js");require("./time_display_modes.js");require("./unit_scale.js");'use strict';global.tr.exportTo('tr.b',function(){var TimeDisplayModes=tr.b.TimeDisplayModes;var PLUS_MINUS_SIGN=String.fromCharCode(177);function max(a,b){if(a===undefined)return b;if(b===undefined)return a;return a.scale>b.scale?a:b;}var ImprovementDirection={DONT_CARE:0,BIGGER_IS_BETTER:1,SMALLER_IS_BETTER:2};function Unit(unitName,jsonName,basePrefix,isDelta,improvementDirection,formatSpec){this.unitName=unitName;this.jsonName=jsonName;this.basePrefix=basePrefix;this.isDelta=isDelta;this.improvementDirection=improvementDirection;this.formatSpec_=formatSpec;this.baseUnit=undefined;this.correspondingDeltaUnit=undefined;}Unit.prototype={asJSON:function(){return this.jsonName;},get unitString(){var formatSpec=this.formatSpec_;if(typeof formatSpec==='function')formatSpec=formatSpec();if(!formatSpec.unit){return'';}var unitString='';var unitPrefix=formatSpec.unitPrefix;if(unitPrefix!==undefined){var selectedPrefix;if(unitPrefix instanceof Array){selectedPrefix=unitPrefix[0];}else{selectedPrefix=unitPrefix;}unitString+=selectedPrefix.symbol||'';}unitString+=formatSpec.unit;return unitString;},format:function(value,opt_context){var context=opt_context||{};var formatSpec=this.formatSpec_;if(typeof formatSpec==='function')formatSpec=formatSpec();function resolveProperty(propertyName){if(propertyName in context)return context[propertyName];else if(propertyName in formatSpec)return formatSpec[propertyName];else return undefined;}var signString='';if(value<0){signString='-';value=-value;}else if(this.isDelta){signString=value===0?PLUS_MINUS_SIGN:'+';}var unitString='';if(formatSpec.unit){if(formatSpec.unitHasPrecedingSpace!==false)unitString+=' ';var unitPrefix=resolveProperty('unitPrefix');if(unitPrefix!==undefined){var selectedPrefix;if(unitPrefix instanceof Array){var i=0;while(i<unitPrefix.length-1&&value/unitPrefix[i+1].value>=1){i++;}selectedPrefix=unitPrefix[i];}else{selectedPrefix=unitPrefix;}unitString+=selectedPrefix.symbol||'';value=tr.b.convertUnit(value,this.basePrefix,selectedPrefix);}else{value=tr.b.convertUnit(value,this.basePrefix,tr.b.UnitScale.Metric.NONE);}unitString+=formatSpec.unit;}var minimumFractionDigits=resolveProperty('minimumFractionDigits');var maximumFractionDigits=resolveProperty('maximumFractionDigits');if(minimumFractionDigits>maximumFractionDigits){if('minimumFractionDigits'in context&&!('maximumFractionDigits'in context)){maximumFractionDigits=minimumFractionDigits;}else if('maximumFractionDigits'in context&&!('minimumFractionDigits'in context)){minimumFractionDigits=maximumFractionDigits;}}var numberString=value.toLocaleString(undefined,{minimumFractionDigits:minimumFractionDigits,maximumFractionDigits:maximumFractionDigits});return signString+numberString+unitString;}};Unit.reset=function(){Unit.currentTimeDisplayMode=TimeDisplayModes.ms;};Unit.timestampFromUs=function(us){return tr.b.convertUnit(us,tr.b.UnitScale.Metric.MICRO,tr.b.UnitScale.Metric.MILLI);};Object.defineProperty(Unit,'currentTimeDisplayMode',{get:function(){return Unit.currentTimeDisplayMode_;},set:function(value){if(Unit.currentTimeDisplayMode_===value)return;Unit.currentTimeDisplayMode_=value;Unit.dispatchEvent(new tr.b.Event('display-mode-changed'));}});Unit.didPreferredTimeDisplayUnitChange=function(){var largest=undefined;var els=tr.b.findDeepElementsMatching(document.body,'tr-v-ui-preferred-display-unit');els.forEach(function(el){largest=max(largest,el.preferredTimeDisplayMode);});Unit.currentDisplayUnit=largest===undefined?TimeDisplayModes.ms:largest;};Unit.byName={};Unit.byJSONName={};Unit.fromJSON=function(object){var u=Unit.byJSONName[object];if(u){return u;}throw new Error('Unrecognized unit');};Unit.define=function(params){var definedUnits=[];tr.b.iterItems(ImprovementDirection,function(_,improvementDirection){var regularUnit=Unit.defineUnitVariant_(params,false,improvementDirection);var deltaUnit=Unit.defineUnitVariant_(params,true,improvementDirection);regularUnit.correspondingDeltaUnit=deltaUnit;deltaUnit.correspondingDeltaUnit=deltaUnit;definedUnits.push(regularUnit,deltaUnit);});var baseUnit=Unit.byName[params.baseUnitName];definedUnits.forEach(u=>u.baseUnit=baseUnit);};Unit.nameSuffixForImprovementDirection=function(improvementDirection){switch(improvementDirection){case ImprovementDirection.DONT_CARE:return'';case ImprovementDirection.BIGGER_IS_BETTER:return'_biggerIsBetter';case ImprovementDirection.SMALLER_IS_BETTER:return'_smallerIsBetter';default:throw new Error('Unknown improvement direction: '+improvementDirection);}};Unit.defineUnitVariant_=function(params,isDelta,improvementDirection){var nameSuffix=isDelta?'Delta':'';nameSuffix+=Unit.nameSuffixForImprovementDirection(improvementDirection);var unitName=params.baseUnitName+nameSuffix;var jsonName=params.baseJsonName+nameSuffix;if(Unit.byName[unitName]!==undefined)throw new Error('Unit \''+unitName+'\' already exists');if(Unit.byJSONName[jsonName]!==undefined)throw new Error('JSON unit \''+jsonName+'\' alread exists');var basePrefix=params.basePrefix?params.basePrefix:tr.b.UnitScale.Metric.NONE;var unit=new Unit(unitName,jsonName,basePrefix,isDelta,improvementDirection,params.formatSpec);Unit.byName[unitName]=unit;Unit.byJSONName[jsonName]=unit;return unit;};tr.b.EventTarget.decorate(Unit);Unit.reset();Unit.define({baseUnitName:'timeDurationInMs',baseJsonName:'ms',basePrefix:tr.b.UnitScale.Metric.MILLI,formatSpec:function(){return Unit.currentTimeDisplayMode_.formatSpec;}});Unit.define({baseUnitName:'timeStampInMs',baseJsonName:'tsMs',basePrefix:tr.b.UnitScale.Metric.MILLI,formatSpec:function(){return Unit.currentTimeDisplayMode_.formatSpec;}});Unit.define({baseUnitName:'normalizedPercentage',baseJsonName:'n%',formatSpec:{unit:'%',unitPrefix:{value:0.01},unitHasPrecedingSpace:false,minimumFractionDigits:3,maximumFractionDigits:3}});Unit.define({baseUnitName:'sizeInBytes',baseJsonName:'sizeInBytes',formatSpec:{unit:'B',unitPrefix:tr.b.UnitScale.Binary.AUTO,minimumFractionDigits:1,maximumFractionDigits:1}});Unit.define({baseUnitName:'energyInJoules',baseJsonName:'J',formatSpec:{unit:'J',minimumFractionDigits:3}});Unit.define({baseUnitName:'powerInWatts',baseJsonName:'W',formatSpec:{unit:'W',minimumFractionDigits:3}});Unit.define({baseUnitName:'unitlessNumber',baseJsonName:'unitless',formatSpec:{minimumFractionDigits:3,maximumFractionDigits:3}});Unit.define({baseUnitName:'count',baseJsonName:'count',formatSpec:{minimumFractionDigits:0,maximumFractionDigits:0}});Unit.define({baseUnitName:'sigma',baseJsonName:'sigma',formatSpec:{unit:String.fromCharCode(963),minimumFractionDigits:1,maximumFractionDigits:1}});return{ImprovementDirection:ImprovementDirection,Unit:Unit};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./event.js":39,"./event_target.js":40,"./iteration_helpers.js":47,"./time_display_modes.js":61,"./unit_scale.js":64}],64:[function(require,module,exports){(function(global){"use strict";require("./iteration_helpers.js");'use strict';var GREEK_SMALL_LETTER_MU=String.fromCharCode(956);global.tr.exportTo('tr.b',function(){var UnitScale={};function defineUnitScale(name,prefixes){if(UnitScale[name]!==undefined)throw new Error('Unit scale \''+name+'\' already exists');if(prefixes.AUTO!==undefined){throw new Error('\'AUTO\' unit prefix will be added automatically '+'for unit scale \''+name+'\'');}prefixes.AUTO=tr.b.dictionaryValues(prefixes);prefixes.AUTO.sort((a,b)=>a.value-b.value);UnitScale[name]=prefixes;}function convertUnit(value,fromPrefix,toPrefix){if(value===undefined)return undefined;return value*(fromPrefix.value/toPrefix.value);}defineUnitScale('Binary',{NONE:{value:Math.pow(1024,0),symbol:''},KIBI:{value:Math.pow(1024,1),symbol:'Ki'},MEBI:{value:Math.pow(1024,2),symbol:'Mi'},GIBI:{value:Math.pow(1024,3),symbol:'Gi'},TEBI:{value:Math.pow(1024,4),symbol:'Ti'}});defineUnitScale('Metric',{NANO:{value:1e-9,symbol:'n'},MICRO:{value:1e-6,symbol:GREEK_SMALL_LETTER_MU},MILLI:{value:1e-3,symbol:'m'},NONE:{value:1,symbol:''},KILO:{value:1e3,symbol:'k'},MEGA:{value:1e6,symbol:'M'},GIGA:{value:1e9,symbol:'G'}});return{UnitScale:UnitScale,convertUnit:convertUnit};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./iteration_helpers.js":47}],65:[function(require,module,exports){(function(global){"use strict";require("./base.js");'use strict';global.tr.exportTo('tr.b',function(){function addSingletonGetter(ctor){ctor.getInstance=function(){return ctor.instance_||(ctor.instance_=new ctor());};}function deepCopy(value){if(!(value instanceof Object)){if(value===undefined||value===null)return value;if(typeof value=='string')return value.substring();if(typeof value=='boolean')return value;if(typeof value=='number')return value;throw new Error('Unrecognized: '+typeof value);}var object=value;if(object instanceof Array){var res=new Array(object.length);for(var i=0;i<object.length;i++)res[i]=deepCopy(object[i]);return res;}if(object.__proto__!=Object.prototype)throw new Error('Can only clone simple types');var res={};for(var key in object){res[key]=deepCopy(object[key]);}return res;}function normalizeException(e){if(e===undefined||e===null){return{typeName:'UndefinedError',message:'Unknown: null or undefined exception',stack:'Unknown'};}if(typeof e=='string'){return{typeName:'StringError',message:e,stack:[e]};}var typeName;if(e.name){typeName=e.name;}else if(e.constructor){if(e.constructor.name){typeName=e.constructor.name;}else{typeName='AnonymousError';}}else{typeName='ErrorWithNoConstructor';}var msg=e.message?e.message:'Unknown';return{typeName:typeName,message:msg,stack:e.stack?e.stack:[msg]};}function stackTraceAsString(){return new Error().stack+'';}function stackTrace(){var stack=stackTraceAsString();stack=stack.split('\n');return stack.slice(2);}function getUsingPath(path,fromDict){var parts=path.split('.');var cur=fromDict;for(var part;parts.length&&(part=parts.shift());){if(!parts.length){return cur[part];}else if(part in cur){cur=cur[part];}else{return undefined;}}return undefined;}function formatDate(date){return date.toISOString().replace('T',' ').slice(0,19);}return{addSingletonGetter:addSingletonGetter,deepCopy:deepCopy,normalizeException:normalizeException,stackTrace:stackTrace,stackTraceAsString:stackTraceAsString,formatDate:formatDate,getUsingPath:getUsingPath};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./base.js":34}],66:[function(require,module,exports){(function(global){"use strict";require("../base/base.js");require("../base/extension_registry.js");'use strict';global.tr.exportTo('tr.c',function(){function Auditor(model){this.model_=model;}Auditor.prototype={__proto__:Object.prototype,get model(){return this.model_;},runAnnotate:function(){},installUserFriendlyCategoryDriverIfNeeded:function(){},runAudit:function(){}};var options=new tr.b.ExtensionRegistryOptions(tr.b.BASIC_REGISTRY_MODE);options.defaultMetadata={};options.mandatoryBaseClass=Auditor;tr.b.decorateExtensionRegistry(Auditor,options);return{Auditor:Auditor};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/base.js":34,"../base/extension_registry.js":41}],67:[function(require,module,exports){(function(global){"use strict";require("../base/base.js");'use strict';global.tr.exportTo('tr.c',function(){function makeCaseInsensitiveRegex(pattern){pattern=pattern.replace(/[.*+?^${}()|[\]\\]/g,'\\$&');return new RegExp(pattern,'i');}function Filter(){}Filter.prototype={__proto__:Object.prototype,matchCounter:function(counter){return true;},matchCpu:function(cpu){return true;},matchProcess:function(process){return true;},matchSlice:function(slice){return true;},matchThread:function(thread){return true;}};function TitleOrCategoryFilter(text){Filter.call(this);this.regex_=makeCaseInsensitiveRegex(text);if(!text.length)throw new Error('Filter text is empty.');}TitleOrCategoryFilter.prototype={__proto__:Filter.prototype,matchSlice:function(slice){if(slice.title===undefined&&slice.category===undefined)return false;return this.regex_.test(slice.title)||!!slice.category&&this.regex_.test(slice.category);}};function ExactTitleFilter(text){Filter.call(this);this.text_=text;if(!text.length)throw new Error('Filter text is empty.');}ExactTitleFilter.prototype={__proto__:Filter.prototype,matchSlice:function(slice){return slice.title===this.text_;}};function FullTextFilter(text){Filter.call(this);this.regex_=makeCaseInsensitiveRegex(text);this.titleOrCategoryFilter_=new TitleOrCategoryFilter(text);}FullTextFilter.prototype={__proto__:Filter.prototype,matchObject_:function(obj){for(var key in obj){if(!obj.hasOwnProperty(key))continue;if(this.regex_.test(key))return true;if(this.regex_.test(obj[key]))return true;}return false;},matchSlice:function(slice){if(this.titleOrCategoryFilter_.matchSlice(slice))return true;return this.matchObject_(slice.args);}};return{Filter:Filter,TitleOrCategoryFilter:TitleOrCategoryFilter,ExactTitleFilter:ExactTitleFilter,FullTextFilter:FullTextFilter};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/base.js":34}],68:[function(require,module,exports){(function(global){"use strict";require("../../../model/async_slice.js");require("../../../model/event_set.js");require("../../../model/helpers/chrome_model_helper.js");'use strict';global.tr.exportTo('tr.e.cc',function(){var AsyncSlice=tr.model.AsyncSlice;var EventSet=tr.model.EventSet;var UI_COMP_NAME='INPUT_EVENT_LATENCY_UI_COMPONENT';var ORIGINAL_COMP_NAME='INPUT_EVENT_LATENCY_ORIGINAL_COMPONENT';var BEGIN_COMP_NAME='INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT';var END_COMP_NAME='INPUT_EVENT_LATENCY_TERMINATED_FRAME_SWAP_COMPONENT';var MAIN_RENDERER_THREAD_NAME='CrRendererMain';var COMPOSITOR_THREAD_NAME='Compositor';var POSTTASK_FLOW_EVENT='disabled-by-default-toplevel.flow';var IPC_FLOW_EVENT='disabled-by-default-ipc.flow';var INPUT_EVENT_TYPE_NAMES={CHAR:'Char',CLICK:'GestureClick',CONTEXT_MENU:'ContextMenu',FLING_CANCEL:'GestureFlingCancel',FLING_START:'GestureFlingStart',KEY_DOWN:'KeyDown',KEY_DOWN_RAW:'RawKeyDown',KEY_UP:'KeyUp',LATENCY_SCROLL_UPDATE:'ScrollUpdate',MOUSE_DOWN:'MouseDown',MOUSE_ENTER:'MouseEnter',MOUSE_LEAVE:'MouseLeave',MOUSE_MOVE:'MouseMove',MOUSE_UP:'MouseUp',MOUSE_WHEEL:'MouseWheel',PINCH_BEGIN:'GesturePinchBegin',PINCH_END:'GesturePinchEnd',PINCH_UPDATE:'GesturePinchUpdate',SCROLL_BEGIN:'GestureScrollBegin',SCROLL_END:'GestureScrollEnd',SCROLL_UPDATE:'GestureScrollUpdate',SCROLL_UPDATE_RENDERER:'ScrollUpdate',SHOW_PRESS:'GestureShowPress',TAP:'GestureTap',TAP_CANCEL:'GestureTapCancel',TAP_DOWN:'GestureTapDown',TOUCH_CANCEL:'TouchCancel',TOUCH_END:'TouchEnd',TOUCH_MOVE:'TouchMove',TOUCH_START:'TouchStart',UNKNOWN:'UNKNOWN'};function InputLatencyAsyncSlice(){AsyncSlice.apply(this,arguments);this.associatedEvents_=new EventSet();this.typeName_=undefined;if(!this.isLegacyEvent)this.determineModernTypeName_();}InputLatencyAsyncSlice.prototype={__proto__:AsyncSlice.prototype,get isLegacyEvent(){return this.title==='InputLatency';},get typeName(){if(!this.typeName_)this.determineLegacyTypeName_();return this.typeName_;},checkTypeName_:function(){if(!this.typeName_)throw'Unable to determine typeName';var found=false;for(var typeName in INPUT_EVENT_TYPE_NAMES){if(this.typeName===INPUT_EVENT_TYPE_NAMES[typeName]){found=true;break;}}if(!found)this.typeName_=INPUT_EVENT_TYPE_NAMES.UNKNOWN;},determineModernTypeName_:function(){var lastColonIndex=this.title.lastIndexOf(':');if(lastColonIndex<0)return;var characterAfterLastColonIndex=lastColonIndex+1;this.typeName_=this.title.slice(characterAfterLastColonIndex);this.checkTypeName_();},determineLegacyTypeName_:function(){for(var subSlice of this.enumerateAllDescendents()){var subSliceIsAInputLatencyAsyncSlice=subSlice instanceof InputLatencyAsyncSlice;if(!subSliceIsAInputLatencyAsyncSlice)continue;if(!subSlice.typeName)continue;if(this.typeName_&&subSlice.typeName_){var subSliceHasDifferentTypeName=this.typeName_!==subSlice.typeName_;if(subSliceHasDifferentTypeName){throw'InputLatencyAsyncSlice.determineLegacyTypeName_() '+' found multiple typeNames';}}this.typeName_=subSlice.typeName_;}if(!this.typeName_)throw'InputLatencyAsyncSlice.determineLegacyTypeName_() failed';this.checkTypeName_();},getRendererHelper:function(sourceSlices){var traceModel=this.startThread.parent.model;var modelHelper=traceModel.getOrCreateHelper(tr.model.helpers.ChromeModelHelper);if(!modelHelper)return undefined;var mainThread=undefined;var compositorThread=undefined;for(var i in sourceSlices){if(sourceSlices[i].parentContainer.name===MAIN_RENDERER_THREAD_NAME)mainThread=sourceSlices[i].parentContainer;else if(sourceSlices[i].parentContainer.name===COMPOSITOR_THREAD_NAME)compositorThread=sourceSlices[i].parentContainer;if(mainThread&&compositorThread)break;}var rendererHelpers=modelHelper.rendererHelpers;var pids=Object.keys(rendererHelpers);for(var i=0;i<pids.length;i++){var pid=pids[i];var rendererHelper=rendererHelpers[pid];if(rendererHelper.mainThread===mainThread||rendererHelper.compositorThread===compositorThread)return rendererHelper;}return undefined;},addEntireSliceHierarchy:function(slice){this.associatedEvents_.push(slice);slice.iterateAllSubsequentSlices(function(subsequentSlice){this.associatedEvents_.push(subsequentSlice);},this);},addDirectlyAssociatedEvents:function(flowEvents){var slices=[];flowEvents.forEach(function(flowEvent){this.associatedEvents_.push(flowEvent);var newSource=flowEvent.startSlice.mostTopLevelSlice;if(slices.indexOf(newSource)===-1)slices.push(newSource);},this);var lastFlowEvent=flowEvents[flowEvents.length-1];var lastSource=lastFlowEvent.endSlice.mostTopLevelSlice;if(slices.indexOf(lastSource)===-1)slices.push(lastSource);return slices;},addScrollUpdateEvents:function(rendererHelper){if(!rendererHelper||!rendererHelper.compositorThread)return;var compositorThread=rendererHelper.compositorThread;var gestureScrollUpdateStart=this.start;var gestureScrollUpdateEnd=this.end;var allCompositorAsyncSlices=compositorThread.asyncSliceGroup.slices;for(var i in allCompositorAsyncSlices){var slice=allCompositorAsyncSlices[i];if(slice.title!=='Latency::ScrollUpdate')continue;var parentId=slice.args.data.INPUT_EVENT_LATENCY_FORWARD_SCROLL_UPDATE_TO_MAIN_COMPONENT.sequence_number;if(parentId===undefined){if(slice.start<gestureScrollUpdateStart||slice.start>=gestureScrollUpdateEnd)continue;}else{if(parseInt(parentId)!==parseInt(this.id))continue;}slice.associatedEvents.forEach(function(event){this.associatedEvents_.push(event);},this);break;}},belongToOtherInputs:function(slice,flowEvents){var fromOtherInputs=false;slice.iterateEntireHierarchy(function(subsequentSlice){if(fromOtherInputs)return;subsequentSlice.inFlowEvents.forEach(function(inflow){if(fromOtherInputs)return;if(inflow.category.indexOf('input')>-1){if(flowEvents.indexOf(inflow)===-1)fromOtherInputs=true;}},this);},this);return fromOtherInputs;},triggerOtherInputs:function(event,flowEvents){if(event.outFlowEvents===undefined||event.outFlowEvents.length===0)return false;var flow=event.outFlowEvents[0];if(flow.category!==POSTTASK_FLOW_EVENT||!flow.endSlice)return false;var endSlice=flow.endSlice;if(this.belongToOtherInputs(endSlice.mostTopLevelSlice,flowEvents))return true;return false;},followSubsequentSlices:function(event,queue,visited,flowEvents){var stopFollowing=false;var inputAck=false;event.iterateAllSubsequentSlices(function(slice){if(stopFollowing)return;if(slice.title==='TaskQueueManager::RunTask')return;if(slice.title==='ThreadProxy::ScheduledActionSendBeginMainFrame')return;if(slice.title==='Scheduler::ScheduleBeginImplFrameDeadline'){if(this.triggerOtherInputs(slice,flowEvents))return;}if(slice.title==='CompositorImpl::PostComposite'){if(this.triggerOtherInputs(slice,flowEvents))return;}if(slice.title==='InputRouterImpl::ProcessInputEventAck')inputAck=true;if(inputAck&&slice.title==='InputRouterImpl::FilterAndSendWebInputEvent')stopFollowing=true;this.followCurrentSlice(slice,queue,visited);},this);},followCurrentSlice:function(event,queue,visited){event.outFlowEvents.forEach(function(outflow){if((outflow.category===POSTTASK_FLOW_EVENT||outflow.category===IPC_FLOW_EVENT)&&outflow.endSlice){this.associatedEvents_.push(outflow);var nextEvent=outflow.endSlice.mostTopLevelSlice;if(!visited.contains(nextEvent)){visited.push(nextEvent);queue.push(nextEvent);}}},this);},backtraceFromDraw:function(beginImplFrame,visited){var pendingEventQueue=[];pendingEventQueue.push(beginImplFrame.mostTopLevelSlice);while(pendingEventQueue.length!==0){var event=pendingEventQueue.pop();this.addEntireSliceHierarchy(event);event.inFlowEvents.forEach(function(inflow){if(inflow.category===POSTTASK_FLOW_EVENT&&inflow.startSlice){var nextEvent=inflow.startSlice.mostTopLevelSlice;if(!visited.contains(nextEvent)){visited.push(nextEvent);pendingEventQueue.push(nextEvent);}}},this);}},sortRasterizerSlices:function(rasterWorkerThreads,sortedRasterizerSlices){rasterWorkerThreads.forEach(function(rasterizer){Array.prototype.push.apply(sortedRasterizerSlices,rasterizer.sliceGroup.slices);},this);sortedRasterizerSlices.sort(function(a,b){if(a.start!==b.start)return a.start-b.start;return a.guid-b.guid;});},addRasterizationEvents:function(prepareTiles,rendererHelper,visited,flowEvents,sortedRasterizerSlices){if(!prepareTiles.args.prepare_tiles_id)return;if(!rendererHelper||!rendererHelper.rasterWorkerThreads)return;var rasterWorkerThreads=rendererHelper.rasterWorkerThreads;var prepareTileId=prepareTiles.args.prepare_tiles_id;var pendingEventQueue=[];if(sortedRasterizerSlices.length===0)this.sortRasterizerSlices(rasterWorkerThreads,sortedRasterizerSlices);var numFinishedTasks=0;var RASTER_TASK_TITLE='RasterizerTaskImpl::RunOnWorkerThread';var IMAGEDECODE_TASK_TITLE='ImageDecodeTaskImpl::RunOnWorkerThread';var FINISHED_TASK_TITLE='TaskSetFinishedTaskImpl::RunOnWorkerThread';for(var i=0;i<sortedRasterizerSlices.length;i++){var task=sortedRasterizerSlices[i];if(task.title===RASTER_TASK_TITLE||task.title===IMAGEDECODE_TASK_TITLE){if(task.args.source_prepare_tiles_id===prepareTileId)this.addEntireSliceHierarchy(task.mostTopLevelSlice);}else if(task.title===FINISHED_TASK_TITLE){if(task.start>prepareTiles.start){pendingEventQueue.push(task.mostTopLevelSlice);if(++numFinishedTasks===3)break;}}}while(pendingEventQueue.length!=0){var event=pendingEventQueue.pop();this.addEntireSliceHierarchy(event);this.followSubsequentSlices(event,pendingEventQueue,visited,flowEvents);}},addOtherCausallyRelatedEvents:function(rendererHelper,sourceSlices,flowEvents,sortedRasterizerSlices){var pendingEventQueue=[];var visitedEvents=new EventSet();var beginImplFrame=undefined;var prepareTiles=undefined;var sortedRasterizerSlices=[];sourceSlices.forEach(function(sourceSlice){if(!visitedEvents.contains(sourceSlice)){visitedEvents.push(sourceSlice);pendingEventQueue.push(sourceSlice);}},this);while(pendingEventQueue.length!=0){var event=pendingEventQueue.pop();this.addEntireSliceHierarchy(event);this.followCurrentSlice(event,pendingEventQueue,visitedEvents);this.followSubsequentSlices(event,pendingEventQueue,visitedEvents,flowEvents);var COMPOSITOR_PREPARE_TILES='TileManager::PrepareTiles';prepareTiles=event.findDescendentSlice(COMPOSITOR_PREPARE_TILES);if(prepareTiles)this.addRasterizationEvents(prepareTiles,rendererHelper,visitedEvents,flowEvents,sortedRasterizerSlices);var COMPOSITOR_ON_BIFD='Scheduler::OnBeginImplFrameDeadline';beginImplFrame=event.findDescendentSlice(COMPOSITOR_ON_BIFD);if(beginImplFrame)this.backtraceFromDraw(beginImplFrame,visitedEvents);}var INPUT_GSU='InputLatency::GestureScrollUpdate';if(this.title===INPUT_GSU)this.addScrollUpdateEvents(rendererHelper);},get associatedEvents(){if(this.associatedEvents_.length!==0)return this.associatedEvents_;var modelIndices=this.startThread.parent.model.modelIndices;var flowEvents=modelIndices.getFlowEventsWithId(this.id);if(flowEvents.length===0)return this.associatedEvents_;var sourceSlices=this.addDirectlyAssociatedEvents(flowEvents);var rendererHelper=this.getRendererHelper(sourceSlices);this.addOtherCausallyRelatedEvents(rendererHelper,sourceSlices,flowEvents);return this.associatedEvents_;},get inputLatency(){if(!('data'in this.args))return undefined;var data=this.args.data;if(!(END_COMP_NAME in data))return undefined;var latency=0;var endTime=data[END_COMP_NAME].time;if(ORIGINAL_COMP_NAME in data){latency=endTime-data[ORIGINAL_COMP_NAME].time;}else if(UI_COMP_NAME in data){latency=endTime-data[UI_COMP_NAME].time;}else if(BEGIN_COMP_NAME in data){latency=endTime-data[BEGIN_COMP_NAME].time;}else{throw new Error('No valid begin latency component');}return latency;}};var eventTypeNames=['Char','ContextMenu','GestureClick','GestureFlingCancel','GestureFlingStart','GestureScrollBegin','GestureScrollEnd','GestureScrollUpdate','GestureShowPress','GestureTap','GestureTapCancel','GestureTapDown','GesturePinchBegin','GesturePinchEnd','GesturePinchUpdate','KeyDown','KeyUp','MouseDown','MouseEnter','MouseLeave','MouseMove','MouseUp','MouseWheel','RawKeyDown','ScrollUpdate','TouchCancel','TouchEnd','TouchMove','TouchStart'];var allTypeNames=['InputLatency'];eventTypeNames.forEach(function(eventTypeName){allTypeNames.push('InputLatency:'+eventTypeName);allTypeNames.push('InputLatency::'+eventTypeName);});AsyncSlice.subTypes.register(InputLatencyAsyncSlice,{typeNames:allTypeNames,categoryParts:['latencyInfo']});return{InputLatencyAsyncSlice:InputLatencyAsyncSlice,INPUT_EVENT_TYPE_NAMES:INPUT_EVENT_TYPE_NAMES};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../../../model/async_slice.js":109,"../../../model/event_set.js":126,"../../../model/helpers/chrome_model_helper.js":133}],69:[function(require,module,exports){(function(global){"use strict";require("../../base/event.js");require("../../base/iteration_helpers.js");require("../../base/sinebow_color_generator.js");'use strict';global.tr.exportTo('tr.e.chrome',function(){var SAME_AS_PARENT='same-as-parent';var TITLES_FOR_USER_FRIENDLY_CATEGORY={composite:['CompositingInputsUpdater::update','ThreadProxy::SetNeedsUpdateLayers','LayerTreeHost::UpdateLayers::CalcDrawProps','UpdateLayerTree'],gc:['minorGC','majorGC','MajorGC','MinorGC','V8.GCScavenger','V8.GCIncrementalMarking','V8.GCIdleNotification','V8.GCContext','V8.GCCompactor','V8GCController::traceDOMWrappers'],iframe_creation:['WebLocalFrameImpl::createChildframe'],imageDecode:['Decode Image','ImageFrameGenerator::decode','ImageFrameGenerator::decodeAndScale'],input:['HitTest','ScrollableArea::scrollPositionChanged','EventHandler::handleMouseMoveEvent'],layout:['FrameView::invalidateTree','FrameView::layout','FrameView::performLayout','FrameView::performPostLayoutTasks','FrameView::performPreLayoutTasks','Layer::updateLayerPositionsAfterLayout','Layout','LayoutView::hitTest','ResourceLoadPriorityOptimizer::updateAllImageResourcePriorities','WebViewImpl::layout'],parseHTML:['ParseHTML','HTMLDocumentParser::didReceiveParsedChunkFromBackgroundParser','HTMLDocumentParser::processParsedChunkFromBackgroundParser'],raster:['DisplayListRasterSource::PerformSolidColorAnalysis','Picture::Raster','RasterBufferImpl::Playback','RasterTask','RasterizerTaskImpl::RunOnWorkerThread','SkCanvas::drawImageRect()','SkCanvas::drawPicture()','SkCanvas::drawTextBlob()','TileTaskWorkerPool::PlaybackToMemory'],record:['ContentLayerDelegate::paintContents','DeprecatedPaintLayerCompositor::updateIfNeededRecursive','DeprecatedPaintLayerCompositor::updateLayerPositionsAfterLayout','Paint','Picture::Record','PictureLayer::Update','RenderLayer::updateLayerPositionsAfterLayout'],style:['CSSParserImpl::parseStyleSheet.parse','CSSParserImpl::parseStyleSheet.tokenize','Document::updateStyle','Document::updateStyleInvalidationIfNeeded','ParseAuthorStyleSheet','RuleSet::addRulesFromSheet','StyleElement::processStyleSheet','StyleEngine::createResolver','StyleSheetContents::parseAuthorStyleSheet','UpdateLayoutTree'],script_parse_and_compile:['v8.parseOnBackground','V8.ScriptCompiler'],script_execute:['V8.Execute','WindowProxy::initialize'],resource_loading:['ResourceFetcher::requestResource','ResourceDispatcher::OnReceivedData','ResourceDispatcher::OnRequestComplete','ResourceDispatcher::OnReceivedResponse','Resource::appendData'],renderer_misc:['DecodeFont','ThreadState::completeSweep'],v8_runtime:[],[SAME_AS_PARENT]:['SyncChannel::Send']};var COLOR_FOR_USER_FRIENDLY_CATEGORY=new tr.b.SinebowColorGenerator();var USER_FRIENDLY_CATEGORY_FOR_TITLE=new Map();for(var category in TITLES_FOR_USER_FRIENDLY_CATEGORY){TITLES_FOR_USER_FRIENDLY_CATEGORY[category].forEach(function(title){USER_FRIENDLY_CATEGORY_FOR_TITLE.set(title,category);});}var USER_FRIENDLY_CATEGORY_FOR_EVENT_CATEGORY={netlog:'net',overhead:'overhead',startup:'startup',gpu:'gpu'};function ChromeUserFriendlyCategoryDriver(){}ChromeUserFriendlyCategoryDriver.fromEvent=function(event){var userFriendlyCategory=USER_FRIENDLY_CATEGORY_FOR_TITLE.get(event.title);if(userFriendlyCategory){if(userFriendlyCategory==SAME_AS_PARENT){if(event.parentSlice)return ChromeUserFriendlyCategoryDriver.fromEvent(event.parentSlice);}else{return userFriendlyCategory;}}var eventCategoryParts=tr.b.getCategoryParts(event.category);for(var i=0;i<eventCategoryParts.length;++i){var eventCategory=eventCategoryParts[i];userFriendlyCategory=USER_FRIENDLY_CATEGORY_FOR_EVENT_CATEGORY[eventCategory];if(userFriendlyCategory)return userFriendlyCategory;}return'other';};ChromeUserFriendlyCategoryDriver.getColor=function(ufc){return COLOR_FOR_USER_FRIENDLY_CATEGORY.colorForKey(ufc);};ChromeUserFriendlyCategoryDriver.ALL_TITLES=['other'];for(var category in TITLES_FOR_USER_FRIENDLY_CATEGORY){if(category===SAME_AS_PARENT)continue;ChromeUserFriendlyCategoryDriver.ALL_TITLES.push(category);}for(var category of tr.b.dictionaryValues(USER_FRIENDLY_CATEGORY_FOR_EVENT_CATEGORY)){ChromeUserFriendlyCategoryDriver.ALL_TITLES.push(category);}ChromeUserFriendlyCategoryDriver.ALL_TITLES.sort();for(var category of ChromeUserFriendlyCategoryDriver.ALL_TITLES)ChromeUserFriendlyCategoryDriver.getColor(category);return{ChromeUserFriendlyCategoryDriver:ChromeUserFriendlyCategoryDriver};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../../base/event.js":39,"../../base/iteration_helpers.js":47,"../../base/sinebow_color_generator.js":57}],70:[function(require,module,exports){(function(global){"use strict";require("../../model/source_info/js_source_info.js");'use strict';global.tr.exportTo('tr.e.importer',function(){function TraceCodeEntry(address,size,name,scriptId){this.id_=tr.b.GUID.allocateSimple();this.address_=address;this.size_=size;var rePrefix=/^(\w*:)?([*~]?)(.*)$/m;var tokens=rePrefix.exec(name);var prefix=tokens[1];var state=tokens[2];var body=tokens[3];if(state==='*'){state=tr.model.source_info.JSSourceState.OPTIMIZED;}else if(state==='~'){state=tr.model.source_info.JSSourceState.OPTIMIZABLE;}else if(state===''){state=tr.model.source_info.JSSourceState.COMPILED;}else{console.warning('Unknown v8 code state '+state);state=tr.model.source_info.JSSourceState.UNKNOWN;}var rawName;var rawUrl;if(prefix==='Script:'){rawName='';rawUrl=body;}else{var spacePos=body.lastIndexOf(' ');rawName=spacePos!==-1?body.substr(0,spacePos):body;rawUrl=spacePos!==-1?body.substr(spacePos+1):'';}function splitLineAndColumn(url){var lineColumnRegEx=/(?::(\d+))?(?::(\d+))?$/;var lineColumnMatch=lineColumnRegEx.exec(url);var lineNumber;var columnNumber;if(typeof lineColumnMatch[1]==='string'){lineNumber=parseInt(lineColumnMatch[1],10);lineNumber=isNaN(lineNumber)?undefined:lineNumber-1;}if(typeof lineColumnMatch[2]==='string'){columnNumber=parseInt(lineColumnMatch[2],10);columnNumber=isNaN(columnNumber)?undefined:columnNumber-1;}return{url:url.substring(0,url.length-lineColumnMatch[0].length),lineNumber:lineNumber,columnNumber:columnNumber};}var nativeSuffix=' native';var isNative=rawName.endsWith(nativeSuffix);this.name_=isNative?rawName.slice(0,-nativeSuffix.length):rawName;var urlData=splitLineAndColumn(rawUrl);var url=urlData.url||'';var line=urlData.lineNumber||0;var column=urlData.columnNumber||0;this.sourceInfo_=new tr.model.source_info.JSSourceInfo(url,line,column,isNative,scriptId,state);};TraceCodeEntry.prototype={get id(){return this.id_;},get sourceInfo(){return this.sourceInfo_;},get name(){return this.name_;},set address(address){this.address_=address;},get address(){return this.address_;},set size(size){this.size_=size;},get size(){return this.size_;}};return{TraceCodeEntry:TraceCodeEntry};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../../model/source_info/js_source_info.js":159}],71:[function(require,module,exports){(function(global){"use strict";require("./trace_code_entry.js");'use strict';global.tr.exportTo('tr.e.importer',function(){function TraceCodeMap(){this.banks_=new Map();}TraceCodeMap.prototype={addEntry:function(addressHex,size,name,scriptId){var entry=new tr.e.importer.TraceCodeEntry(this.getAddress_(addressHex),size,name,scriptId);this.addEntry_(addressHex,entry);},moveEntry:function(oldAddressHex,newAddressHex,size){var entry=this.getBank_(oldAddressHex).removeEntry(this.getAddress_(oldAddressHex));if(!entry)return;entry.address=this.getAddress_(newAddressHex);entry.size=size;this.addEntry_(newAddressHex,entry);},lookupEntry:function(addressHex){return this.getBank_(addressHex).lookupEntry(this.getAddress_(addressHex));},addEntry_:function(addressHex,entry){this.getBank_(addressHex).addEntry(entry);},getAddress_:function(addressHex){var bankSizeHexDigits=13;addressHex=addressHex.slice(2);return parseInt(addressHex.slice(-bankSizeHexDigits),16);},getBank_:function(addressHex){addressHex=addressHex.slice(2);var bankSizeHexDigits=13;var maxHexDigits=16;var bankName=addressHex.slice(-maxHexDigits,-bankSizeHexDigits);var bank=this.banks_.get(bankName);if(!bank){bank=new TraceCodeBank();this.banks_.set(bankName,bank);}return bank;}};function TraceCodeBank(){this.entries_=[];}TraceCodeBank.prototype={removeEntry:function(address){if(this.entries_.length===0)return undefined;var index=tr.b.findLowIndexInSortedArray(this.entries_,function(entry){return entry.address;},address);var entry=this.entries_[index];if(!entry||entry.address!==address)return undefined;this.entries_.splice(index,1);return entry;},lookupEntry:function(address){var index=tr.b.findHighIndexInSortedArray(this.entries_,function(e){return address-e.address;})-1;var entry=this.entries_[index];return entry&&address<entry.address+entry.size?entry:undefined;},addEntry:function(newEntry){if(this.entries_.length===0)this.entries_.push(newEntry);var endAddress=newEntry.address+newEntry.size;var lastIndex=tr.b.findLowIndexInSortedArray(this.entries_,function(entry){return entry.address;},endAddress);var index;for(index=lastIndex-1;index>=0;--index){var entry=this.entries_[index];var entryEndAddress=entry.address+entry.size;if(entryEndAddress<=newEntry.address)break;}++index;this.entries_.splice(index,lastIndex-index,newEntry);}};return{TraceCodeMap:TraceCodeMap};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./trace_code_entry.js":70}],72:[function(require,module,exports){(function(global){"use strict";require("../../base/base64.js");require("../../base/color_scheme.js");require("../../base/range.js");require("../../base/unit.js");require("../../base/utils.js");require("./trace_code_entry.js");require("./trace_code_map.js");require("./v8/codemap.js");require("../../importer/context_processor.js");require("../../importer/importer.js");require("../../model/comment_box_annotation.js");require("../../model/constants.js");require("../../model/container_memory_dump.js");require("../../model/counter_series.js");require("../../model/flow_event.js");require("../../model/global_memory_dump.js");require("../../model/heap_dump.js");require("../../model/instant_event.js");require("../../model/memory_allocator_dump.js");require("../../model/model.js");require("../../model/process_memory_dump.js");require("../../model/rect_annotation.js");require("../../model/scoped_id.js");require("../../model/slice_group.js");require("../../model/vm_region.js");require("../../model/x_marker_annotation.js");require("../../value/numeric.js");'use strict';global.tr.exportTo('tr.e.importer',function(){var Base64=tr.b.Base64;var deepCopy=tr.b.deepCopy;var ColorScheme=tr.b.ColorScheme;function getEventColor(event,opt_customName){if(event.cname)return ColorScheme.getColorIdForReservedName(event.cname);else if(opt_customName||event.name){return ColorScheme.getColorIdForGeneralPurposeString(opt_customName||event.name);}}var PRODUCER='producer';var CONSUMER='consumer';var STEP='step';var BACKGROUND=tr.model.ContainerMemoryDump.LevelOfDetail.BACKGROUND;var LIGHT=tr.model.ContainerMemoryDump.LevelOfDetail.LIGHT;var DETAILED=tr.model.ContainerMemoryDump.LevelOfDetail.DETAILED;var MEMORY_DUMP_LEVEL_OF_DETAIL_ORDER=[undefined,BACKGROUND,LIGHT,DETAILED];var GLOBAL_MEMORY_ALLOCATOR_DUMP_PREFIX='global/';var ASYNC_CLOCK_SYNC_EVENT_TITLE_PREFIX='ClockSyncEvent.';var BYTE_STAT_NAME_MAP={'pc':'privateCleanResident','pd':'privateDirtyResident','sc':'sharedCleanResident','sd':'sharedDirtyResident','pss':'proportionalResident','sw':'swapped'};var WEAK_MEMORY_ALLOCATOR_DUMP_FLAG=1<<0;var OBJECT_TYPE_NAME_PATTERNS=[{prefix:'const char *WTF::getStringWithTypeName() [T = ',suffix:']'},{prefix:'const char* WTF::getStringWithTypeName() [with T = ',suffix:']'},{prefix:'const char *__cdecl WTF::getStringWithTypeName<',suffix:'>(void)'}];var SUBTRACE_FIELDS=new Set(['powerTraceAsString','systemTraceEvents']);var NON_METADATA_FIELDS=new Set(['samples','stackFrames','traceAnnotations','traceEvents']);for(var subtraceField in SUBTRACE_FIELDS)NON_METADATA_FIELDS.add(subtraceField);function TraceEventImporter(model,eventData){this.importPriority=1;this.model_=model;this.events_=undefined;this.sampleEvents_=undefined;this.stackFrameEvents_=undefined;this.subtraces_=[];this.eventsWereFromString_=false;this.softwareMeasuredCpuCount_=undefined;this.allAsyncEvents_=[];this.allFlowEvents_=[];this.allObjectEvents_=[];this.contextProcessorPerThread={};this.traceEventSampleStackFramesByName_={};this.v8ProcessCodeMaps_={};this.v8ProcessRootStackFrame_={};this.v8SamplingData_=[];this.asyncClockSyncStart_=undefined;this.asyncClockSyncFinish_=undefined;this.allMemoryDumpEvents_={};this.objectTypeNameMap_={};this.clockDomainId_=tr.model.ClockDomainId.UNKNOWN_CHROME_LEGACY;this.toModelTime_=undefined;if(typeof eventData==='string'||eventData instanceof String){eventData=eventData.trim();if(eventData[0]==='['){eventData=eventData.replace(/\s*,\s*$/,'');if(eventData[eventData.length-1]!==']')eventData=eventData+']';}this.events_=JSON.parse(eventData);this.eventsWereFromString_=true;}else{this.events_=eventData;}this.traceAnnotations_=this.events_.traceAnnotations;if(this.events_.traceEvents){var container=this.events_;this.events_=this.events_.traceEvents;for(var subtraceField of SUBTRACE_FIELDS)if(container[subtraceField])this.subtraces_.push(container[subtraceField]);this.sampleEvents_=container.samples;this.stackFrameEvents_=container.stackFrames;if(container.displayTimeUnit){var unitName=container.displayTimeUnit;var unit=tr.b.TimeDisplayModes[unitName];if(unit===undefined){throw new Error('Unit '+unitName+' is not supported.');}this.model_.intrinsicTimeUnit=unit;}for(var fieldName in container){if(NON_METADATA_FIELDS.has(fieldName))continue;this.model_.metadata.push({name:fieldName,value:container[fieldName]});if(fieldName==='metadata'){var metadata=container[fieldName];if(metadata['highres-ticks'])this.model_.isTimeHighResolution=metadata['highres-ticks'];if(metadata['clock-domain'])this.clockDomainId_=metadata['clock-domain'];}}}}TraceEventImporter.canImport=function(eventData){if(typeof eventData==='string'||eventData instanceof String){eventData=eventData.trim();return eventData[0]==='{'||eventData[0]==='[';}if(eventData instanceof Array&&eventData.length&&eventData[0].ph)return true;if(eventData.traceEvents){if(eventData.traceEvents instanceof Array){if(eventData.traceEvents.length&&eventData.traceEvents[0].ph)return true;if(eventData.samples.length&&eventData.stackFrames!==undefined)return true;}}return false;};TraceEventImporter.prototype={__proto__:tr.importer.Importer.prototype,get importerName(){return'TraceEventImporter';},extractSubtraces:function(){var subtraces=this.subtraces_;this.subtraces_=[];return subtraces;},deepCopyIfNeeded_:function(obj){if(obj===undefined)obj={};if(this.eventsWereFromString_)return obj;return deepCopy(obj);},deepCopyAlways_:function(obj){if(obj===undefined)obj={};return deepCopy(obj);},processAsyncEvent:function(event){var thread=this.model_.getOrCreateProcess(event.pid).getOrCreateThread(event.tid);this.allAsyncEvents_.push({sequenceNumber:this.allAsyncEvents_.length,event:event,thread:thread});},processFlowEvent:function(event,opt_slice){var thread=this.model_.getOrCreateProcess(event.pid).getOrCreateThread(event.tid);this.allFlowEvents_.push({refGuid:tr.b.GUID.getLastSimpleGuid(),sequenceNumber:this.allFlowEvents_.length,event:event,slice:opt_slice,thread:thread});},processCounterEvent:function(event){var ctrName;if(event.id!==undefined)ctrName=event.name+'['+event.id+']';else ctrName=event.name;var ctr=this.model_.getOrCreateProcess(event.pid).getOrCreateCounter(event.cat,ctrName);var reservedColorId=event.cname?getEventColor(event):undefined;if(ctr.numSeries===0){for(var seriesName in event.args){var colorId=reservedColorId||getEventColor(event,ctr.name+'.'+seriesName);ctr.addSeries(new tr.model.CounterSeries(seriesName,colorId));}if(ctr.numSeries===0){this.model_.importWarning({type:'counter_parse_error',message:'Expected counter '+event.name+' to have at least one argument to use as a value.'});delete ctr.parent.counters[ctr.name];return;}}var ts=this.toModelTimeFromUs_(event.ts);ctr.series.forEach(function(series){var val=event.args[series.name]?event.args[series.name]:0;series.addCounterSample(ts,val);});},scopedIdForEvent_:function(event){return new tr.model.ScopedId(event.scope||tr.model.OBJECT_DEFAULT_SCOPE,event.id);},processObjectEvent:function(event){var thread=this.model_.getOrCreateProcess(event.pid).getOrCreateThread(event.tid);this.allObjectEvents_.push({sequenceNumber:this.allObjectEvents_.length,event:event,thread:thread});if(thread.guid in this.contextProcessorPerThread){var processor=this.contextProcessorPerThread[thread.guid];var scopedId=this.scopedIdForEvent_(event);if(event.ph==='D')processor.destroyContext(scopedId);processor.invalidateContextCacheForSnapshot(scopedId);}},processContextEvent:function(event){var thread=this.model_.getOrCreateProcess(event.pid).getOrCreateThread(event.tid);if(!(thread.guid in this.contextProcessorPerThread)){this.contextProcessorPerThread[thread.guid]=new tr.importer.ContextProcessor(this.model_);}var scopedId=this.scopedIdForEvent_(event);var contextType=event.name;var processor=this.contextProcessorPerThread[thread.guid];if(event.ph==='('){processor.enterContext(contextType,scopedId);}else if(event.ph===')'){processor.leaveContext(contextType,scopedId);}else{this.model_.importWarning({type:'unknown_context_phase',message:'Unknown context event phase: '+event.ph+'.'});}},setContextsFromThread_:function(thread,slice){if(thread.guid in this.contextProcessorPerThread){slice.contexts=this.contextProcessorPerThread[thread.guid].activeContexts;}},processDurationEvent:function(event){var thread=this.model_.getOrCreateProcess(event.pid).getOrCreateThread(event.tid);var ts=this.toModelTimeFromUs_(event.ts);if(!thread.sliceGroup.isTimestampValidForBeginOrEnd(ts)){this.model_.importWarning({type:'duration_parse_error',message:'Timestamps are moving backward.'});return;}if(event.ph==='B'){var slice=thread.sliceGroup.beginSlice(event.cat,event.name,this.toModelTimeFromUs_(event.ts),this.deepCopyIfNeeded_(event.args),this.toModelTimeFromUs_(event.tts),event.argsStripped,getEventColor(event));slice.startStackFrame=this.getStackFrameForEvent_(event);this.setContextsFromThread_(thread,slice);}else if(event.ph==='I'||event.ph==='i'||event.ph==='R'){if(event.s!==undefined&&event.s!=='t')throw new Error('This should never happen');thread.sliceGroup.beginSlice(event.cat,event.name,this.toModelTimeFromUs_(event.ts),this.deepCopyIfNeeded_(event.args),this.toModelTimeFromUs_(event.tts),event.argsStripped,getEventColor(event));var slice=thread.sliceGroup.endSlice(this.toModelTimeFromUs_(event.ts),this.toModelTimeFromUs_(event.tts));slice.startStackFrame=this.getStackFrameForEvent_(event);slice.endStackFrame=undefined;}else{if(!thread.sliceGroup.openSliceCount){this.model_.importWarning({type:'duration_parse_error',message:'E phase event without a matching B phase event.'});return;}var slice=thread.sliceGroup.endSlice(this.toModelTimeFromUs_(event.ts),this.toModelTimeFromUs_(event.tts),getEventColor(event));if(event.name&&slice.title!=event.name){this.model_.importWarning({type:'title_match_error',message:'Titles do not match. Title is '+slice.title+' in openSlice, and is '+event.name+' in endSlice'});}slice.endStackFrame=this.getStackFrameForEvent_(event);this.mergeArgsInto_(slice.args,event.args,slice.title);}},mergeArgsInto_:function(dstArgs,srcArgs,eventName){for(var arg in srcArgs){if(dstArgs[arg]!==undefined){this.model_.importWarning({type:'arg_merge_error',message:'Different phases of '+eventName+' provided values for argument '+arg+'.'+' The last provided value will be used.'});}dstArgs[arg]=this.deepCopyIfNeeded_(srcArgs[arg]);}},processCompleteEvent:function(event){if(event.cat!==undefined&&event.cat.indexOf('trace_event_overhead')>-1)return undefined;var thread=this.model_.getOrCreateProcess(event.pid).getOrCreateThread(event.tid);if(event.flow_out){if(event.flow_in)event.flowPhase=STEP;else event.flowPhase=PRODUCER;}else if(event.flow_in){event.flowPhase=CONSUMER;}var slice=thread.sliceGroup.pushCompleteSlice(event.cat,event.name,this.toModelTimeFromUs_(event.ts),this.maybeToModelTimeFromUs_(event.dur),this.maybeToModelTimeFromUs_(event.tts),this.maybeToModelTimeFromUs_(event.tdur),this.deepCopyIfNeeded_(event.args),event.argsStripped,getEventColor(event),event.bind_id);slice.startStackFrame=this.getStackFrameForEvent_(event);slice.endStackFrame=this.getStackFrameForEvent_(event,true);this.setContextsFromThread_(thread,slice);return slice;},processJitCodeEvent:function(event){if(this.v8ProcessCodeMaps_[event.pid]===undefined)this.v8ProcessCodeMaps_[event.pid]=new tr.e.importer.TraceCodeMap();var map=this.v8ProcessCodeMaps_[event.pid];var data=event.args.data;if(event.name==='JitCodeMoved')map.moveEntry(data.code_start,data.new_code_start,data.code_len);else map.addEntry(data.code_start,data.code_len,data.name,data.script_id);},processMetadataEvent:function(event){if(event.name==='JitCodeAdded'||event.name==='JitCodeMoved'){this.v8SamplingData_.push(event);return;}if(event.argsStripped)return;if(event.name==='process_name'){var process=this.model_.getOrCreateProcess(event.pid);process.name=event.args.name;}else if(event.name==='process_labels'){var process=this.model_.getOrCreateProcess(event.pid);var labels=event.args.labels.split(',');for(var i=0;i<labels.length;i++)process.addLabelIfNeeded(labels[i]);}else if(event.name==='process_sort_index'){var process=this.model_.getOrCreateProcess(event.pid);process.sortIndex=event.args.sort_index;}else if(event.name==='thread_name'){var thread=this.model_.getOrCreateProcess(event.pid).getOrCreateThread(event.tid);thread.name=event.args.name;}else if(event.name==='thread_sort_index'){var thread=this.model_.getOrCreateProcess(event.pid).getOrCreateThread(event.tid);thread.sortIndex=event.args.sort_index;}else if(event.name==='num_cpus'){var n=event.args.number;if(this.softwareMeasuredCpuCount_!==undefined)n=Math.max(n,this.softwareMeasuredCpuCount_);this.softwareMeasuredCpuCount_=n;}else if(event.name==='stackFrames'){var stackFrames=event.args.stackFrames;if(stackFrames===undefined){this.model_.importWarning({type:'metadata_parse_error',message:'No stack frames found in a \''+event.name+'\' metadata event'});}else{this.importStackFrames_(stackFrames,'p'+event.pid+':');}}else if(event.name==='typeNames'){var objectTypeNameMap=event.args.typeNames;if(objectTypeNameMap===undefined){this.model_.importWarning({type:'metadata_parse_error',message:'No mapping from object type IDs to names found in a \''+event.name+'\' metadata event'});}else{this.importObjectTypeNameMap_(objectTypeNameMap,event.pid);}}else if(event.name==='TraceConfig'){this.model_.metadata.push({name:'TraceConfig',value:event.args.value});}else{this.model_.importWarning({type:'metadata_parse_error',message:'Unrecognized metadata name: '+event.name});}},processInstantEvent:function(event){if(event.name==='JitCodeAdded'||event.name==='JitCodeMoved'){this.v8SamplingData_.push(event);return;}if(event.s==='t'||event.s===undefined){this.processDurationEvent(event);return;}var constructor;switch(event.s){case'g':constructor=tr.model.GlobalInstantEvent;break;case'p':constructor=tr.model.ProcessInstantEvent;break;default:this.model_.importWarning({type:'instant_parse_error',message:'I phase event with unknown "s" field value.'});return;}var instantEvent=new constructor(event.cat,event.name,getEventColor(event),this.toModelTimeFromUs_(event.ts),this.deepCopyIfNeeded_(event.args));switch(instantEvent.type){case tr.model.InstantEventType.GLOBAL:this.model_.instantEvents.push(instantEvent);break;case tr.model.InstantEventType.PROCESS:var process=this.model_.getOrCreateProcess(event.pid);process.instantEvents.push(instantEvent);break;default:throw new Error('Unknown instant event type: '+event.s);}},processV8Sample:function(event){var data=event.args.data;if(data.vm_state==='js'&&!data.stack.length)return;var rootStackFrame=this.v8ProcessRootStackFrame_[event.pid];if(!rootStackFrame){rootStackFrame=new tr.model.StackFrame(undefined,'v8-root-stack-frame','v8-root-stack-frame',0);this.v8ProcessRootStackFrame_[event.pid]=rootStackFrame;}function findChildWithEntryID(stackFrame,entryID){return tr.b.findFirstInArray(stackFrame.children,function(child){return child.entryID===entryID;});}var model=this.model_;function addStackFrame(lastStackFrame,entry){var childFrame=findChildWithEntryID(lastStackFrame,entry.id);if(childFrame)return childFrame;var frame=new tr.model.StackFrame(lastStackFrame,tr.b.GUID.allocateSimple(),entry.name,ColorScheme.getColorIdForGeneralPurposeString(entry.name),entry.sourceInfo);frame.entryID=entry.id;model.addStackFrame(frame);return frame;}var lastStackFrame=rootStackFrame;if(data.stack.length>0&&this.v8ProcessCodeMaps_[event.pid]){var map=this.v8ProcessCodeMaps_[event.pid];data.stack.reverse();for(var i=0;i<data.stack.length;i++){var entry=map.lookupEntry(data.stack[i]);if(entry===undefined){entry={id:'unknown',name:'unknown',sourceInfo:undefined};}lastStackFrame=addStackFrame(lastStackFrame,entry);}}else{var entry={id:data.vm_state,name:data.vm_state,sourceInfo:undefined};lastStackFrame=addStackFrame(lastStackFrame,entry);}var thread=this.model_.getOrCreateProcess(event.pid).getOrCreateThread(event.tid);var sample=new tr.model.Sample(undefined,thread,'V8 Sample',this.toModelTimeFromUs_(event.ts),lastStackFrame,1,this.deepCopyIfNeeded_(event.args));this.model_.samples.push(sample);},processTraceSampleEvent:function(event){if(event.name==='V8Sample'){this.v8SamplingData_.push(event);return;}var stackFrame=this.getStackFrameForEvent_(event);if(stackFrame===undefined){stackFrame=this.traceEventSampleStackFramesByName_[event.name];}if(stackFrame===undefined){var id='te-'+tr.b.GUID.allocateSimple();stackFrame=new tr.model.StackFrame(undefined,id,event.name,ColorScheme.getColorIdForGeneralPurposeString(event.name));this.model_.addStackFrame(stackFrame);this.traceEventSampleStackFramesByName_[event.name]=stackFrame;}var thread=this.model_.getOrCreateProcess(event.pid).getOrCreateThread(event.tid);var sample=new tr.model.Sample(undefined,thread,'Trace Event Sample',this.toModelTimeFromUs_(event.ts),stackFrame,1,this.deepCopyIfNeeded_(event.args));this.setContextsFromThread_(thread,sample);this.model_.samples.push(sample);},processMemoryDumpEvent:function(event){if(event.ph!=='v')throw new Error('Invalid memory dump event phase "'+event.ph+'".');var dumpId=event.id;if(dumpId===undefined){this.model_.importWarning({type:'memory_dump_parse_error',message:'Memory dump event (phase \''+event.ph+'\') without a dump ID.'});return;}var pid=event.pid;if(pid===undefined){this.model_.importWarning({type:'memory_dump_parse_error',message:'Memory dump event (phase\''+event.ph+'\', dump ID \''+dumpId+'\') without a PID.'});return;}var allEvents=this.allMemoryDumpEvents_;var dumpIdEvents=allEvents[dumpId];if(dumpIdEvents===undefined)allEvents[dumpId]=dumpIdEvents={};var processEvents=dumpIdEvents[pid];if(processEvents===undefined)dumpIdEvents[pid]=processEvents=[];processEvents.push(event);},processClockSyncEvent:function(event){if(event.ph!=='c')throw new Error('Invalid clock sync event phase "'+event.ph+'".');var syncId=event.args.sync_id;if(syncId===undefined){this.model_.importWarning({type:'clock_sync_parse_error',message:'Clock sync at time '+event.ts+' without an ID.'});return;}if(event.args&&event.args.issue_ts!==undefined){this.model_.clockSyncManager.addClockSyncMarker(this.clockDomainId_,syncId,tr.b.Unit.timestampFromUs(event.args.issue_ts),tr.b.Unit.timestampFromUs(event.ts));}else{this.model_.clockSyncManager.addClockSyncMarker(this.clockDomainId_,syncId,tr.b.Unit.timestampFromUs(event.ts));}},processV8Events:function(){this.v8SamplingData_.sort(function(a,b){if(a.ts!==b.ts)return a.ts-b.ts;if(a.ph==='M'||a.ph==='I')return-1;else if(b.ph==='M'||b.ph==='I')return 1;return 0;});var length=this.v8SamplingData_.length;for(var i=0;i<length;++i){var event=this.v8SamplingData_[i];if(event.ph==='M'||event.ph==='I'){this.processJitCodeEvent(event);}else if(event.ph==='P'){this.processV8Sample(event);}}},initBackcompatClockSyncEventTracker_:function(event){if(event.name!==undefined&&event.name.startsWith(ASYNC_CLOCK_SYNC_EVENT_TITLE_PREFIX)&&event.ph==='S')this.asyncClockSyncStart_=event;if(event.name!==undefined&&event.name.startsWith(ASYNC_CLOCK_SYNC_EVENT_TITLE_PREFIX)&&event.ph==='F')this.asyncClockSyncFinish_=event;if(this.asyncClockSyncStart_==undefined||this.asyncClockSyncFinish_==undefined)return;var syncId=this.asyncClockSyncStart_.name.substring(ASYNC_CLOCK_SYNC_EVENT_TITLE_PREFIX.length);if(syncId!==this.asyncClockSyncFinish_.name.substring(ASYNC_CLOCK_SYNC_EVENT_TITLE_PREFIX.length)){throw new Error('Inconsistent clock sync id of async clock sync '+'events.');}var clockSyncEvent={ph:'c',args:{sync_id:syncId,issue_ts:this.asyncClockSyncStart_.ts},ts:this.asyncClockSyncFinish_.ts};this.asyncClockSyncStart_=undefined;this.asyncClockSyncFinish_=undefined;return clockSyncEvent;},importClockSyncMarkers:function(){var asyncClockSyncStart,asyncClockSyncFinish;for(var i=0;i<this.events_.length;i++){var event=this.events_[i];var possibleBackCompatClockSyncEvent=this.initBackcompatClockSyncEventTracker_(event);if(possibleBackCompatClockSyncEvent)this.processClockSyncEvent(possibleBackCompatClockSyncEvent);if(event.ph!=='c')continue;var eventSizeInBytes=this.model_.importOptions.trackDetailedModelStats?JSON.stringify(event).length:undefined;this.model_.stats.willProcessBasicTraceEvent('clock_sync',event.cat,event.name,event.ts,eventSizeInBytes);this.processClockSyncEvent(event);}},importEvents:function(){if(this.stackFrameEvents_)this.importStackFrames_(this.stackFrameEvents_,'g');if(this.traceAnnotations_)this.importAnnotations_();var importOptions=this.model_.importOptions;var trackDetailedModelStats=importOptions.trackDetailedModelStats;var modelStats=this.model_.stats;var events=this.events_;for(var eI=0;eI<events.length;eI++){var event=events[eI];if(event.args==='__stripped__'){event.argsStripped=true;event.args=undefined;}var eventSizeInBytes;if(trackDetailedModelStats)eventSizeInBytes=JSON.stringify(event).length;else eventSizeInBytes=undefined;if(event.ph==='B'||event.ph==='E'){modelStats.willProcessBasicTraceEvent('begin_end (non-compact)',event.cat,event.name,event.ts,eventSizeInBytes);this.processDurationEvent(event);}else if(event.ph==='X'){modelStats.willProcessBasicTraceEvent('begin_end (compact)',event.cat,event.name,event.ts,eventSizeInBytes);var slice=this.processCompleteEvent(event);if(slice!==undefined&&event.bind_id!==undefined)this.processFlowEvent(event,slice);}else if(event.ph==='b'||event.ph==='e'||event.ph==='n'||event.ph==='S'||event.ph==='F'||event.ph==='T'||event.ph==='p'){modelStats.willProcessBasicTraceEvent('async',event.cat,event.name,event.ts,eventSizeInBytes);this.processAsyncEvent(event);}else if(event.ph==='I'||event.ph==='i'||event.ph==='R'){modelStats.willProcessBasicTraceEvent('instant',event.cat,event.name,event.ts,eventSizeInBytes);this.processInstantEvent(event);}else if(event.ph==='P'){modelStats.willProcessBasicTraceEvent('samples',event.cat,event.name,event.ts,eventSizeInBytes);this.processTraceSampleEvent(event);}else if(event.ph==='C'){modelStats.willProcessBasicTraceEvent('counters',event.cat,event.name,event.ts,eventSizeInBytes);this.processCounterEvent(event);}else if(event.ph==='M'){modelStats.willProcessBasicTraceEvent('metadata',event.cat,event.name,event.ts,eventSizeInBytes);this.processMetadataEvent(event);}else if(event.ph==='N'||event.ph==='D'||event.ph==='O'){modelStats.willProcessBasicTraceEvent('objects',event.cat,event.name,event.ts,eventSizeInBytes);this.processObjectEvent(event);}else if(event.ph==='s'||event.ph==='t'||event.ph==='f'){modelStats.willProcessBasicTraceEvent('flows',event.cat,event.name,event.ts,eventSizeInBytes);this.processFlowEvent(event);}else if(event.ph==='v'){modelStats.willProcessBasicTraceEvent('memory_dumps',event.cat,event.name,event.ts,eventSizeInBytes);this.processMemoryDumpEvent(event);}else if(event.ph==='('||event.ph===')'){this.processContextEvent(event);}else if(event.ph==='c'){}else{modelStats.willProcessBasicTraceEvent('unknown',event.cat,event.name,event.ts,eventSizeInBytes);this.model_.importWarning({type:'parse_error',message:'Unrecognized event phase: '+event.ph+' ('+event.name+')'});}}this.processV8Events();tr.b.iterItems(this.v8ProcessRootStackFrame_,function(name,frame){frame.removeAllChildren();});},importStackFrames_:function(rawStackFrames,idPrefix){var model=this.model_;for(var id in rawStackFrames){var rawStackFrame=rawStackFrames[id];var fullId=idPrefix+id;var textForColor=rawStackFrame.category?rawStackFrame.category:rawStackFrame.name;var stackFrame=new tr.model.StackFrame(undefined,fullId,rawStackFrame.name,ColorScheme.getColorIdForGeneralPurposeString(textForColor));model.addStackFrame(stackFrame);}for(var id in rawStackFrames){var fullId=idPrefix+id;var stackFrame=model.stackFrames[fullId];if(stackFrame===undefined)throw new Error('Internal error');var rawStackFrame=rawStackFrames[id];var parentId=rawStackFrame.parent;var parentStackFrame;if(parentId===undefined){parentStackFrame=undefined;}else{var parentFullId=idPrefix+parentId;parentStackFrame=model.stackFrames[parentFullId];if(parentStackFrame===undefined){this.model_.importWarning({type:'metadata_parse_error',message:'Missing parent frame with ID '+parentFullId+' for stack frame \''+stackFrame.name+'\' (ID '+fullId+').'});}}stackFrame.parentFrame=parentStackFrame;}},importObjectTypeNameMap_:function(rawObjectTypeNameMap,pid){if(pid in this.objectTypeNameMap_){this.model_.importWarning({type:'metadata_parse_error',message:'Mapping from object type IDs to names provided for pid='+pid+' multiple times.'});return;}var objectTypeNamePrefix=undefined;var objectTypeNameSuffix=undefined;var objectTypeNameMap={};for(var objectTypeId in rawObjectTypeNameMap){var rawObjectTypeName=rawObjectTypeNameMap[objectTypeId];if(objectTypeNamePrefix===undefined){for(var i=0;i<OBJECT_TYPE_NAME_PATTERNS.length;i++){var pattern=OBJECT_TYPE_NAME_PATTERNS[i];if(rawObjectTypeName.startsWith(pattern.prefix)&&rawObjectTypeName.endsWith(pattern.suffix)){objectTypeNamePrefix=pattern.prefix;objectTypeNameSuffix=pattern.suffix;break;}}}if(objectTypeNamePrefix!==undefined&&rawObjectTypeName.startsWith(objectTypeNamePrefix)&&rawObjectTypeName.endsWith(objectTypeNameSuffix)){objectTypeNameMap[objectTypeId]=rawObjectTypeName.substring(objectTypeNamePrefix.length,rawObjectTypeName.length-objectTypeNameSuffix.length);}else{objectTypeNameMap[objectTypeId]=rawObjectTypeName;}}this.objectTypeNameMap_[pid]=objectTypeNameMap;},importAnnotations_:function(){for(var id in this.traceAnnotations_){var annotation=tr.model.Annotation.fromDictIfPossible(this.traceAnnotations_[id]);if(!annotation){this.model_.importWarning({type:'annotation_warning',message:'Unrecognized traceAnnotation typeName \"'+this.traceAnnotations_[id].typeName+'\"'});continue;}this.model_.addAnnotation(annotation);}},finalizeImport:function(){if(this.softwareMeasuredCpuCount_!==undefined){this.model_.kernel.softwareMeasuredCpuCount=this.softwareMeasuredCpuCount_;}this.createAsyncSlices_();this.createFlowSlices_();this.createExplicitObjects_();this.createImplicitObjects_();this.createMemoryDumps_();},getStackFrameForEvent_:function(event,opt_lookForEndEvent){var sf;var stack;if(opt_lookForEndEvent){sf=event.esf;stack=event.estack;}else{sf=event.sf;stack=event.stack;}if(stack!==undefined&&sf!==undefined){this.model_.importWarning({type:'stack_frame_and_stack_error',message:'Event at '+event.ts+' cannot have both a stack and a stackframe.'});return undefined;}if(stack!==undefined)return this.model_.resolveStackToStackFrame_(event.pid,stack);if(sf===undefined)return undefined;var stackFrame=this.model_.stackFrames['g'+sf];if(stackFrame===undefined){this.model_.importWarning({type:'sample_import_error',message:'No frame for '+sf});return;}return stackFrame;},resolveStackToStackFrame_:function(pid,stack){return undefined;},importSampleData:function(){if(!this.sampleEvents_)return;var m=this.model_;var events=this.sampleEvents_;if(this.events_.length===0){for(var i=0;i<events.length;i++){var event=events[i];m.getOrCreateProcess(event.tid).getOrCreateThread(event.tid);}}var threadsByTid={};m.getAllThreads().forEach(function(t){threadsByTid[t.tid]=t;});for(var i=0;i<events.length;i++){var event=events[i];var thread=threadsByTid[event.tid];if(thread===undefined){m.importWarning({type:'sample_import_error',message:'Thread '+events.tid+'not found'});continue;}var cpu;if(event.cpu!==undefined)cpu=m.kernel.getOrCreateCpu(event.cpu);var stackFrame=this.getStackFrameForEvent_(event);var sample=new tr.model.Sample(cpu,thread,event.name,this.toModelTimeFromUs_(event.ts),stackFrame,event.weight);m.samples.push(sample);}},createAsyncSlices_:function(){if(this.allAsyncEvents_.length===0)return;this.allAsyncEvents_.sort(function(x,y){var d=x.event.ts-y.event.ts;if(d!==0)return d;return x.sequenceNumber-y.sequenceNumber;});var legacyEvents=[];var nestableAsyncEventsByKey={};var nestableMeasureAsyncEventsByKey={};for(var i=0;i<this.allAsyncEvents_.length;i++){var asyncEventState=this.allAsyncEvents_[i];var event=asyncEventState.event;if(event.ph==='S'||event.ph==='F'||event.ph==='T'||event.ph==='p'){legacyEvents.push(asyncEventState);continue;}if(event.cat===undefined){this.model_.importWarning({type:'async_slice_parse_error',message:'Nestable async events (ph: b, e, or n) require a '+'cat parameter.'});continue;}if(event.name===undefined){this.model_.importWarning({type:'async_slice_parse_error',message:'Nestable async events (ph: b, e, or n) require a '+'name parameter.'});continue;}if(event.id===undefined){this.model_.importWarning({type:'async_slice_parse_error',message:'Nestable async events (ph: b, e, or n) require an '+'id parameter.'});continue;}if(event.cat==='blink.user_timing'){var matched=/([^\/:]+):([^\/:]+)\/?(.*)/.exec(event.name);if(matched!==null){var key=matched[1]+':'+event.cat;event.args=JSON.parse(Base64.atob(matched[3])||'{}');if(nestableMeasureAsyncEventsByKey[key]===undefined)nestableMeasureAsyncEventsByKey[key]=[];nestableMeasureAsyncEventsByKey[key].push(asyncEventState);continue;}}var key=event.cat+':'+event.id;if(nestableAsyncEventsByKey[key]===undefined)nestableAsyncEventsByKey[key]=[];nestableAsyncEventsByKey[key].push(asyncEventState);}this.createLegacyAsyncSlices_(legacyEvents);this.createNestableAsyncSlices_(nestableMeasureAsyncEventsByKey);this.createNestableAsyncSlices_(nestableAsyncEventsByKey);},createLegacyAsyncSlices_:function(legacyEvents){if(legacyEvents.length===0)return;legacyEvents.sort(function(x,y){var d=x.event.ts-y.event.ts;if(d!=0)return d;return x.sequenceNumber-y.sequenceNumber;});var asyncEventStatesByNameThenID={};for(var i=0;i<legacyEvents.length;i++){var asyncEventState=legacyEvents[i];var event=asyncEventState.event;var name=event.name;if(name===undefined){this.model_.importWarning({type:'async_slice_parse_error',message:'Async events (ph: S, T, p, or F) require a name '+' parameter.'});continue;}var id=event.id;if(id===undefined){this.model_.importWarning({type:'async_slice_parse_error',message:'Async events (ph: S, T, p, or F) require an id parameter.'});continue;}if(event.ph==='S'){if(asyncEventStatesByNameThenID[name]===undefined)asyncEventStatesByNameThenID[name]={};if(asyncEventStatesByNameThenID[name][id]){this.model_.importWarning({type:'async_slice_parse_error',message:'At '+event.ts+', a slice of the same id '+id+' was alrady open.'});continue;}asyncEventStatesByNameThenID[name][id]=[];asyncEventStatesByNameThenID[name][id].push(asyncEventState);}else{if(asyncEventStatesByNameThenID[name]===undefined){this.model_.importWarning({type:'async_slice_parse_error',message:'At '+event.ts+', no slice named '+name+' was open.'});continue;}if(asyncEventStatesByNameThenID[name][id]===undefined){this.model_.importWarning({type:'async_slice_parse_error',message:'At '+event.ts+', no slice named '+name+' with id='+id+' was open.'});continue;}var events=asyncEventStatesByNameThenID[name][id];events.push(asyncEventState);if(event.ph==='F'){var asyncSliceConstructor=tr.model.AsyncSlice.subTypes.getConstructor(events[0].event.cat,name);var slice=new asyncSliceConstructor(events[0].event.cat,name,getEventColor(events[0].event),this.toModelTimeFromUs_(events[0].event.ts),tr.b.concatenateObjects(events[0].event.args,events[events.length-1].event.args),this.toModelTimeFromUs_(event.ts-events[0].event.ts),true,undefined,undefined,events[0].event.argsStripped);slice.startThread=events[0].thread;slice.endThread=asyncEventState.thread;slice.id=id;var stepType=events[1].event.ph;var isValid=true;for(var j=1;j<events.length-1;++j){if(events[j].event.ph==='T'||events[j].event.ph==='p'){isValid=this.assertStepTypeMatches_(stepType,events[j]);if(!isValid)break;}if(events[j].event.ph==='S'){this.model_.importWarning({type:'async_slice_parse_error',message:'At '+event.event.ts+', a slice named '+event.event.name+' with id='+event.event.id+' had a step before the start event.'});continue;}if(events[j].event.ph==='F'){this.model_.importWarning({type:'async_slice_parse_error',message:'At '+event.event.ts+', a slice named '+event.event.name+' with id='+event.event.id+' had a step after the finish event.'});continue;}var startIndex=j+(stepType==='T'?0:-1);var endIndex=startIndex+1;var subName=events[j].event.name;if(!events[j].event.argsStripped&&(events[j].event.ph==='T'||events[j].event.ph==='p'))subName=subName+':'+events[j].event.args.step;var asyncSliceConstructor=tr.model.AsyncSlice.subTypes.getConstructor(events[0].event.cat,subName);var subSlice=new asyncSliceConstructor(events[0].event.cat,subName,getEventColor(event,subName+j),this.toModelTimeFromUs_(events[startIndex].event.ts),this.deepCopyIfNeeded_(events[j].event.args),this.toModelTimeFromUs_(events[endIndex].event.ts-events[startIndex].event.ts),undefined,undefined,events[startIndex].event.argsStripped);subSlice.startThread=events[startIndex].thread;subSlice.endThread=events[endIndex].thread;subSlice.id=id;slice.subSlices.push(subSlice);}if(isValid){slice.startThread.asyncSliceGroup.push(slice);}delete asyncEventStatesByNameThenID[name][id];}}}},createNestableAsyncSlices_:function(nestableEventsByKey){for(var key in nestableEventsByKey){var eventStateEntries=nestableEventsByKey[key];var parentStack=[];for(var i=0;i<eventStateEntries.length;++i){var eventStateEntry=eventStateEntries[i];if(eventStateEntry.event.ph==='e'){var parentIndex=-1;for(var k=parentStack.length-1;k>=0;--k){if(parentStack[k].event.name===eventStateEntry.event.name){parentIndex=k;break;}}if(parentIndex===-1){eventStateEntry.finished=false;}else{parentStack[parentIndex].end=eventStateEntry;while(parentIndex<parentStack.length){parentStack.pop();}}}if(parentStack.length>0)eventStateEntry.parentEntry=parentStack[parentStack.length-1];if(eventStateEntry.event.ph==='b'){parentStack.push(eventStateEntry);}}var topLevelSlices=[];for(var i=0;i<eventStateEntries.length;++i){var eventStateEntry=eventStateEntries[i];if(eventStateEntry.event.ph==='e'&&eventStateEntry.finished===undefined){continue;}var startState=undefined;var endState=undefined;var sliceArgs=eventStateEntry.event.args||{};var sliceError=undefined;if(eventStateEntry.event.ph==='n'){startState=eventStateEntry;endState=eventStateEntry;}else if(eventStateEntry.event.ph==='b'){if(eventStateEntry.end===undefined){eventStateEntry.end=eventStateEntries[eventStateEntries.length-1];sliceError='Slice has no matching END. End time has been adjusted.';this.model_.importWarning({type:'async_slice_parse_error',message:'Nestable async BEGIN event at '+eventStateEntry.event.ts+' with name='+eventStateEntry.event.name+' and id='+eventStateEntry.event.id+' was unmatched.'});}else{function concatenateArguments(args1,args2){if(args1.params===undefined||args2.params===undefined)return tr.b.concatenateObjects(args1,args2);var args3={};args3.params=tr.b.concatenateObjects(args1.params,args2.params);return tr.b.concatenateObjects(args1,args2,args3);}var endArgs=eventStateEntry.end.event.args||{};sliceArgs=concatenateArguments(sliceArgs,endArgs);}startState=eventStateEntry;endState=eventStateEntry.end;}else{sliceError='Slice has no matching BEGIN. Start time has been adjusted.';this.model_.importWarning({type:'async_slice_parse_error',message:'Nestable async END event at '+eventStateEntry.event.ts+' with name='+eventStateEntry.event.name+' and id='+eventStateEntry.event.id+' was unmatched.'});startState=eventStateEntries[0];endState=eventStateEntry;}var isTopLevel=eventStateEntry.parentEntry===undefined;var asyncSliceConstructor=tr.model.AsyncSlice.subTypes.getConstructor(eventStateEntry.event.cat,eventStateEntry.event.name);var threadStart=undefined;var threadDuration=undefined;if(startState.event.tts&&startState.event.use_async_tts){threadStart=this.toModelTimeFromUs_(startState.event.tts);if(endState.event.tts){var threadEnd=this.toModelTimeFromUs_(endState.event.tts);threadDuration=threadEnd-threadStart;}}var slice=new asyncSliceConstructor(eventStateEntry.event.cat,eventStateEntry.event.name,getEventColor(endState.event),this.toModelTimeFromUs_(startState.event.ts),sliceArgs,this.toModelTimeFromUs_(endState.event.ts-startState.event.ts),isTopLevel,threadStart,threadDuration,startState.event.argsStripped);slice.startThread=startState.thread;slice.endThread=endState.thread;slice.startStackFrame=this.getStackFrameForEvent_(startState.event);slice.endStackFrame=this.getStackFrameForEvent_(endState.event);slice.id=key;if(sliceError!==undefined)slice.error=sliceError;eventStateEntry.slice=slice;if(isTopLevel){topLevelSlices.push(slice);}else if(eventStateEntry.parentEntry.slice!==undefined){eventStateEntry.parentEntry.slice.subSlices.push(slice);}}for(var si=0;si<topLevelSlices.length;si++){topLevelSlices[si].startThread.asyncSliceGroup.push(topLevelSlices[si]);}}},assertStepTypeMatches_:function(stepType,event){if(stepType!=event.event.ph){this.model_.importWarning({type:'async_slice_parse_error',message:'At '+event.event.ts+', a slice named '+event.event.name+' with id='+event.event.id+' had both begin and end steps, which is not allowed.'});return false;}return true;},createFlowSlices_:function(){if(this.allFlowEvents_.length===0)return;var that=this;function validateFlowEvent(){if(event.name===undefined){that.model_.importWarning({type:'flow_slice_parse_error',message:'Flow events (ph: s, t or f) require a name parameter.'});return false;}if(event.ph==='s'||event.ph==='f'||event.ph==='t'){if(event.id===undefined){that.model_.importWarning({type:'flow_slice_parse_error',message:'Flow events (ph: s, t or f) require an id parameter.'});return false;}return true;}if(event.bind_id){if(event.flow_in===undefined&&event.flow_out===undefined){that.model_.importWarning({type:'flow_slice_parse_error',message:'Flow producer or consumer require flow_in or flow_out.'});return false;}return true;}return false;}var createFlowEvent=function(thread,event,opt_slice){var startSlice,flowId,flowStartTs;if(event.bind_id){startSlice=opt_slice;flowId=event.bind_id;flowStartTs=this.toModelTimeFromUs_(event.ts+event.dur);}else{var ts=this.toModelTimeFromUs_(event.ts);startSlice=thread.sliceGroup.findSliceAtTs(ts);if(startSlice===undefined)return undefined;flowId=event.id;flowStartTs=ts;}var flowEvent=new tr.model.FlowEvent(event.cat,flowId,event.name,getEventColor(event),flowStartTs,that.deepCopyAlways_(event.args));flowEvent.startSlice=startSlice;flowEvent.startStackFrame=that.getStackFrameForEvent_(event);flowEvent.endStackFrame=undefined;startSlice.outFlowEvents.push(flowEvent);return flowEvent;}.bind(this);var finishFlowEventWith=function(flowEvent,thread,event,refGuid,bindToParent,opt_slice){var endSlice;if(event.bind_id){endSlice=opt_slice;}else{var ts=this.toModelTimeFromUs_(event.ts);if(bindToParent){endSlice=thread.sliceGroup.findSliceAtTs(ts);}else{endSlice=thread.sliceGroup.findNextSliceAfter(ts,refGuid);}if(endSlice===undefined)return false;}endSlice.inFlowEvents.push(flowEvent);flowEvent.endSlice=endSlice;flowEvent.duration=this.toModelTimeFromUs_(event.ts)-flowEvent.start;flowEvent.endStackFrame=that.getStackFrameForEvent_(event);that.mergeArgsInto_(flowEvent.args,event.args,flowEvent.title);return true;}.bind(this);function processFlowConsumer(flowIdToEvent,sliceGuidToEvent,event,slice){var flowEvent=flowIdToEvent[event.bind_id];if(flowEvent===undefined){that.model_.importWarning({type:'flow_slice_ordering_error',message:'Flow consumer '+event.bind_id+' does not have '+'a flow producer'});return false;}else if(flowEvent.endSlice){var flowProducer=flowEvent.startSlice;flowEvent=createFlowEvent(undefined,sliceGuidToEvent[flowProducer.guid],flowProducer);}var ok=finishFlowEventWith(flowEvent,undefined,event,refGuid,undefined,slice);if(ok){that.model_.flowEvents.push(flowEvent);}else{that.model_.importWarning({type:'flow_slice_end_error',message:'Flow consumer '+event.bind_id+' does not end '+'at an actual slice, so cannot be created.'});return false;}return true;}function processFlowProducer(flowIdToEvent,flowStatus,event,slice){if(flowIdToEvent[event.bind_id]&&flowStatus[event.bind_id]){that.model_.importWarning({type:'flow_slice_start_error',message:'Flow producer '+event.bind_id+' already seen'});return false;}var flowEvent=createFlowEvent(undefined,event,slice);if(!flowEvent){that.model_.importWarning({type:'flow_slice_start_error',message:'Flow producer '+event.bind_id+' does not start'+'a flow'});return false;}flowIdToEvent[event.bind_id]=flowEvent;}this.allFlowEvents_.sort(function(x,y){var d=x.event.ts-y.event.ts;if(d!=0)return d;return x.sequenceNumber-y.sequenceNumber;});var flowIdToEvent={};var sliceGuidToEvent={};var flowStatus={};for(var i=0;i<this.allFlowEvents_.length;++i){var data=this.allFlowEvents_[i];var refGuid=data.refGuid;var event=data.event;var thread=data.thread;if(!validateFlowEvent(event))continue;if(event.bind_id){var slice=data.slice;sliceGuidToEvent[slice.guid]=event;if(event.flowPhase===PRODUCER){if(!processFlowProducer(flowIdToEvent,flowStatus,event,slice))continue;flowStatus[event.bind_id]=true;}else{if(!processFlowConsumer(flowIdToEvent,sliceGuidToEvent,event,slice))continue;flowStatus[event.bind_id]=false;if(event.flowPhase===STEP){if(!processFlowProducer(flowIdToEvent,flowStatus,event,slice))continue;flowStatus[event.bind_id]=true;}}continue;}var flowEvent;if(event.ph==='s'){if(flowIdToEvent[event.id]){this.model_.importWarning({type:'flow_slice_start_error',message:'event id '+event.id+' already seen when '+'encountering start of flow event.'});continue;}flowEvent=createFlowEvent(thread,event);if(!flowEvent){this.model_.importWarning({type:'flow_slice_start_error',message:'event id '+event.id+' does not start '+'at an actual slice, so cannot be created.'});continue;}flowIdToEvent[event.id]=flowEvent;}else if(event.ph==='t'||event.ph==='f'){flowEvent=flowIdToEvent[event.id];if(flowEvent===undefined){this.model_.importWarning({type:'flow_slice_ordering_error',message:'Found flow phase '+event.ph+' for id: '+event.id+' but no flow start found.'});continue;}var bindToParent=event.ph==='t';if(event.ph==='f'){if(event.bp===undefined){if(event.cat.indexOf('input')>-1)bindToParent=true;else if(event.cat.indexOf('ipc.flow')>-1)bindToParent=true;}else{if(event.bp!=='e'){this.model_.importWarning({type:'flow_slice_bind_point_error',message:'Flow event with invalid binding point (event.bp).'});continue;}bindToParent=true;}}var ok=finishFlowEventWith(flowEvent,thread,event,refGuid,bindToParent);if(ok){that.model_.flowEvents.push(flowEvent);}else{this.model_.importWarning({type:'flow_slice_end_error',message:'event id '+event.id+' does not end '+'at an actual slice, so cannot be created.'});}flowIdToEvent[event.id]=undefined;if(ok&&event.ph==='t'){flowEvent=createFlowEvent(thread,event);flowIdToEvent[event.id]=flowEvent;}}}},createExplicitObjects_:function(){if(this.allObjectEvents_.length===0)return;var processEvent=function(objectEventState){var event=objectEventState.event;var scopedId=this.scopedIdForEvent_(event);var thread=objectEventState.thread;if(event.name===undefined){this.model_.importWarning({type:'object_parse_error',message:'While processing '+JSON.stringify(event)+': '+'Object events require an name parameter.'});}if(scopedId.id===undefined){this.model_.importWarning({type:'object_parse_error',message:'While processing '+JSON.stringify(event)+': '+'Object events require an id parameter.'});}var process=thread.parent;var ts=this.toModelTimeFromUs_(event.ts);var instance;if(event.ph==='N'){try{instance=process.objects.idWasCreated(scopedId,event.cat,event.name,ts);}catch(e){this.model_.importWarning({type:'object_parse_error',message:'While processing create of '+scopedId+' at ts='+ts+': '+e});return;}}else if(event.ph==='O'){if(event.args.snapshot===undefined){this.model_.importWarning({type:'object_parse_error',message:'While processing '+scopedId+' at ts='+ts+': '+'Snapshots must have args: {snapshot: ...}'});return;}var snapshot;try{var args=this.deepCopyIfNeeded_(event.args.snapshot);var cat;if(args.cat){cat=args.cat;delete args.cat;}else{cat=event.cat;}var baseTypename;if(args.base_type){baseTypename=args.base_type;delete args.base_type;}else{baseTypename=undefined;}snapshot=process.objects.addSnapshot(scopedId,cat,event.name,ts,args,baseTypename);snapshot.snapshottedOnThread=thread;}catch(e){this.model_.importWarning({type:'object_parse_error',message:'While processing snapshot of '+scopedId+' at ts='+ts+': '+e});return;}instance=snapshot.objectInstance;}else if(event.ph==='D'){try{process.objects.idWasDeleted(scopedId,event.cat,event.name,ts);var instanceMap=process.objects.getOrCreateInstanceMap_(scopedId);instance=instanceMap.lastInstance;}catch(e){this.model_.importWarning({type:'object_parse_error',message:'While processing delete of '+scopedId+' at ts='+ts+': '+e});return;}}if(instance)instance.colorId=getEventColor(event,instance.typeName);}.bind(this);this.allObjectEvents_.sort(function(x,y){var d=x.event.ts-y.event.ts;if(d!=0)return d;return x.sequenceNumber-y.sequenceNumber;});var allObjectEvents=this.allObjectEvents_;for(var i=0;i<allObjectEvents.length;i++){var objectEventState=allObjectEvents[i];try{processEvent.call(this,objectEventState);}catch(e){this.model_.importWarning({type:'object_parse_error',message:e.message});}}},createImplicitObjects_:function(){tr.b.iterItems(this.model_.processes,function(pid,process){this.createImplicitObjectsForProcess_(process);},this);},createImplicitObjectsForProcess_:function(process){function processField(referencingObject,referencingObjectFieldName,referencingObjectFieldValue,containingSnapshot){if(!referencingObjectFieldValue)return;if(referencingObjectFieldValue instanceof tr.model.ObjectSnapshot)return null;if(referencingObjectFieldValue.id===undefined)return;var implicitSnapshot=referencingObjectFieldValue;var rawId=implicitSnapshot.id;var m=/(.+)\/(.+)/.exec(rawId);if(!m)throw new Error('Implicit snapshots must have names.');delete implicitSnapshot.id;var name=m[1];var id=m[2];var res;var cat;if(implicitSnapshot.cat!==undefined)cat=implicitSnapshot.cat;else cat=containingSnapshot.objectInstance.category;var baseTypename;if(implicitSnapshot.base_type)baseTypename=implicitSnapshot.base_type;else baseTypename=undefined;var scope=containingSnapshot.objectInstance.scopedId.scope;try{res=process.objects.addSnapshot(new tr.model.ScopedId(scope,id),cat,name,containingSnapshot.ts,implicitSnapshot,baseTypename);}catch(e){this.model_.importWarning({type:'object_snapshot_parse_error',message:'While processing implicit snapshot of '+rawId+' at ts='+containingSnapshot.ts+': '+e});return;}res.objectInstance.hasImplicitSnapshots=true;res.containingSnapshot=containingSnapshot;res.snapshottedOnThread=containingSnapshot.snapshottedOnThread;referencingObject[referencingObjectFieldName]=res;if(!(res instanceof tr.model.ObjectSnapshot))throw new Error('Created object must be instanceof snapshot');return res.args;}function iterObject(object,func,containingSnapshot,thisArg){if(!(object instanceof Object))return;if(object instanceof Array){for(var i=0;i<object.length;i++){var res=func.call(thisArg,object,i,object[i],containingSnapshot);if(res===null)continue;if(res)iterObject(res,func,containingSnapshot,thisArg);else iterObject(object[i],func,containingSnapshot,thisArg);}return;}for(var key in object){var res=func.call(thisArg,object,key,object[key],containingSnapshot);if(res===null)continue;if(res)iterObject(res,func,containingSnapshot,thisArg);else iterObject(object[key],func,containingSnapshot,thisArg);}}process.objects.iterObjectInstances(function(instance){instance.snapshots.forEach(function(snapshot){if(snapshot.args.id!==undefined)throw new Error('args cannot have an id field inside it');iterObject(snapshot.args,processField,snapshot,this);},this);},this);},createMemoryDumps_:function(){for(var dumpId in this.allMemoryDumpEvents_)this.createGlobalMemoryDump_(this.allMemoryDumpEvents_[dumpId],dumpId);},createGlobalMemoryDump_:function(dumpIdEvents,dumpId){var globalRange=new tr.b.Range();for(var pid in dumpIdEvents){var processEvents=dumpIdEvents[pid];for(var i=0;i<processEvents.length;i++)globalRange.addValue(this.toModelTimeFromUs_(processEvents[i].ts));}if(globalRange.isEmpty)throw new Error('Internal error: Global memory dump without events');var globalMemoryDump=new tr.model.GlobalMemoryDump(this.model_,globalRange.min);globalMemoryDump.duration=globalRange.range;this.model_.globalMemoryDumps.push(globalMemoryDump);var globalMemoryAllocatorDumpsByFullName={};var levelsOfDetail={};var allMemoryAllocatorDumpsByGuid={};for(var pid in dumpIdEvents){this.createProcessMemoryDump_(globalMemoryDump,globalMemoryAllocatorDumpsByFullName,levelsOfDetail,allMemoryAllocatorDumpsByGuid,dumpIdEvents[pid],pid,dumpId);}globalMemoryDump.levelOfDetail=levelsOfDetail.global;globalMemoryDump.memoryAllocatorDumps=this.inferMemoryAllocatorDumpTree_(globalMemoryAllocatorDumpsByFullName);this.parseMemoryDumpAllocatorEdges_(allMemoryAllocatorDumpsByGuid,dumpIdEvents,dumpId);},createProcessMemoryDump_:function(globalMemoryDump,globalMemoryAllocatorDumpsByFullName,levelsOfDetail,allMemoryAllocatorDumpsByGuid,processEvents,pid,dumpId){var processRange=new tr.b.Range();for(var i=0;i<processEvents.length;i++)processRange.addValue(this.toModelTimeFromUs_(processEvents[i].ts));if(processRange.isEmpty)throw new Error('Internal error: Process memory dump without events');var process=this.model_.getOrCreateProcess(pid);var processMemoryDump=new tr.model.ProcessMemoryDump(globalMemoryDump,process,processRange.min);processMemoryDump.duration=processRange.range;process.memoryDumps.push(processMemoryDump);globalMemoryDump.processMemoryDumps[pid]=processMemoryDump;var processMemoryAllocatorDumpsByFullName={};for(var i=0;i<processEvents.length;i++){var processEvent=processEvents[i];var dumps=processEvent.args.dumps;if(dumps===undefined){this.model_.importWarning({type:'memory_dump_parse_error',message:'\'dumps\' field not found in a process memory dump'+' event for PID='+pid+' and dump ID='+dumpId+'.'});continue;}this.parseMemoryDumpTotals_(processMemoryDump,dumps,pid,dumpId);this.parseMemoryDumpVmRegions_(processMemoryDump,dumps,pid,dumpId);this.parseMemoryDumpHeapDumps_(processMemoryDump,dumps,pid,dumpId);this.parseMemoryDumpLevelOfDetail_(levelsOfDetail,dumps,pid,dumpId);this.parseMemoryDumpAllocatorDumps_(processMemoryDump,globalMemoryDump,processMemoryAllocatorDumpsByFullName,globalMemoryAllocatorDumpsByFullName,allMemoryAllocatorDumpsByGuid,dumps,pid,dumpId);}if(levelsOfDetail.process===undefined){levelsOfDetail.process=processMemoryDump.vmRegions?DETAILED:LIGHT;}if(!this.updateMemoryDumpLevelOfDetail_(levelsOfDetail,'global',levelsOfDetail.process)){this.model_.importWarning({type:'memory_dump_parse_error',message:'diffent levels of detail provided for global memory'+' dump (dump ID='+dumpId+').'});}processMemoryDump.levelOfDetail=levelsOfDetail.process;delete levelsOfDetail.process;processMemoryDump.memoryAllocatorDumps=this.inferMemoryAllocatorDumpTree_(processMemoryAllocatorDumpsByFullName);},parseMemoryDumpTotals_:function(processMemoryDump,dumps,pid,dumpId){var rawTotals=dumps.process_totals;if(rawTotals===undefined)return;if(processMemoryDump.totals!==undefined){this.model_.importWarning({type:'memory_dump_parse_error',message:'Process totals provided multiple times for'+' process memory dump for PID='+pid+' and dump ID='+dumpId+'.'});return;}var totals={};var platformSpecificTotals=undefined;for(var rawTotalName in rawTotals){var rawTotalValue=rawTotals[rawTotalName];if(rawTotalValue===undefined)continue;if(rawTotalName==='resident_set_bytes'){totals.residentBytes=parseInt(rawTotalValue,16);continue;}if(rawTotalName==='peak_resident_set_bytes'){totals.peakResidentBytes=parseInt(rawTotalValue,16);continue;}if(rawTotalName==='is_peak_rss_resetable'){totals.arePeakResidentBytesResettable=!!rawTotalValue;continue;}if(platformSpecificTotals===undefined){platformSpecificTotals={};totals.platformSpecific=platformSpecificTotals;}platformSpecificTotals[rawTotalName]=parseInt(rawTotalValue,16);}if(totals.peakResidentBytes===undefined&&totals.arePeakResidentBytesResettable!==undefined){this.model_.importWarning({type:'memory_dump_parse_error',message:'Optional field peak_resident_set_bytes found'+' but is_peak_rss_resetable not found in'+' process memory dump for PID='+pid+' and dump ID='+dumpId+'.'});}if(totals.arePeakResidentBytesResettable!==undefined&&totals.peakResidentBytes===undefined){this.model_.importWarning({type:'memory_dump_parse_error',message:'Optional field is_peak_rss_resetable found'+' but peak_resident_set_bytes not found in'+' process memory dump for PID='+pid+' and dump ID='+dumpId+'.'});}processMemoryDump.totals=totals;},parseMemoryDumpVmRegions_:function(processMemoryDump,dumps,pid,dumpId){var rawProcessMmaps=dumps.process_mmaps;if(rawProcessMmaps===undefined)return;var rawVmRegions=rawProcessMmaps.vm_regions;if(rawVmRegions===undefined)return;if(processMemoryDump.vmRegions!==undefined){this.model_.importWarning({type:'memory_dump_parse_error',message:'VM regions provided multiple times for'+' process memory dump for PID='+pid+' and dump ID='+dumpId+'.'});return;}var vmRegions=new Array(rawVmRegions.length);for(var i=0;i<rawVmRegions.length;i++){var rawVmRegion=rawVmRegions[i];var byteStats={};var rawByteStats=rawVmRegion.bs;for(var rawByteStatName in rawByteStats){var rawByteStatValue=rawByteStats[rawByteStatName];if(rawByteStatValue===undefined){this.model_.importWarning({type:'memory_dump_parse_error',message:'Byte stat \''+rawByteStatName+'\' of VM region '+i+' ('+rawVmRegion.mf+') in process memory dump for '+'PID='+pid+' and dump ID='+dumpId+' does not have a value.'});continue;}var byteStatName=BYTE_STAT_NAME_MAP[rawByteStatName];if(byteStatName===undefined){this.model_.importWarning({type:'memory_dump_parse_error',message:'Unknown byte stat name \''+rawByteStatName+'\' ('+rawByteStatValue+') of VM region '+i+' ('+rawVmRegion.mf+') in process memory dump for PID='+pid+' and dump ID='+dumpId+'.'});continue;}byteStats[byteStatName]=parseInt(rawByteStatValue,16);}vmRegions[i]=new tr.model.VMRegion(parseInt(rawVmRegion.sa,16),parseInt(rawVmRegion.sz,16),rawVmRegion.pf,rawVmRegion.mf,byteStats);}processMemoryDump.vmRegions=tr.model.VMRegionClassificationNode.fromRegions(vmRegions);},parseMemoryDumpHeapDumps_:function(processMemoryDump,dumps,pid,dumpId){var rawHeapDumps=dumps.heaps;if(rawHeapDumps===undefined)return;if(processMemoryDump.heapDumps!==undefined){this.model_.importWarning({type:'memory_dump_parse_error',message:'Heap dumps provided multiple times for'+' process memory dump for PID='+pid+' and dump ID='+dumpId+'.'});return;}var model=this.model_;var idPrefix='p'+pid+':';var heapDumps={};var objectTypeNameMap=this.objectTypeNameMap_[pid];if(objectTypeNameMap===undefined){this.model_.importWarning({type:'memory_dump_parse_error',message:'Missing mapping from object type IDs to names.'});}for(var allocatorName in rawHeapDumps){var entries=rawHeapDumps[allocatorName].entries;if(entries===undefined||entries.length===0){this.model_.importWarning({type:'memory_dump_parse_error',message:'No heap entries in a '+allocatorName+' heap dump for PID='+pid+' and dump ID='+dumpId+'.'});continue;}var isOldFormat=entries[0].bt===undefined;if(!isOldFormat&&objectTypeNameMap===undefined){continue;}var heapDump=new tr.model.HeapDump(processMemoryDump,allocatorName);for(var i=0;i<entries.length;i++){var entry=entries[i];var leafStackFrameIndex=entry.bt;var leafStackFrame;if(isOldFormat){if(leafStackFrameIndex===undefined){leafStackFrame=undefined;}else{var leafStackFrameId=idPrefix+leafStackFrameIndex;if(leafStackFrameIndex===''){leafStackFrame=undefined;}else{leafStackFrame=model.stackFrames[leafStackFrameId];if(leafStackFrame===undefined){this.model_.importWarning({type:'memory_dump_parse_error',message:'Missing leaf stack frame (ID '+leafStackFrameId+') of heap entry '+i+' (size '+size+') in a '+allocatorName+' heap dump for PID='+pid+'.'});continue;}}leafStackFrameId+=':self';if(model.stackFrames[leafStackFrameId]!==undefined){leafStackFrame=model.stackFrames[leafStackFrameId];}else{leafStackFrame=new tr.model.StackFrame(leafStackFrame,leafStackFrameId,'<self>',undefined);model.addStackFrame(leafStackFrame);}}}else{if(leafStackFrameIndex===undefined){this.model_.importWarning({type:'memory_dump_parse_error',message:'Missing stack frame ID of heap entry '+i+' (size '+size+') in a '+allocatorName+' heap dump for PID='+pid+'.'});continue;}var leafStackFrameId=idPrefix+leafStackFrameIndex;if(leafStackFrameIndex===''){leafStackFrame=undefined;}else{leafStackFrame=model.stackFrames[leafStackFrameId];if(leafStackFrame===undefined){this.model_.importWarning({type:'memory_dump_parse_error',message:'Missing leaf stack frame (ID '+leafStackFrameId+') of heap entry '+i+' (size '+size+') in a '+allocatorName+' heap dump for PID='+pid+'.'});continue;}}}var objectTypeId=entry.type;var objectTypeName;if(objectTypeId===undefined){objectTypeName=undefined;}else if(objectTypeNameMap===undefined){continue;}else{objectTypeName=objectTypeNameMap[objectTypeId];if(objectTypeName===undefined){this.model_.importWarning({type:'memory_dump_parse_error',message:'Missing object type name (ID '+objectTypeId+') of heap entry '+i+' (size '+size+') in a '+allocatorName+' heap dump for pid='+pid+'.'});continue;}}var size=parseInt(entry.size,16);var count=entry.count===undefined?undefined:parseInt(entry.count,16);heapDump.addEntry(leafStackFrame,objectTypeName,size,count);}if(heapDump.entries.length>0)heapDumps[allocatorName]=heapDump;}if(Object.keys(heapDumps).length>0)processMemoryDump.heapDumps=heapDumps;},parseMemoryDumpLevelOfDetail_:function(levelsOfDetail,dumps,pid,dumpId){var rawLevelOfDetail=dumps.level_of_detail;var level;switch(rawLevelOfDetail){case'background':level=BACKGROUND;break;case'light':level=LIGHT;break;case'detailed':level=DETAILED;break;case undefined:level=undefined;break;default:this.model_.importWarning({type:'memory_dump_parse_error',message:'unknown raw level of detail \''+rawLevelOfDetail+'\' of process memory dump for PID='+pid+' and dump ID='+dumpId+'.'});return;}if(!this.updateMemoryDumpLevelOfDetail_(levelsOfDetail,'process',level)){this.model_.importWarning({type:'memory_dump_parse_error',message:'diffent levels of detail provided for process memory'+' dump for PID='+pid+' (dump ID='+dumpId+').'});}},updateMemoryDumpLevelOfDetail_:function(levelsOfDetail,scope,level){if(!(scope in levelsOfDetail)||level===levelsOfDetail[scope]){levelsOfDetail[scope]=level;return true;}if(MEMORY_DUMP_LEVEL_OF_DETAIL_ORDER.indexOf(level)>MEMORY_DUMP_LEVEL_OF_DETAIL_ORDER.indexOf(levelsOfDetail[scope])){levelsOfDetail[scope]=level;}return false;},parseMemoryDumpAllocatorDumps_:function(processMemoryDump,globalMemoryDump,processMemoryAllocatorDumpsByFullName,globalMemoryAllocatorDumpsByFullName,allMemoryAllocatorDumpsByGuid,dumps,pid,dumpId){var rawAllocatorDumps=dumps.allocators;if(rawAllocatorDumps===undefined)return;for(var fullName in rawAllocatorDumps){var rawAllocatorDump=rawAllocatorDumps[fullName];var guid=rawAllocatorDump.guid;if(guid===undefined){this.model_.importWarning({type:'memory_dump_parse_error',message:'Memory allocator dump '+fullName+' for PID='+pid+' and dump ID='+dumpId+' does not have a GUID.'});}var flags=rawAllocatorDump.flags||0;var isWeakDump=!!(flags&WEAK_MEMORY_ALLOCATOR_DUMP_FLAG);var containerMemoryDump;var dstIndex;if(fullName.startsWith(GLOBAL_MEMORY_ALLOCATOR_DUMP_PREFIX)){fullName=fullName.substring(GLOBAL_MEMORY_ALLOCATOR_DUMP_PREFIX.length);containerMemoryDump=globalMemoryDump;dstIndex=globalMemoryAllocatorDumpsByFullName;}else{containerMemoryDump=processMemoryDump;dstIndex=processMemoryAllocatorDumpsByFullName;}var allocatorDump=allMemoryAllocatorDumpsByGuid[guid];if(allocatorDump===undefined){if(fullName in dstIndex){this.model_.importWarning({type:'memory_dump_parse_error',message:'Multiple GUIDs provided for'+' memory allocator dump '+fullName+': '+dstIndex[fullName].guid+', '+guid+' (ignored) for'+' PID='+pid+' and dump ID='+dumpId+'.'});continue;}allocatorDump=new tr.model.MemoryAllocatorDump(containerMemoryDump,fullName,guid);allocatorDump.weak=isWeakDump;dstIndex[fullName]=allocatorDump;if(guid!==undefined)allMemoryAllocatorDumpsByGuid[guid]=allocatorDump;}else{if(allocatorDump.containerMemoryDump!==containerMemoryDump){this.model_.importWarning({type:'memory_dump_parse_error',message:'Memory allocator dump '+fullName+' (GUID='+guid+') for PID='+pid+' and dump ID='+dumpId+' dumped in different contexts.'});continue;}if(allocatorDump.fullName!==fullName){this.model_.importWarning({type:'memory_dump_parse_error',message:'Memory allocator dump with GUID='+guid+' for PID='+pid+' and dump ID='+dumpId+' has multiple names: '+allocatorDump.fullName+', '+fullName+' (ignored).'});continue;}if(!isWeakDump){allocatorDump.weak=false;}}var attributes=rawAllocatorDump.attrs;if(attributes===undefined){this.model_.importWarning({type:'memory_dump_parse_error',message:'Memory allocator dump '+fullName+' (GUID='+guid+') for PID='+pid+' and dump ID='+dumpId+' does not have attributes.'});attributes={};}for(var attrName in attributes){var attrArgs=attributes[attrName];var attrType=attrArgs.type;var attrValue=attrArgs.value;switch(attrType){case'scalar':if(attrName in allocatorDump.numerics){this.model_.importWarning({type:'memory_dump_parse_error',message:'Multiple values provided for scalar attribute '+attrName+' of memory allocator dump '+fullName+' (GUID='+guid+') for PID='+pid+' and dump ID='+dumpId+'.'});break;}var unit=attrArgs.units==='bytes'?tr.b.Unit.byName.sizeInBytes_smallerIsBetter:tr.b.Unit.byName.unitlessNumber_smallerIsBetter;var value=parseInt(attrValue,16);allocatorDump.addNumeric(attrName,new tr.v.ScalarNumeric(unit,value));break;case'string':if(attrName in allocatorDump.diagnostics){this.model_.importWarning({type:'memory_dump_parse_error',message:'Multiple values provided for string attribute '+attrName+' of memory allocator dump '+fullName+' (GUID='+guid+') for PID='+pid+' and dump ID='+dumpId+'.'});break;}allocatorDump.addDiagnostic(attrName,attrValue);break;default:this.model_.importWarning({type:'memory_dump_parse_error',message:'Unknown type provided for attribute '+attrName+' of memory allocator dump '+fullName+' (GUID='+guid+') for PID='+pid+' and dump ID='+dumpId+': '+attrType});break;}}}},inferMemoryAllocatorDumpTree_:function(memoryAllocatorDumpsByFullName){var rootAllocatorDumps=[];var fullNames=Object.keys(memoryAllocatorDumpsByFullName);fullNames.sort();for(var i=0;i<fullNames.length;i++){var fullName=fullNames[i];var allocatorDump=memoryAllocatorDumpsByFullName[fullName];while(true){var lastSlashIndex=fullName.lastIndexOf('/');if(lastSlashIndex===-1){rootAllocatorDumps.push(allocatorDump);break;}var parentFullName=fullName.substring(0,lastSlashIndex);var parentAllocatorDump=memoryAllocatorDumpsByFullName[parentFullName];var parentAlreadyExisted=true;if(parentAllocatorDump===undefined){parentAlreadyExisted=false;parentAllocatorDump=new tr.model.MemoryAllocatorDump(allocatorDump.containerMemoryDump,parentFullName);if(allocatorDump.weak!==false){parentAllocatorDump.weak=undefined;}memoryAllocatorDumpsByFullName[parentFullName]=parentAllocatorDump;}allocatorDump.parent=parentAllocatorDump;parentAllocatorDump.children.push(allocatorDump);if(parentAlreadyExisted){if(!allocatorDump.weak){while(parentAllocatorDump!==undefined&&parentAllocatorDump.weak===undefined){parentAllocatorDump.weak=false;parentAllocatorDump=parentAllocatorDump.parent;}}break;}fullName=parentFullName;allocatorDump=parentAllocatorDump;}}for(var fullName in memoryAllocatorDumpsByFullName){var allocatorDump=memoryAllocatorDumpsByFullName[fullName];if(allocatorDump.weak===undefined)allocatorDump.weak=true;}return rootAllocatorDumps;},parseMemoryDumpAllocatorEdges_:function(allMemoryAllocatorDumpsByGuid,dumpIdEvents,dumpId){for(var pid in dumpIdEvents){var processEvents=dumpIdEvents[pid];for(var i=0;i<processEvents.length;i++){var processEvent=processEvents[i];var dumps=processEvent.args.dumps;if(dumps===undefined)continue;var rawEdges=dumps.allocators_graph;if(rawEdges===undefined)continue;for(var j=0;j<rawEdges.length;j++){var rawEdge=rawEdges[j];var sourceGuid=rawEdge.source;var sourceDump=allMemoryAllocatorDumpsByGuid[sourceGuid];if(sourceDump===undefined){this.model_.importWarning({type:'memory_dump_parse_error',message:'Edge for PID='+pid+' and dump ID='+dumpId+' is missing source memory allocator dump (GUID='+sourceGuid+').'});continue;}var targetGuid=rawEdge.target;var targetDump=allMemoryAllocatorDumpsByGuid[targetGuid];if(targetDump===undefined){this.model_.importWarning({type:'memory_dump_parse_error',message:'Edge for PID='+pid+' and dump ID='+dumpId+' is missing target memory allocator dump (GUID='+targetGuid+').'});continue;}var importance=rawEdge.importance;var edge=new tr.model.MemoryAllocatorDumpLink(sourceDump,targetDump,importance);switch(rawEdge.type){case'ownership':if(sourceDump.owns!==undefined){this.model_.importWarning({type:'memory_dump_parse_error',message:'Memory allocator dump '+sourceDump.fullName+' (GUID='+sourceGuid+') already owns a memory'+' allocator dump ('+sourceDump.owns.target.fullName+').'});}else{sourceDump.owns=edge;targetDump.ownedBy.push(edge);}break;case'retention':sourceDump.retains.push(edge);targetDump.retainedBy.push(edge);break;default:this.model_.importWarning({type:'memory_dump_parse_error',message:'Invalid edge type: '+rawEdge.type+' (PID='+pid+', dump ID='+dumpId+', source='+sourceGuid+', target='+targetGuid+', importance='+importance+').'});}}}}},toModelTimeFromUs_:function(ts){if(!this.toModelTime_){this.toModelTime_=this.model_.clockSyncManager.getModelTimeTransformer(this.clockDomainId_);}return this.toModelTime_(tr.b.Unit.timestampFromUs(ts));},maybeToModelTimeFromUs_:function(ts){if(ts===undefined)return undefined;return this.toModelTimeFromUs_(ts);}};tr.importer.Importer.register(TraceEventImporter);return{TraceEventImporter:TraceEventImporter};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../../base/base64.js":35,"../../base/color_scheme.js":38,"../../base/range.js":53,"../../base/unit.js":63,"../../base/utils.js":65,"../../importer/context_processor.js":76,"../../importer/importer.js":82,"../../model/comment_box_annotation.js":112,"../../model/constants.js":114,"../../model/container_memory_dump.js":115,"../../model/counter_series.js":118,"../../model/flow_event.js":127,"../../model/global_memory_dump.js":129,"../../model/heap_dump.js":130,"../../model/instant_event.js":136,"../../model/memory_allocator_dump.js":140,"../../model/model.js":141,"../../model/process_memory_dump.js":151,"../../model/rect_annotation.js":152,"../../model/scoped_id.js":154,"../../model/slice_group.js":158,"../../model/vm_region.js":174,"../../model/x_marker_annotation.js":175,"../../value/numeric.js":196,"./trace_code_entry.js":70,"./trace_code_map.js":71,"./v8/codemap.js":73}],73:[function(require,module,exports){(function(global){"use strict";require("./splaytree.js");'use strict';global.tr.exportTo('tr.e.importer.v8',function(){function CodeMap(){this.dynamics_=new tr.e.importer.v8.SplayTree();this.dynamicsNameGen_=new tr.e.importer.v8.CodeMap.NameGenerator();this.statics_=new tr.e.importer.v8.SplayTree();this.libraries_=new tr.e.importer.v8.SplayTree();this.pages_=[];}CodeMap.PAGE_ALIGNMENT=12;CodeMap.PAGE_SIZE=1<<CodeMap.PAGE_ALIGNMENT;CodeMap.prototype.addCode=function(start,codeEntry){this.deleteAllCoveredNodes_(this.dynamics_,start,start+codeEntry.size);this.dynamics_.insert(start,codeEntry);};CodeMap.prototype.moveCode=function(from,to){var removedNode=this.dynamics_.remove(from);this.deleteAllCoveredNodes_(this.dynamics_,to,to+removedNode.value.size);this.dynamics_.insert(to,removedNode.value);};CodeMap.prototype.deleteCode=function(start){var removedNode=this.dynamics_.remove(start);};CodeMap.prototype.addLibrary=function(start,codeEntry){this.markPages_(start,start+codeEntry.size);this.libraries_.insert(start,codeEntry);};CodeMap.prototype.addStaticCode=function(start,codeEntry){this.statics_.insert(start,codeEntry);};CodeMap.prototype.markPages_=function(start,end){for(var addr=start;addr<=end;addr+=CodeMap.PAGE_SIZE){this.pages_[addr>>>CodeMap.PAGE_ALIGNMENT]=1;}};CodeMap.prototype.deleteAllCoveredNodes_=function(tree,start,end){var toDelete=[];var addr=end-1;while(addr>=start){var node=tree.findGreatestLessThan(addr);if(!node)break;var start2=node.key,end2=start2+node.value.size;if(start2<end&&start<end2)toDelete.push(start2);addr=start2-1;}for(var i=0,l=toDelete.length;i<l;++i)tree.remove(toDelete[i]);};CodeMap.prototype.isAddressBelongsTo_=function(addr,node){return addr>=node.key&&addr<node.key+node.value.size;};CodeMap.prototype.findInTree_=function(tree,addr){var node=tree.findGreatestLessThan(addr);return node&&this.isAddressBelongsTo_(addr,node)?node.value:null;};CodeMap.prototype.findEntryInLibraries=function(addr){var pageAddr=addr>>>CodeMap.PAGE_ALIGNMENT;if(pageAddr in this.pages_)return this.findInTree_(this.libraries_,addr);return undefined;};CodeMap.prototype.findEntry=function(addr){var pageAddr=addr>>>CodeMap.PAGE_ALIGNMENT;if(pageAddr in this.pages_){return this.findInTree_(this.statics_,addr)||this.findInTree_(this.libraries_,addr);}var min=this.dynamics_.findMin();var max=this.dynamics_.findMax();if(max!=null&&addr<max.key+max.value.size&&addr>=min.key){var dynaEntry=this.findInTree_(this.dynamics_,addr);if(dynaEntry==null)return null;if(!dynaEntry.nameUpdated_){dynaEntry.name=this.dynamicsNameGen_.getName(dynaEntry.name);dynaEntry.nameUpdated_=true;}return dynaEntry;}return null;};CodeMap.prototype.findDynamicEntryByStartAddress=function(addr){var node=this.dynamics_.find(addr);return node?node.value:null;};CodeMap.prototype.getAllDynamicEntries=function(){return this.dynamics_.exportValues();};CodeMap.prototype.getAllDynamicEntriesWithAddresses=function(){return this.dynamics_.exportKeysAndValues();};CodeMap.prototype.getAllStaticEntries=function(){return this.statics_.exportValues();};CodeMap.prototype.getAllLibrariesEntries=function(){return this.libraries_.exportValues();};CodeMap.CodeState={COMPILED:0,OPTIMIZABLE:1,OPTIMIZED:2};CodeMap.CodeEntry=function(size,opt_name,opt_type){this.id=tr.b.GUID.allocateSimple();this.size=size;this.name_=opt_name||'';this.type=opt_type||'';this.nameUpdated_=false;};CodeMap.CodeEntry.prototype={__proto__:Object.prototype,get name(){return this.name_;},set name(value){this.name_=value;},toString:function(){this.name_+': '+this.size.toString(16);}};CodeMap.CodeEntry.TYPE={SHARED_LIB:'SHARED_LIB',CPP:'CPP'};CodeMap.DynamicFuncCodeEntry=function(size,type,func,state){CodeMap.CodeEntry.call(this,size,'',type);this.func=func;this.state=state;};CodeMap.DynamicFuncCodeEntry.STATE_PREFIX=['','~','*'];CodeMap.DynamicFuncCodeEntry.prototype={__proto__:CodeMap.CodeEntry.prototype,get name(){return CodeMap.DynamicFuncCodeEntry.STATE_PREFIX[this.state]+this.func.name;},set name(value){this.name_=value;},getRawName:function(){return this.func.getName();},isJSFunction:function(){return true;},toString:function(){return this.type+': '+this.name+': '+this.size.toString(16);}};CodeMap.FunctionEntry=function(name){CodeMap.CodeEntry.call(this,0,name);};CodeMap.FunctionEntry.prototype={__proto__:CodeMap.CodeEntry.prototype,get name(){var name=this.name_;if(name.length==0){name='<anonymous>';}else if(name.charAt(0)==' '){name='<anonymous>'+name;}return name;},set name(value){this.name_=value;}};CodeMap.NameGenerator=function(){this.knownNames_={};};CodeMap.NameGenerator.prototype.getName=function(name){if(!(name in this.knownNames_)){this.knownNames_[name]=0;return name;}var count=++this.knownNames_[name];return name+' {'+count+'}';};return{CodeMap:CodeMap};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./splaytree.js":74}],74:[function(require,module,exports){(function(global){"use strict";require("../../../base/base.js");'use strict';global.tr.exportTo('tr.e.importer.v8',function(){function SplayTree(){};SplayTree.prototype.root_=null;SplayTree.prototype.isEmpty=function(){return!this.root_;};SplayTree.prototype.insert=function(key,value){if(this.isEmpty()){this.root_=new SplayTree.Node(key,value);return;}this.splay_(key);if(this.root_.key==key){return;}var node=new SplayTree.Node(key,value);if(key>this.root_.key){node.left=this.root_;node.right=this.root_.right;this.root_.right=null;}else{node.right=this.root_;node.left=this.root_.left;this.root_.left=null;}this.root_=node;};SplayTree.prototype.remove=function(key){if(this.isEmpty()){throw Error('Key not found: '+key);}this.splay_(key);if(this.root_.key!=key){throw Error('Key not found: '+key);}var removed=this.root_;if(!this.root_.left){this.root_=this.root_.right;}else{var right=this.root_.right;this.root_=this.root_.left;this.splay_(key);this.root_.right=right;}return removed;};SplayTree.prototype.find=function(key){if(this.isEmpty()){return null;}this.splay_(key);return this.root_.key==key?this.root_:null;};SplayTree.prototype.findMin=function(){if(this.isEmpty()){return null;}var current=this.root_;while(current.left){current=current.left;}return current;};SplayTree.prototype.findMax=function(opt_startNode){if(this.isEmpty()){return null;}var current=opt_startNode||this.root_;while(current.right){current=current.right;}return current;};SplayTree.prototype.findGreatestLessThan=function(key){if(this.isEmpty()){return null;}this.splay_(key);if(this.root_.key<=key){return this.root_;}else if(this.root_.left){return this.findMax(this.root_.left);}else{return null;}};SplayTree.prototype.exportKeysAndValues=function(){var result=[];this.traverse_(function(node){result.push([node.key,node.value]);});return result;};SplayTree.prototype.exportValues=function(){var result=[];this.traverse_(function(node){result.push(node.value);});return result;};SplayTree.prototype.splay_=function(key){if(this.isEmpty()){return;}var dummy,left,right;dummy=left=right=new SplayTree.Node(null,null);var current=this.root_;while(true){if(key<current.key){if(!current.left){break;}if(key<current.left.key){var tmp=current.left;current.left=tmp.right;tmp.right=current;current=tmp;if(!current.left){break;}}right.left=current;right=current;current=current.left;}else if(key>current.key){if(!current.right){break;}if(key>current.right.key){var tmp=current.right;current.right=tmp.left;tmp.left=current;current=tmp;if(!current.right){break;}}left.right=current;left=current;current=current.right;}else{break;}}left.right=current.left;right.left=current.right;current.left=dummy.right;current.right=dummy.left;this.root_=current;};SplayTree.prototype.traverse_=function(f){var nodesToVisit=[this.root_];while(nodesToVisit.length>0){var node=nodesToVisit.shift();if(node==null){continue;}f(node);nodesToVisit.push(node.left);nodesToVisit.push(node.right);}};SplayTree.Node=function(key,value){this.key=key;this.value=value;};SplayTree.Node.prototype.left=null;SplayTree.Node.prototype.right=null;return{SplayTree:SplayTree};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../../../base/base.js":34}],75:[function(require,module,exports){"use strict";require("./importer/trace_event_importer.js");require("../model/model.js");},{"../model/model.js":141,"./importer/trace_event_importer.js":72}],76:[function(require,module,exports){(function(global){"use strict";require("../base/base.js");'use strict';global.tr.exportTo('tr.importer',function(){function ContextProcessor(model){this.model_=model;this.activeContexts_=[];this.stackPerType_={};this.contextCache_={};this.contextSetCache_={};this.cachedEntryForActiveContexts_=undefined;this.seenSnapshots_={};};ContextProcessor.prototype={enterContext:function(contextType,scopedId){var newActiveContexts=[this.getOrCreateContext_(contextType,scopedId)];for(var oldContext of this.activeContexts_){if(oldContext.type===contextType){this.pushContext_(oldContext);}else{newActiveContexts.push(oldContext);}}this.activeContexts_=newActiveContexts;this.cachedEntryForActiveContexts_=undefined;},leaveContext:function(contextType,scopedId){this.leaveContextImpl_(context=>context.type===contextType&&context.snapshot.scope===scopedId.scope&&context.snapshot.idRef===scopedId.id);},destroyContext:function(scopedId){tr.b.iterItems(this.stackPerType_,function(contextType,stack){var newLength=0;for(var i=0;i<stack.length;++i){if(stack[i].snapshot.scope!==scopedId.scope||stack[i].snapshot.idRef!==scopedId.id){stack[newLength++]=stack[i];}}stack.length=newLength;});this.leaveContextImpl_(context=>context.snapshot.scope===scopedId.scope&&context.snapshot.idRef===scopedId.id);},leaveContextImpl_:function(predicate){var newActiveContexts=[];for(var oldContext of this.activeContexts_){if(predicate(oldContext)){var previousContext=this.popContext_(oldContext.type);if(previousContext)newActiveContexts.push(previousContext);}else{newActiveContexts.push(oldContext);}}this.activeContexts_=newActiveContexts;this.cachedEntryForActiveContexts_=undefined;},getOrCreateContext_:function(contextType,scopedId){var context={type:contextType,snapshot:{scope:scopedId.scope,idRef:scopedId.id}};var key=this.getContextKey_(context);if(key in this.contextCache_)return this.contextCache_[key];this.contextCache_[key]=context;var snapshotKey=this.getSnapshotKey_(scopedId);this.seenSnapshots_[snapshotKey]=true;return context;},pushContext_:function(context){if(!(context.type in this.stackPerType_))this.stackPerType_[context.type]=[];this.stackPerType_[context.type].push(context);},popContext_:function(contextType){if(!(contextType in this.stackPerType_))return undefined;return this.stackPerType_[contextType].pop();},getContextKey_:function(context){return[context.type,context.snapshot.scope,context.snapshot.idRef].join('\x00');},getSnapshotKey_:function(scopedId){return[scopedId.scope,scopedId.idRef].join('\x00');},get activeContexts(){if(this.cachedEntryForActiveContexts_===undefined){var key=[];for(var context of this.activeContexts_)key.push(this.getContextKey_(context));key.sort();key=key.join('\x00');if(key in this.contextSetCache_){this.cachedEntryForActiveContexts_=this.contextSetCache_[key];}else{this.activeContexts_.sort(function(a,b){var keyA=this.getContextKey_(a);var keyB=this.getContextKey_(b);if(keyA<keyB)return-1;if(keyA>keyB)return 1;return 0;}.bind(this));this.contextSetCache_[key]=Object.freeze(this.activeContexts_);this.cachedEntryForActiveContexts_=this.contextSetCache_[key];}}return this.cachedEntryForActiveContexts_;},invalidateContextCacheForSnapshot:function(scopedId){var snapshotKey=this.getSnapshotKey_(scopedId);if(!(snapshotKey in this.seenSnapshots_))return;this.contextCache_={};this.contextSetCache_={};this.cachedEntryForActiveContexts_=undefined;this.activeContexts_=this.activeContexts_.map(function(context){if(context.snapshot.scope!==scopedId.scope||context.snapshot.idRef!==scopedId.id)return context;return{type:context.type,snapshot:{scope:context.snapshot.scope,idRef:context.snapshot.idRef}};});this.seenSnapshots_={};}};return{ContextProcessor:ContextProcessor};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/base.js":34}],77:[function(require,module,exports){(function(global){"use strict";require("../base/base.js");require("./importer.js");'use strict';global.tr.exportTo('tr.importer',function(){function EmptyImporter(events){this.importPriority=0;};EmptyImporter.canImport=function(eventData){if(eventData instanceof Array&&eventData.length==0)return true;if(typeof eventData==='string'||eventData instanceof String){return eventData.length==0;}return false;};EmptyImporter.prototype={__proto__:tr.importer.Importer.prototype,get importerName(){return'EmptyImporter';}};tr.importer.Importer.register(EmptyImporter);return{EmptyImporter:EmptyImporter};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/base.js":34,"./importer.js":82}],78:[function(require,module,exports){(function(global){"use strict";require("../base/range_utils.js");require("../extras/chrome/cc/input_latency_async_slice.js");require("./proto_expectation.js");'use strict';global.tr.exportTo('tr.importer',function(){var ProtoExpectation=tr.importer.ProtoExpectation;var INPUT_TYPE=tr.e.cc.INPUT_EVENT_TYPE_NAMES;var KEYBOARD_TYPE_NAMES=[INPUT_TYPE.CHAR,INPUT_TYPE.KEY_DOWN_RAW,INPUT_TYPE.KEY_DOWN,INPUT_TYPE.KEY_UP];var MOUSE_RESPONSE_TYPE_NAMES=[INPUT_TYPE.CLICK,INPUT_TYPE.CONTEXT_MENU];var MOUSE_WHEEL_TYPE_NAMES=[INPUT_TYPE.MOUSE_WHEEL];var MOUSE_DRAG_TYPE_NAMES=[INPUT_TYPE.MOUSE_DOWN,INPUT_TYPE.MOUSE_MOVE,INPUT_TYPE.MOUSE_UP];var TAP_TYPE_NAMES=[INPUT_TYPE.TAP,INPUT_TYPE.TAP_CANCEL,INPUT_TYPE.TAP_DOWN];var PINCH_TYPE_NAMES=[INPUT_TYPE.PINCH_BEGIN,INPUT_TYPE.PINCH_END,INPUT_TYPE.PINCH_UPDATE];var FLING_TYPE_NAMES=[INPUT_TYPE.FLING_CANCEL,INPUT_TYPE.FLING_START];var TOUCH_TYPE_NAMES=[INPUT_TYPE.TOUCH_END,INPUT_TYPE.TOUCH_MOVE,INPUT_TYPE.TOUCH_START];var SCROLL_TYPE_NAMES=[INPUT_TYPE.SCROLL_BEGIN,INPUT_TYPE.SCROLL_END,INPUT_TYPE.SCROLL_UPDATE];var ALL_HANDLED_TYPE_NAMES=[].concat(KEYBOARD_TYPE_NAMES,MOUSE_RESPONSE_TYPE_NAMES,MOUSE_WHEEL_TYPE_NAMES,MOUSE_DRAG_TYPE_NAMES,PINCH_TYPE_NAMES,TAP_TYPE_NAMES,FLING_TYPE_NAMES,TOUCH_TYPE_NAMES,SCROLL_TYPE_NAMES);var RENDERER_FLING_TITLE='InputHandlerProxy::HandleGestureFling::started';var PLAYBACK_EVENT_TITLE='VideoPlayback';var CSS_ANIMATION_TITLE='Animation';var INPUT_MERGE_THRESHOLD_MS=200;var ANIMATION_MERGE_THRESHOLD_MS=32;var MOUSE_WHEEL_THRESHOLD_MS=40;var MOUSE_MOVE_THRESHOLD_MS=40;var KEYBOARD_IR_NAME='Keyboard';var MOUSE_IR_NAME='Mouse';var MOUSEWHEEL_IR_NAME='MouseWheel';var TAP_IR_NAME='Tap';var PINCH_IR_NAME='Pinch';var FLING_IR_NAME='Fling';var TOUCH_IR_NAME='Touch';var SCROLL_IR_NAME='Scroll';var CSS_IR_NAME='CSS';var WEBGL_IR_NAME='WebGL';var VIDEO_IR_NAME='Video';function compareEvents(x,y){if(x.start!==y.start)return x.start-y.start;if(x.end!==y.end)return x.end-y.end;if(x.guid&&y.guid)return x.guid-y.guid;return 0;}function forEventTypesIn(events,typeNames,cb,opt_this){events.forEach(function(event){if(typeNames.indexOf(event.typeName)>=0){cb.call(opt_this,event);}});}function causedFrame(event){return event.associatedEvents.some(x=>x.title===tr.model.helpers.IMPL_RENDERING_STATS);}function getSortedFrameEventsByProcess(modelHelper){var frameEventsByPid={};tr.b.iterItems(modelHelper.rendererHelpers,function(pid,rendererHelper){frameEventsByPid[pid]=rendererHelper.getFrameEventsInRange(tr.model.helpers.IMPL_FRAMETIME_TYPE,modelHelper.model.bounds);});return frameEventsByPid;}function getSortedInputEvents(modelHelper){var inputEvents=[];var browserProcess=modelHelper.browserHelper.process;var mainThread=browserProcess.findAtMostOneThreadNamed('CrBrowserMain');for(var slice of mainThread.asyncSliceGroup.getDescendantEvents()){if(!slice.isTopLevel)continue;if(!(slice instanceof tr.e.cc.InputLatencyAsyncSlice))continue;if(isNaN(slice.start)||isNaN(slice.duration)||isNaN(slice.end))continue;inputEvents.push(slice);}return inputEvents.sort(compareEvents);}function findProtoExpectations(modelHelper,sortedInputEvents){var protoExpectations=[];var handlers=[handleKeyboardEvents,handleMouseResponseEvents,handleMouseWheelEvents,handleMouseDragEvents,handleTapResponseEvents,handlePinchEvents,handleFlingEvents,handleTouchEvents,handleScrollEvents,handleCSSAnimations,handleWebGLAnimations,handleVideoAnimations];handlers.forEach(function(handler){protoExpectations.push.apply(protoExpectations,handler(modelHelper,sortedInputEvents));});protoExpectations.sort(compareEvents);return protoExpectations;}function handleKeyboardEvents(modelHelper,sortedInputEvents){var protoExpectations=[];forEventTypesIn(sortedInputEvents,KEYBOARD_TYPE_NAMES,function(event){var pe=new ProtoExpectation(ProtoExpectation.RESPONSE_TYPE,KEYBOARD_IR_NAME);pe.pushEvent(event);protoExpectations.push(pe);});return protoExpectations;}function handleMouseResponseEvents(modelHelper,sortedInputEvents){var protoExpectations=[];forEventTypesIn(sortedInputEvents,MOUSE_RESPONSE_TYPE_NAMES,function(event){var pe=new ProtoExpectation(ProtoExpectation.RESPONSE_TYPE,MOUSE_IR_NAME);pe.pushEvent(event);protoExpectations.push(pe);});return protoExpectations;}function handleMouseWheelEvents(modelHelper,sortedInputEvents){var protoExpectations=[];var currentPE=undefined;var prevEvent_=undefined;forEventTypesIn(sortedInputEvents,MOUSE_WHEEL_TYPE_NAMES,function(event){var prevEvent=prevEvent_;prevEvent_=event;if(currentPE&&prevEvent.start+MOUSE_WHEEL_THRESHOLD_MS>=event.start){if(currentPE.irType===ProtoExpectation.ANIMATION_TYPE){currentPE.pushEvent(event);}else{currentPE=new ProtoExpectation(ProtoExpectation.ANIMATION_TYPE,MOUSEWHEEL_IR_NAME);currentPE.pushEvent(event);protoExpectations.push(currentPE);}return;}currentPE=new ProtoExpectation(ProtoExpectation.RESPONSE_TYPE,MOUSEWHEEL_IR_NAME);currentPE.pushEvent(event);protoExpectations.push(currentPE);});return protoExpectations;}function handleMouseDragEvents(modelHelper,sortedInputEvents){var protoExpectations=[];var currentPE=undefined;var mouseDownEvent=undefined;forEventTypesIn(sortedInputEvents,MOUSE_DRAG_TYPE_NAMES,function(event){switch(event.typeName){case INPUT_TYPE.MOUSE_DOWN:if(causedFrame(event)){var pe=new ProtoExpectation(ProtoExpectation.RESPONSE_TYPE,MOUSE_IR_NAME);pe.pushEvent(event);protoExpectations.push(pe);}else{mouseDownEvent=event;}break;case INPUT_TYPE.MOUSE_MOVE:if(!causedFrame(event)){var pe=new ProtoExpectation(ProtoExpectation.IGNORED_TYPE);pe.pushEvent(event);protoExpectations.push(pe);}else if(!currentPE||!currentPE.isNear(event,MOUSE_MOVE_THRESHOLD_MS)){currentPE=new ProtoExpectation(ProtoExpectation.RESPONSE_TYPE,MOUSE_IR_NAME);currentPE.pushEvent(event);if(mouseDownEvent){currentPE.associatedEvents.push(mouseDownEvent);mouseDownEvent=undefined;}protoExpectations.push(currentPE);}else{if(currentPE.irType===ProtoExpectation.ANIMATION_TYPE){currentPE.pushEvent(event);}else{currentPE=new ProtoExpectation(ProtoExpectation.ANIMATION_TYPE,MOUSE_IR_NAME);currentPE.pushEvent(event);protoExpectations.push(currentPE);}}break;case INPUT_TYPE.MOUSE_UP:if(!mouseDownEvent){var pe=new ProtoExpectation(causedFrame(event)?ProtoExpectation.RESPONSE_TYPE:ProtoExpectation.IGNORED_TYPE,MOUSE_IR_NAME);pe.pushEvent(event);protoExpectations.push(pe);break;}if(currentPE){currentPE.pushEvent(event);}else{currentPE=new ProtoExpectation(ProtoExpectation.RESPONSE_TYPE,MOUSE_IR_NAME);if(mouseDownEvent)currentPE.associatedEvents.push(mouseDownEvent);currentPE.pushEvent(event);protoExpectations.push(currentPE);}mouseDownEvent=undefined;currentPE=undefined;break;}});if(mouseDownEvent){currentPE=new ProtoExpectation(ProtoExpectation.IGNORED_TYPE);currentPE.pushEvent(mouseDownEvent);protoExpectations.push(currentPE);}return protoExpectations;}function handleTapResponseEvents(modelHelper,sortedInputEvents){var protoExpectations=[];var currentPE=undefined;forEventTypesIn(sortedInputEvents,TAP_TYPE_NAMES,function(event){switch(event.typeName){case INPUT_TYPE.TAP_DOWN:currentPE=new ProtoExpectation(ProtoExpectation.RESPONSE_TYPE,TAP_IR_NAME);currentPE.pushEvent(event);protoExpectations.push(currentPE);break;case INPUT_TYPE.TAP:if(currentPE){currentPE.pushEvent(event);}else{currentPE=new ProtoExpectation(ProtoExpectation.RESPONSE_TYPE,TAP_IR_NAME);currentPE.pushEvent(event);protoExpectations.push(currentPE);}currentPE=undefined;break;case INPUT_TYPE.TAP_CANCEL:if(!currentPE){var pe=new ProtoExpectation(ProtoExpectation.IGNORED_TYPE);pe.pushEvent(event);protoExpectations.push(pe);break;}if(currentPE.isNear(event,INPUT_MERGE_THRESHOLD_MS)){currentPE.pushEvent(event);}else{currentPE=new ProtoExpectation(ProtoExpectation.RESPONSE_TYPE,TAP_IR_NAME);currentPE.pushEvent(event);protoExpectations.push(currentPE);}currentPE=undefined;break;}});return protoExpectations;}function handlePinchEvents(modelHelper,sortedInputEvents){var protoExpectations=[];var currentPE=undefined;var sawFirstUpdate=false;var modelBounds=modelHelper.model.bounds;forEventTypesIn(sortedInputEvents,PINCH_TYPE_NAMES,function(event){switch(event.typeName){case INPUT_TYPE.PINCH_BEGIN:if(currentPE&&currentPE.isNear(event,INPUT_MERGE_THRESHOLD_MS)){currentPE.pushEvent(event);break;}currentPE=new ProtoExpectation(ProtoExpectation.RESPONSE_TYPE,PINCH_IR_NAME);currentPE.pushEvent(event);currentPE.isAnimationBegin=true;protoExpectations.push(currentPE);sawFirstUpdate=false;break;case INPUT_TYPE.PINCH_UPDATE:if(!currentPE||currentPE.irType===ProtoExpectation.RESPONSE_TYPE&&sawFirstUpdate||!currentPE.isNear(event,INPUT_MERGE_THRESHOLD_MS)){currentPE=new ProtoExpectation(ProtoExpectation.ANIMATION_TYPE,PINCH_IR_NAME);currentPE.pushEvent(event);protoExpectations.push(currentPE);}else{currentPE.pushEvent(event);sawFirstUpdate=true;}break;case INPUT_TYPE.PINCH_END:if(currentPE){currentPE.pushEvent(event);}else{var pe=new ProtoExpectation(ProtoExpectation.IGNORED_TYPE);pe.pushEvent(event);protoExpectations.push(pe);}currentPE=undefined;break;}});return protoExpectations;}function handleFlingEvents(modelHelper,sortedInputEvents){var protoExpectations=[];var currentPE=undefined;function isRendererFling(event){return event.title===RENDERER_FLING_TITLE;}var browserHelper=modelHelper.browserHelper;var flingEvents=browserHelper.getAllAsyncSlicesMatching(isRendererFling);forEventTypesIn(sortedInputEvents,FLING_TYPE_NAMES,function(event){flingEvents.push(event);});flingEvents.sort(compareEvents);flingEvents.forEach(function(event){if(event.title===RENDERER_FLING_TITLE){if(currentPE){currentPE.pushEvent(event);}else{currentPE=new ProtoExpectation(ProtoExpectation.ANIMATION_TYPE,FLING_IR_NAME);currentPE.pushEvent(event);protoExpectations.push(currentPE);}return;}switch(event.typeName){case INPUT_TYPE.FLING_START:if(currentPE){console.error('Another FlingStart? File a bug with this trace!');currentPE.pushEvent(event);}else{currentPE=new ProtoExpectation(ProtoExpectation.ANIMATION_TYPE,FLING_IR_NAME);currentPE.pushEvent(event);currentPE.end=0;protoExpectations.push(currentPE);}break;case INPUT_TYPE.FLING_CANCEL:if(currentPE){currentPE.pushEvent(event);currentPE.end=event.start;currentPE=undefined;}else{var pe=new ProtoExpectation(ProtoExpectation.IGNORED_TYPE);pe.pushEvent(event);protoExpectations.push(pe);}break;}});if(currentPE&&!currentPE.end)currentPE.end=modelHelper.model.bounds.max;return protoExpectations;}function handleTouchEvents(modelHelper,sortedInputEvents){var protoExpectations=[];var currentPE=undefined;var sawFirstMove=false;forEventTypesIn(sortedInputEvents,TOUCH_TYPE_NAMES,function(event){switch(event.typeName){case INPUT_TYPE.TOUCH_START:if(currentPE){currentPE.pushEvent(event);}else{currentPE=new ProtoExpectation(ProtoExpectation.RESPONSE_TYPE,TOUCH_IR_NAME);currentPE.pushEvent(event);currentPE.isAnimationBegin=true;protoExpectations.push(currentPE);sawFirstMove=false;}break;case INPUT_TYPE.TOUCH_MOVE:if(!currentPE){currentPE=new ProtoExpectation(ProtoExpectation.ANIMATION_TYPE,TOUCH_IR_NAME);currentPE.pushEvent(event);protoExpectations.push(currentPE);break;}if(sawFirstMove&&currentPE.irType===ProtoExpectation.RESPONSE_TYPE||!currentPE.isNear(event,INPUT_MERGE_THRESHOLD_MS)){var prevEnd=currentPE.end;currentPE=new ProtoExpectation(ProtoExpectation.ANIMATION_TYPE,TOUCH_IR_NAME);currentPE.pushEvent(event);currentPE.start=prevEnd;protoExpectations.push(currentPE);}else{currentPE.pushEvent(event);sawFirstMove=true;}break;case INPUT_TYPE.TOUCH_END:if(!currentPE){var pe=new ProtoExpectation(ProtoExpectation.IGNORED_TYPE);pe.pushEvent(event);protoExpectations.push(pe);break;}if(currentPE.isNear(event,INPUT_MERGE_THRESHOLD_MS)){currentPE.pushEvent(event);}else{var pe=new ProtoExpectation(ProtoExpectation.IGNORED_TYPE);pe.pushEvent(event);protoExpectations.push(pe);}currentPE=undefined;break;}});return protoExpectations;}function handleScrollEvents(modelHelper,sortedInputEvents){var protoExpectations=[];var currentPE=undefined;var sawFirstUpdate=false;forEventTypesIn(sortedInputEvents,SCROLL_TYPE_NAMES,function(event){switch(event.typeName){case INPUT_TYPE.SCROLL_BEGIN:currentPE=new ProtoExpectation(ProtoExpectation.RESPONSE_TYPE,SCROLL_IR_NAME);currentPE.pushEvent(event);currentPE.isAnimationBegin=true;protoExpectations.push(currentPE);sawFirstUpdate=false;break;case INPUT_TYPE.SCROLL_UPDATE:if(currentPE){if(currentPE.isNear(event,INPUT_MERGE_THRESHOLD_MS)&&(currentPE.irType===ProtoExpectation.ANIMATION_TYPE||!sawFirstUpdate)){currentPE.pushEvent(event);sawFirstUpdate=true;}else{currentPE=new ProtoExpectation(ProtoExpectation.ANIMATION_TYPE,SCROLL_IR_NAME);currentPE.pushEvent(event);protoExpectations.push(currentPE);}}else{currentPE=new ProtoExpectation(ProtoExpectation.ANIMATION_TYPE,SCROLL_IR_NAME);currentPE.pushEvent(event);protoExpectations.push(currentPE);}break;case INPUT_TYPE.SCROLL_END:if(!currentPE){console.error('ScrollEnd without ScrollUpdate? '+'File a bug with this trace!');var pe=new ProtoExpectation(ProtoExpectation.IGNORED_TYPE);pe.pushEvent(event);protoExpectations.push(pe);break;}currentPE.pushEvent(event);break;}});return protoExpectations;}function handleVideoAnimations(modelHelper,sortedInputEvents){var events=[];for(var pid in modelHelper.rendererHelpers){for(var asyncSlice of modelHelper.rendererHelpers[pid].mainThread.asyncSliceGroup.slices){if(asyncSlice.title===PLAYBACK_EVENT_TITLE)events.push(asyncSlice);}}events.sort(tr.importer.compareEvents);var protoExpectations=[];for(var event of events){var currentPE=new ProtoExpectation(ProtoExpectation.ANIMATION_TYPE,VIDEO_IR_NAME);currentPE.start=event.start;currentPE.end=event.end;currentPE.pushEvent(event);protoExpectations.push(currentPE);}return protoExpectations;}function handleCSSAnimations(modelHelper,sortedInputEvents){var animationEvents=modelHelper.browserHelper.getAllAsyncSlicesMatching(function(event){return event.title===CSS_ANIMATION_TITLE&&event.isTopLevel&&event.duration>0;});var animationRanges=[];function pushAnimationRange(start,end,animation){var range=tr.b.Range.fromExplicitRange(start,end);range.animation=animation;animationRanges.push(range);}animationEvents.forEach(function(animation){if(animation.subSlices.length===0){pushAnimationRange(animation.start,animation.end,animation);}else{var start=undefined;animation.subSlices.forEach(function(sub){if(sub.args.data.state==='running'&&start===undefined){start=sub.start;}else if(sub.args.data.state==='paused'||sub.args.data.state==='idle'||sub.args.data.state==='finished'){if(start===undefined){start=modelHelper.model.bounds.min;}pushAnimationRange(start,sub.start,animation);start=undefined;}});if(start!==undefined)pushAnimationRange(start,animation.end,animation);}});return animationRanges.map(function(range){var protoExpectation=new ProtoExpectation(ProtoExpectation.ANIMATION_TYPE,CSS_IR_NAME);protoExpectation.start=range.min;protoExpectation.end=range.max;protoExpectation.associatedEvents.push(range.animation);return protoExpectation;});}function findWebGLEvents(modelHelper,mailboxEvents,animationEvents){for(var event of modelHelper.model.getDescendantEvents()){if(event.title==='DrawingBuffer::prepareMailbox')mailboxEvents.push(event);else if(event.title==='PageAnimator::serviceScriptedAnimations')animationEvents.push(event);}}function findMailboxEventsNearAnimationEvents(mailboxEvents,animationEvents){if(animationEvents.length===0)return[];mailboxEvents.sort(compareEvents);animationEvents.sort(compareEvents);var animationIterator=animationEvents[Symbol.iterator]();var animationEvent=animationIterator.next().value;var filteredEvents=[];for(var event of mailboxEvents){while(animationEvent&&animationEvent.start<event.start-ANIMATION_MERGE_THRESHOLD_MS)animationEvent=animationIterator.next().value;if(!animationEvent)break;if(animationEvent.start<event.start+ANIMATION_MERGE_THRESHOLD_MS)filteredEvents.push(event);}return filteredEvents;}function createProtoExpectationsFromMailboxEvents(mailboxEvents){var protoExpectations=[];var currentPE=undefined;for(var event of mailboxEvents){if(currentPE===undefined||!currentPE.isNear(event,ANIMATION_MERGE_THRESHOLD_MS)){currentPE=new ProtoExpectation(ProtoExpectation.ANIMATION_TYPE,WEBGL_IR_NAME);currentPE.pushEvent(event);protoExpectations.push(currentPE);}else{currentPE.pushEvent(event);}}return protoExpectations;}function handleWebGLAnimations(modelHelper,sortedInputEvents){var prepareMailboxEvents=[];var scriptedAnimationEvents=[];findWebGLEvents(modelHelper,prepareMailboxEvents,scriptedAnimationEvents);var webGLMailboxEvents=findMailboxEventsNearAnimationEvents(prepareMailboxEvents,scriptedAnimationEvents);return createProtoExpectationsFromMailboxEvents(webGLMailboxEvents);}function postProcessProtoExpectations(modelHelper,protoExpectations){protoExpectations=findFrameEventsForAnimations(modelHelper,protoExpectations);protoExpectations=mergeIntersectingResponses(protoExpectations);protoExpectations=mergeIntersectingAnimations(protoExpectations);protoExpectations=fixResponseAnimationStarts(protoExpectations);protoExpectations=fixTapResponseTouchAnimations(protoExpectations);return protoExpectations;}function mergeIntersectingResponses(protoExpectations){var newPEs=[];while(protoExpectations.length){var pe=protoExpectations.shift();newPEs.push(pe);if(pe.irType!==ProtoExpectation.RESPONSE_TYPE)continue;for(var i=0;i<protoExpectations.length;++i){var otherPE=protoExpectations[i];if(otherPE.irType!==pe.irType)continue;if(!otherPE.intersects(pe))continue;var typeNames=pe.associatedEvents.map(function(event){return event.typeName;});if(otherPE.containsTypeNames(typeNames))continue;pe.merge(otherPE);protoExpectations.splice(i,1);--i;}}return newPEs;}function mergeIntersectingAnimations(protoExpectations){var newPEs=[];while(protoExpectations.length){var pe=protoExpectations.shift();newPEs.push(pe);if(pe.irType!==ProtoExpectation.ANIMATION_TYPE)continue;var isCSS=pe.containsSliceTitle(CSS_ANIMATION_TITLE);var isFling=pe.containsTypeNames([INPUT_TYPE.FLING_START]);var isVideo=pe.containsTypeNames([VIDEO_IR_NAME]);for(var i=0;i<protoExpectations.length;++i){var otherPE=protoExpectations[i];if(otherPE.irType!==pe.irType)continue;if(isCSS!=otherPE.containsSliceTitle(CSS_ANIMATION_TITLE))continue;if(isCSS){if(!pe.isNear(otherPE,ANIMATION_MERGE_THRESHOLD_MS))continue;}else if(!otherPE.intersects(pe)){continue;}if(isFling!==otherPE.containsTypeNames([INPUT_TYPE.FLING_START]))continue;if(isVideo!==otherPE.containsTypeNames([VIDEO_IR_NAME]))continue;pe.merge(otherPE);protoExpectations.splice(i,1);--i;}}return newPEs;}function fixResponseAnimationStarts(protoExpectations){protoExpectations.forEach(function(ape){if(ape.irType!==ProtoExpectation.ANIMATION_TYPE)return;protoExpectations.forEach(function(rpe){if(rpe.irType!==ProtoExpectation.RESPONSE_TYPE)return;if(!ape.containsTimestampInclusive(rpe.end))return;if(ape.containsTimestampInclusive(rpe.start))return;ape.start=rpe.end;});});return protoExpectations;}function fixTapResponseTouchAnimations(protoExpectations){function isTapResponse(pe){return pe.irType===ProtoExpectation.RESPONSE_TYPE&&pe.containsTypeNames([INPUT_TYPE.TAP]);}function isTouchAnimation(pe){return pe.irType===ProtoExpectation.ANIMATION_TYPE&&pe.containsTypeNames([INPUT_TYPE.TOUCH_MOVE])&&!pe.containsTypeNames([INPUT_TYPE.SCROLL_UPDATE,INPUT_TYPE.PINCH_UPDATE]);}var newPEs=[];while(protoExpectations.length){var pe=protoExpectations.shift();newPEs.push(pe);var peIsTapResponse=isTapResponse(pe);var peIsTouchAnimation=isTouchAnimation(pe);if(!peIsTapResponse&&!peIsTouchAnimation)continue;for(var i=0;i<protoExpectations.length;++i){var otherPE=protoExpectations[i];if(!otherPE.intersects(pe))continue;if(peIsTapResponse&&!isTouchAnimation(otherPE))continue;if(peIsTouchAnimation&&!isTapResponse(otherPE))continue;pe.irType=ProtoExpectation.RESPONSE_TYPE;pe.merge(otherPE);protoExpectations.splice(i,1);--i;}}return newPEs;}function findFrameEventsForAnimations(modelHelper,protoExpectations){var newPEs=[];var frameEventsByPid=getSortedFrameEventsByProcess(modelHelper);for(var pe of protoExpectations){if(pe.irType!==ProtoExpectation.ANIMATION_TYPE){newPEs.push(pe);continue;}var frameEvents=[];for(var pid of Object.keys(modelHelper.rendererHelpers)){var range=tr.b.Range.fromExplicitRange(pe.start,pe.end);frameEvents.push.apply(frameEvents,range.filterArray(frameEventsByPid[pid],e=>e.start));}if(frameEvents.length===0&&!pe.names.has(WEBGL_IR_NAME)){pe.irType=ProtoExpectation.IGNORED_TYPE;newPEs.push(pe);continue;}pe.associatedEvents.addEventSet(frameEvents);newPEs.push(pe);}return newPEs;}function checkAllInputEventsHandled(sortedInputEvents,protoExpectations){var handledEvents=[];protoExpectations.forEach(function(protoExpectation){protoExpectation.associatedEvents.forEach(function(event){if(event.title===CSS_ANIMATION_TITLE&&event.subSlices.length>0)return;if(handledEvents.indexOf(event)>=0&&event.title!==tr.model.helpers.IMPL_RENDERING_STATS){console.error('double-handled event',event.typeName,parseInt(event.start),parseInt(event.end),protoExpectation);return;}handledEvents.push(event);});});sortedInputEvents.forEach(function(event){if(handledEvents.indexOf(event)<0){console.error('UNHANDLED INPUT EVENT!',event.typeName,parseInt(event.start),parseInt(event.end));}});}function findInputExpectations(modelHelper){var sortedInputEvents=getSortedInputEvents(modelHelper);var protoExpectations=findProtoExpectations(modelHelper,sortedInputEvents);protoExpectations=postProcessProtoExpectations(modelHelper,protoExpectations);checkAllInputEventsHandled(sortedInputEvents,protoExpectations);var irs=[];protoExpectations.forEach(function(protoExpectation){var ir=protoExpectation.createInteractionRecord(modelHelper.model);if(ir)irs.push(ir);});return irs;}return{findInputExpectations:findInputExpectations,compareEvents:compareEvents,CSS_ANIMATION_TITLE:CSS_ANIMATION_TITLE};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/range_utils.js":54,"../extras/chrome/cc/input_latency_async_slice.js":68,"./proto_expectation.js":83}],79:[function(require,module,exports){(function(global){"use strict";require("../model/user_model/load_expectation.js");'use strict';global.tr.exportTo('tr.importer',function(){var NAVIGATION_START='NavigationTiming navigationStart';var FIRST_CONTENTFUL_PAINT_TITLE='firstContentfulPaint';function findLoadExpectations(modelHelper){var events=[];for(var event of modelHelper.model.getDescendantEvents()){if(event.title===NAVIGATION_START||event.title===FIRST_CONTENTFUL_PAINT_TITLE)events.push(event);}events.sort(tr.importer.compareEvents);var loads=[];var startEvent=undefined;for(var event of events){if(event.title===NAVIGATION_START){startEvent=event;}else if(event.title===FIRST_CONTENTFUL_PAINT_TITLE){if(startEvent){loads.push(new tr.model.um.LoadExpectation(modelHelper.model,tr.model.um.LOAD_SUBTYPE_NAMES.SUCCESSFUL,startEvent.start,event.start-startEvent.start));startEvent=undefined;}}}if(startEvent){loads.push(new tr.model.um.LoadExpectation(modelHelper.model,tr.model.um.LOAD_SUBTYPE_NAMES.SUCCESSFUL,startEvent.start,modelHelper.model.bounds.max-startEvent.start));}return loads;}return{findLoadExpectations:findLoadExpectations};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../model/user_model/load_expectation.js":169}],80:[function(require,module,exports){(function(global){"use strict";require("../model/user_model/startup_expectation.js");'use strict';global.tr.exportTo('tr.importer',function(){function getAllFrameEvents(modelHelper){var frameEvents=[];frameEvents.push.apply(frameEvents,modelHelper.browserHelper.getFrameEventsInRange(tr.model.helpers.IMPL_FRAMETIME_TYPE,modelHelper.model.bounds));tr.b.iterItems(modelHelper.rendererHelpers,function(pid,renderer){frameEvents.push.apply(frameEvents,renderer.getFrameEventsInRange(tr.model.helpers.IMPL_FRAMETIME_TYPE,modelHelper.model.bounds));});return frameEvents.sort(tr.importer.compareEvents);}function getStartupEvents(modelHelper){function isStartupSlice(slice){return slice.title==='BrowserMainLoop::CreateThreads';}var events=modelHelper.browserHelper.getAllAsyncSlicesMatching(isStartupSlice);var deduper=new tr.model.EventSet();events.forEach(function(event){var sliceGroup=event.parentContainer.sliceGroup;var slice=sliceGroup&&sliceGroup.findFirstSlice();if(slice)deduper.push(slice);});return deduper.toArray();}function findStartupExpectations(modelHelper){var openingEvents=getStartupEvents(modelHelper);var closingEvents=getAllFrameEvents(modelHelper);var startups=[];openingEvents.forEach(function(openingEvent){closingEvents.forEach(function(closingEvent){if(openingEvent.closingEvent)return;if(closingEvent.openingEvent)return;if(closingEvent.start<=openingEvent.start)return;if(openingEvent.parentContainer.parent.pid!==closingEvent.parentContainer.parent.pid)return;openingEvent.closingEvent=closingEvent;closingEvent.openingEvent=openingEvent;var se=new tr.model.um.StartupExpectation(modelHelper.model,openingEvent.start,closingEvent.end-openingEvent.start);se.associatedEvents.push(openingEvent);se.associatedEvents.push(closingEvent);startups.push(se);});});return startups;}return{findStartupExpectations:findStartupExpectations};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../model/user_model/startup_expectation.js":171}],81:[function(require,module,exports){(function(global){"use strict";require("../base/base.js");require("../base/timing.js");require("./empty_importer.js");require("./importer.js");require("./user_model_builder.js");require("../ui/base/overlay.js");'use strict';global.tr.exportTo('tr.importer',function(){var Timing=tr.b.Timing;function ImportOptions(){this.shiftWorldToZero=true;this.pruneEmptyContainers=true;this.showImportWarnings=true;this.trackDetailedModelStats=false;this.customizeModelCallback=undefined;var auditorTypes=tr.c.Auditor.getAllRegisteredTypeInfos();this.auditorConstructors=auditorTypes.map(function(typeInfo){return typeInfo.constructor;});}function Import(model,opt_options){if(model===undefined)throw new Error('Must provide model to import into.');this.importing_=false;this.importOptions_=opt_options||new ImportOptions();this.model_=model;this.model_.importOptions=this.importOptions_;}Import.prototype={__proto__:Object.prototype,importTraces:function(traces){var progressMeter={update:function(msg){}};tr.b.Task.RunSynchronously(this.createImportTracesTask(progressMeter,traces));},importTracesWithProgressDialog:function(traces){if(tr.isHeadless)throw new Error('Cannot use this method in headless mode.');var overlay=tr.ui.b.Overlay();overlay.title='Importing...';overlay.userCanClose=false;overlay.msgEl=document.createElement('div');Polymer.dom(overlay).appendChild(overlay.msgEl);overlay.msgEl.style.margin='20px';overlay.update=function(msg){Polymer.dom(this.msgEl).textContent=msg;};overlay.visible=true;var promise=tr.b.Task.RunWhenIdle(this.createImportTracesTask(overlay,traces));promise.then(function(){overlay.visible=false;},function(err){overlay.visible=false;});return promise;},createImportTracesTask:function(progressMeter,traces){if(this.importing_)throw new Error('Already importing.');this.importing_=true;var importTask=new tr.b.Task(function prepareImport(){progressMeter.update('I will now import your traces for you...');},this);var lastTask=importTask;var importers=[];lastTask=lastTask.timedAfter('TraceImport',function createImports(){traces=traces.slice(0);progressMeter.update('Creating importers...');for(var i=0;i<traces.length;++i)importers.push(this.createImporter_(traces[i]));for(var i=0;i<importers.length;i++){var subtraces=importers[i].extractSubtraces();for(var j=0;j<subtraces.length;j++){try{traces.push(subtraces[j]);importers.push(this.createImporter_(subtraces[j]));}catch(error){console.warn(error.name+': '+error.message);continue;}}}if(traces.length&&!this.hasEventDataDecoder_(importers)){throw new Error('Could not find an importer for the provided eventData.');}importers.sort(function(x,y){return x.importPriority-y.importPriority;});},this);lastTask=lastTask.timedAfter('TraceImport',function importClockSyncMarkers(task){importers.forEach(function(importer,index){task.subTask(Timing.wrapNamedFunction('TraceImport',importer.importerName,function runImportClockSyncMarkersOnOneImporter(){progressMeter.update('Importing clock sync markers '+(index+1)+' of '+importers.length);importer.importClockSyncMarkers();}),this);},this);},this);lastTask=lastTask.timedAfter('TraceImport',function runImport(task){importers.forEach(function(importer,index){task.subTask(Timing.wrapNamedFunction('TraceImport',importer.importerName,function runImportEventsOnOneImporter(){progressMeter.update('Importing '+(index+1)+' of '+importers.length);importer.importEvents();}),this);},this);},this);if(this.importOptions_.customizeModelCallback){lastTask=lastTask.timedAfter('TraceImport',function runCustomizeCallbacks(task){this.importOptions_.customizeModelCallback(this.model_);},this);}lastTask=lastTask.timedAfter('TraceImport',function importSampleData(task){importers.forEach(function(importer,index){progressMeter.update('Importing sample data '+(index+1)+'/'+importers.length);importer.importSampleData();},this);},this);lastTask=lastTask.timedAfter('TraceImport',function runAutoclosers(){progressMeter.update('Autoclosing open slices...');this.model_.autoCloseOpenSlices();this.model_.createSubSlices();},this);lastTask=lastTask.timedAfter('TraceImport',function finalizeImport(task){importers.forEach(function(importer,index){progressMeter.update('Finalizing import '+(index+1)+'/'+importers.length);importer.finalizeImport();},this);},this);lastTask=lastTask.timedAfter('TraceImport',function runPreinits(){progressMeter.update('Initializing objects (step 1/2)...');this.model_.preInitializeObjects();},this);if(this.importOptions_.pruneEmptyContainers){lastTask=lastTask.timedAfter('TraceImport',function runPruneEmptyContainers(){progressMeter.update('Pruning empty containers...');this.model_.pruneEmptyContainers();},this);}lastTask=lastTask.timedAfter('TraceImport',function runMergeKernelWithuserland(){progressMeter.update('Merging kernel with userland...');this.model_.mergeKernelWithUserland();},this);var auditors=[];lastTask=lastTask.timedAfter('TraceImport',function createAuditorsAndRunAnnotate(){progressMeter.update('Adding arbitrary data to model...');auditors=this.importOptions_.auditorConstructors.map(function(auditorConstructor){return new auditorConstructor(this.model_);},this);auditors.forEach(function(auditor){auditor.runAnnotate();auditor.installUserFriendlyCategoryDriverIfNeeded();});},this);lastTask=lastTask.timedAfter('TraceImport',function computeWorldBounds(){progressMeter.update('Computing final world bounds...');this.model_.computeWorldBounds(this.importOptions_.shiftWorldToZero);},this);lastTask=lastTask.timedAfter('TraceImport',function buildFlowEventIntervalTree(){progressMeter.update('Building flow event map...');this.model_.buildFlowEventIntervalTree();},this);lastTask=lastTask.timedAfter('TraceImport',function joinRefs(){progressMeter.update('Joining object refs...');this.model_.joinRefs();},this);lastTask=lastTask.timedAfter('TraceImport',function cleanupUndeletedObjects(){progressMeter.update('Cleaning up undeleted objects...');this.model_.cleanupUndeletedObjects();},this);lastTask=lastTask.timedAfter('TraceImport',function sortMemoryDumps(){progressMeter.update('Sorting memory dumps...');this.model_.sortMemoryDumps();},this);lastTask=lastTask.timedAfter('TraceImport',function finalizeMemoryGraphs(){progressMeter.update('Finalizing memory dump graphs...');this.model_.finalizeMemoryGraphs();},this);lastTask=lastTask.timedAfter('TraceImport',function initializeObjects(){progressMeter.update('Initializing objects (step 2/2)...');this.model_.initializeObjects();},this);lastTask=lastTask.timedAfter('TraceImport',function buildEventIndices(){progressMeter.update('Building event indices...');this.model_.buildEventIndices();},this);lastTask=lastTask.timedAfter('TraceImport',function buildUserModel(){progressMeter.update('Building UserModel...');var userModelBuilder=new tr.importer.UserModelBuilder(this.model_);userModelBuilder.buildUserModel();},this);lastTask=lastTask.timedAfter('TraceImport',function sortExpectations(){progressMeter.update('Sorting user expectations...');this.model_.userModel.sortExpectations();},this);lastTask=lastTask.timedAfter('TraceImport',function runAudits(){progressMeter.update('Running auditors...');auditors.forEach(function(auditor){auditor.runAudit();});},this);lastTask=lastTask.timedAfter('TraceImport',function sortAlerts(){progressMeter.update('Updating alerts...');this.model_.sortAlerts();},this);lastTask=lastTask.timedAfter('TraceImport',function lastUpdateBounds(){progressMeter.update('Update bounds...');this.model_.updateBounds();},this);lastTask=lastTask.timedAfter('TraceImport',function addModelWarnings(){progressMeter.update('Looking for warnings...');if(!this.model_.isTimeHighResolution){this.model_.importWarning({type:'low_resolution_timer',message:'Trace time is low resolution, trace may be unusable.',showToUser:true});}},this);lastTask.after(function(){this.importing_=false;},this);return importTask;},createImporter_:function(eventData){var importerConstructor=tr.importer.Importer.findImporterFor(eventData);if(!importerConstructor){throw new Error('Couldn\'t create an importer for the provided '+'eventData.');}return new importerConstructor(this.model_,eventData);},hasEventDataDecoder_:function(importers){for(var i=0;i<importers.length;++i){if(!importers[i].isTraceDataContainer())return true;}return false;}};return{ImportOptions:ImportOptions,Import:Import};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/base.js":34,"../base/timing.js":62,"../ui/base/overlay.js":180,"./empty_importer.js":77,"./importer.js":82,"./user_model_builder.js":84}],82:[function(require,module,exports){(function(global){"use strict";require("../base/base.js");require("../base/extension_registry.js");'use strict';global.tr.exportTo('tr.importer',function(){function Importer(){}Importer.prototype={__proto__:Object.prototype,get importerName(){return'Importer';},isTraceDataContainer:function(){return false;},extractSubtraces:function(){return[];},importClockSyncMarkers:function(){},importEvents:function(){},importSampleData:function(){},finalizeImport:function(){}};var options=new tr.b.ExtensionRegistryOptions(tr.b.BASIC_REGISTRY_MODE);options.defaultMetadata={};options.mandatoryBaseClass=Importer;tr.b.decorateExtensionRegistry(Importer,options);Importer.findImporterFor=function(eventData){var typeInfo=Importer.findTypeInfoMatching(function(ti){return ti.constructor.canImport(eventData);});if(typeInfo)return typeInfo.constructor;return undefined;};return{Importer:Importer};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/base.js":34,"../base/extension_registry.js":41}],83:[function(require,module,exports){(function(global){"use strict";require("../base/base.js");require("../base/range_utils.js");require("../core/auditor.js");require("../model/event_info.js");require("../model/user_model/animation_expectation.js");require("../model/user_model/response_expectation.js");'use strict';global.tr.exportTo('tr.importer',function(){function ProtoExpectation(irType,name){this.irType=irType;this.names=new Set(name?[name]:undefined);this.start=Infinity;this.end=-Infinity;this.associatedEvents=new tr.model.EventSet();this.isAnimationBegin=false;}ProtoExpectation.RESPONSE_TYPE='r';ProtoExpectation.ANIMATION_TYPE='a';ProtoExpectation.IGNORED_TYPE='ignored';ProtoExpectation.prototype={get isValid(){return this.end>this.start;},containsTypeNames:function(typeNames){return this.associatedEvents.some(x=>typeNames.indexOf(x.typeName)>=0);},containsSliceTitle:function(title){return this.associatedEvents.some(x=>title===x.title);},createInteractionRecord:function(model){if(!this.isValid){console.error('Invalid ProtoExpectation: '+this.debug()+' File a bug with this trace!');return undefined;}var initiatorTitles=[];this.names.forEach(function(name){initiatorTitles.push(name);});initiatorTitles=initiatorTitles.sort().join(',');var duration=this.end-this.start;var ir=undefined;switch(this.irType){case ProtoExpectation.RESPONSE_TYPE:ir=new tr.model.um.ResponseExpectation(model,initiatorTitles,this.start,duration,this.isAnimationBegin);break;case ProtoExpectation.ANIMATION_TYPE:ir=new tr.model.um.AnimationExpectation(model,initiatorTitles,this.start,duration);break;}if(!ir)return undefined;ir.sourceEvents.addEventSet(this.associatedEvents);function pushAssociatedEvents(event){ir.associatedEvents.push(event);if(event.associatedEvents)ir.associatedEvents.addEventSet(event.associatedEvents);}this.associatedEvents.forEach(function(event){pushAssociatedEvents(event);if(event.subSlices)event.subSlices.forEach(pushAssociatedEvents);});return ir;},merge:function(other){other.names.forEach(function(name){this.names.add(name);}.bind(this));this.associatedEvents.addEventSet(other.associatedEvents);this.start=Math.min(this.start,other.start);this.end=Math.max(this.end,other.end);if(other.isAnimationBegin)this.isAnimationBegin=true;},pushEvent:function(event){this.start=Math.min(this.start,event.start);this.end=Math.max(this.end,event.end);this.associatedEvents.push(event);},containsTimestampInclusive:function(timestamp){return this.start<=timestamp&&timestamp<=this.end;},intersects:function(other){return other.start<this.end&&other.end>this.start;},isNear:function(event,threshold){return this.end+threshold>event.start;},debug:function(){var debugString=this.irType+'(';debugString+=parseInt(this.start)+' ';debugString+=parseInt(this.end);this.associatedEvents.forEach(function(event){debugString+=' '+event.typeName;});return debugString+')';}};return{ProtoExpectation:ProtoExpectation};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/base.js":34,"../base/range_utils.js":54,"../core/auditor.js":66,"../model/event_info.js":124,"../model/user_model/animation_expectation.js":167,"../model/user_model/response_expectation.js":170}],84:[function(require,module,exports){(function(global){"use strict";require("../base/base.js");require("../base/range_utils.js");require("../core/auditor.js");require("../extras/chrome/cc/input_latency_async_slice.js");require("./find_input_expectations.js");require("./find_load_expectations.js");require("./find_startup_expectations.js");require("../model/event_info.js");require("../model/ir_coverage.js");require("../model/user_model/idle_expectation.js");'use strict';global.tr.exportTo('tr.importer',function(){var INSIGNIFICANT_MS=1;function UserModelBuilder(model){this.model=model;this.modelHelper=model.getOrCreateHelper(tr.model.helpers.ChromeModelHelper);};UserModelBuilder.supportsModelHelper=function(modelHelper){return modelHelper.browserHelper!==undefined;};UserModelBuilder.prototype={buildUserModel:function(){if(!this.modelHelper||!this.modelHelper.browserHelper)return;var expectations=undefined;try{expectations=this.findUserExpectations();}catch(error){this.model.importWarning({type:'UserModelBuilder',message:error,showToUser:true});return;}expectations.forEach(function(expectation){this.model.userModel.expectations.push(expectation);},this);},findUserExpectations:function(){var expectations=[];expectations.push.apply(expectations,tr.importer.findStartupExpectations(this.modelHelper));expectations.push.apply(expectations,tr.importer.findLoadExpectations(this.modelHelper));expectations.push.apply(expectations,tr.importer.findInputExpectations(this.modelHelper));expectations.push.apply(expectations,this.findIdleExpectations(expectations));this.collectUnassociatedEvents_(expectations);return expectations;},collectUnassociatedEvents_:function(rirs){var vacuumIRs=[];rirs.forEach(function(ir){if(ir instanceof tr.model.um.IdleExpectation||ir instanceof tr.model.um.LoadExpectation||ir instanceof tr.model.um.StartupExpectation)vacuumIRs.push(ir);});if(vacuumIRs.length===0)return;var allAssociatedEvents=tr.model.getAssociatedEvents(rirs);var unassociatedEvents=tr.model.getUnassociatedEvents(this.model,allAssociatedEvents);unassociatedEvents.forEach(function(event){if(!(event instanceof tr.model.ThreadSlice))return;if(!event.isTopLevel)return;for(var iri=0;iri<vacuumIRs.length;++iri){var ir=vacuumIRs[iri];if(event.start>=ir.start&&event.start<ir.end){ir.associatedEvents.addEventSet(event.entireHierarchy);return;}}});},findIdleExpectations:function(otherIRs){if(this.model.bounds.isEmpty)return;var emptyRanges=tr.b.findEmptyRangesBetweenRanges(tr.b.convertEventsToRanges(otherIRs),this.model.bounds);var irs=[];var model=this.model;emptyRanges.forEach(function(range){if(range.max<range.min+INSIGNIFICANT_MS)return;irs.push(new tr.model.um.IdleExpectation(model,range.min,range.max-range.min));});return irs;}};function createCustomizeModelLinesFromModel(model){var modelLines=[];modelLines.push('      audits.addEvent(model.browserMain,');modelLines.push('          {title: \'model start\', start: 0, end: 1});');var typeNames={};for(var typeName in tr.e.cc.INPUT_EVENT_TYPE_NAMES){typeNames[tr.e.cc.INPUT_EVENT_TYPE_NAMES[typeName]]=typeName;}var modelEvents=new tr.model.EventSet();model.userModel.expectations.forEach(function(ir,index){modelEvents.addEventSet(ir.sourceEvents);});modelEvents=modelEvents.toArray();modelEvents.sort(tr.importer.compareEvents);modelEvents.forEach(function(event){var startAndEnd='start: '+parseInt(event.start)+', '+'end: '+parseInt(event.end)+'});';if(event instanceof tr.e.cc.InputLatencyAsyncSlice){modelLines.push('      audits.addInputEvent(model, INPUT_TYPE.'+typeNames[event.typeName]+',');}else if(event.title==='RenderFrameImpl::didCommitProvisionalLoad'){modelLines.push('      audits.addCommitLoadEvent(model,');}else if(event.title==='InputHandlerProxy::HandleGestureFling::started'){modelLines.push('      audits.addFlingAnimationEvent(model,');}else if(event.title===tr.model.helpers.IMPL_RENDERING_STATS){modelLines.push('      audits.addFrameEvent(model,');}else if(event.title===tr.importer.CSS_ANIMATION_TITLE){modelLines.push('      audits.addEvent(model.rendererMain, {');modelLines.push('        title: \'Animation\', '+startAndEnd);return;}else{throw'You must extend createCustomizeModelLinesFromModel()'+'to support this event:\n'+event.title+'\n';}modelLines.push('          {'+startAndEnd);});modelLines.push('      audits.addEvent(model.browserMain,');modelLines.push('          {'+'title: \'model end\', '+'start: '+(parseInt(model.bounds.max)-1)+', '+'end: '+parseInt(model.bounds.max)+'});');return modelLines;}function createExpectedIRLinesFromModel(model){var expectedLines=[];var irCount=model.userModel.expectations.length;model.userModel.expectations.forEach(function(ir,index){var irString='      {';irString+='title: \''+ir.title+'\', ';irString+='start: '+parseInt(ir.start)+', ';irString+='end: '+parseInt(ir.end)+', ';irString+='eventCount: '+ir.sourceEvents.length;irString+='}';if(index<irCount-1)irString+=',';expectedLines.push(irString);});return expectedLines;}function createIRFinderTestCaseStringFromModel(model){var filename=window.location.hash.substr(1);var testName=filename.substr(filename.lastIndexOf('/')+1);testName=testName.substr(0,testName.indexOf('.'));try{var testLines=[];testLines.push('  /*');testLines.push('    This test was generated from');testLines.push('    '+filename+'');testLines.push('   */');testLines.push('  test(\''+testName+'\', function() {');testLines.push('    var verifier = new UserExpectationVerifier();');testLines.push('    verifier.customizeModelCallback = function(model) {');testLines.push.apply(testLines,createCustomizeModelLinesFromModel(model));testLines.push('    };');testLines.push('    verifier.expectedIRs = [');testLines.push.apply(testLines,createExpectedIRLinesFromModel(model));testLines.push('    ];');testLines.push('    verifier.verify();');testLines.push('  });');return testLines.join('\n');}catch(error){return error;}}return{UserModelBuilder:UserModelBuilder,createIRFinderTestCaseStringFromModel:createIRFinderTestCaseStringFromModel};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/base.js":34,"../base/range_utils.js":54,"../core/auditor.js":66,"../extras/chrome/cc/input_latency_async_slice.js":68,"../model/event_info.js":124,"../model/ir_coverage.js":137,"../model/user_model/idle_expectation.js":168,"./find_input_expectations.js":78,"./find_load_expectations.js":79,"./find_startup_expectations.js":80}],85:[function(require,module,exports){"use strict";require("./importer/import.js");require("./model/model.js");require("./extras/lean_config.js");require("./metrics/all_metrics.js");},{"./extras/lean_config.js":75,"./importer/import.js":81,"./metrics/all_metrics.js":86,"./model/model.js":141}],86:[function(require,module,exports){"use strict";require("./blink/gc_metric.js");require("./cpu_process_metric.js");require("./sample_metric.js");require("./system_health/clock_sync_latency_metric.js");require("./system_health/hazard_metric.js");require("./system_health/loading_metric.js");require("./system_health/memory_metric.js");require("./system_health/power_metric.js");require("./system_health/responsiveness_metric.js");require("./system_health/system_health_metrics.js");require("./system_health/webview_startup_metric.js");require("./tracing_metric.js");require("./v8/execution_metric.js");require("./v8/gc_metric.js");require("./v8/v8_metrics.js");},{"./blink/gc_metric.js":87,"./cpu_process_metric.js":88,"./sample_metric.js":90,"./system_health/clock_sync_latency_metric.js":91,"./system_health/hazard_metric.js":93,"./system_health/loading_metric.js":94,"./system_health/memory_metric.js":96,"./system_health/power_metric.js":97,"./system_health/responsiveness_metric.js":98,"./system_health/system_health_metrics.js":99,"./system_health/webview_startup_metric.js":101,"./tracing_metric.js":102,"./v8/execution_metric.js":103,"./v8/gc_metric.js":104,"./v8/v8_metrics.js":106}],87:[function(require,module,exports){(function(global){"use strict";require("../../base/range.js");require("../../base/unit.js");require("../metric_registry.js");require("../v8/utils.js");require("../../value/histogram.js");'use strict';global.tr.exportTo('tr.metrics.blink',function(){var BLINK_GC_EVENTS={'BlinkGCMarking':'blink-gc-marking','ThreadState::completeSweep':'blink-gc-complete-sweep','ThreadState::performIdleLazySweep':'blink-gc-idle-lazy-sweep'};function isBlinkGarbageCollectionEvent(event){return event.title in BLINK_GC_EVENTS;}function blinkGarbageCollectionEventName(event){return BLINK_GC_EVENTS[event.title];}function blinkGcMetric(values,model){addDurationOfTopEvents(values,model);addTotalDurationOfTopEvents(values,model);addIdleTimesOfTopEvents(values,model);addTotalIdleTimesOfTopEvents(values,model);}tr.metrics.MetricRegistry.register(blinkGcMetric);var timeDurationInMs_smallerIsBetter=tr.b.Unit.byName.timeDurationInMs_smallerIsBetter;var percentage_biggerIsBetter=tr.b.Unit.byName.normalizedPercentage_biggerIsBetter;var CUSTOM_BOUNDARIES=tr.v.HistogramBinBoundaries.createLinear(0,20,200).addExponentialBins(200,100);function createNumericForTopEventTime(name){var n=new tr.v.Histogram(name,timeDurationInMs_smallerIsBetter,CUSTOM_BOUNDARIES);n.customizeSummaryOptions({avg:true,count:true,max:true,min:false,std:true,sum:true,percentile:[0.90]});return n;}function createNumericForIdleTime(name){var n=new tr.v.Histogram(name,timeDurationInMs_smallerIsBetter,CUSTOM_BOUNDARIES);n.customizeSummaryOptions({avg:true,count:false,max:true,min:false,std:false,sum:true,percentile:[]});return n;}function createPercentage(name,numerator,denominator){var histogram=new tr.v.Histogram(name,percentage_biggerIsBetter);if(denominator===0)histogram.addSample(0);else histogram.addSample(numerator/denominator);return histogram;}function addDurationOfTopEvents(values,model){tr.metrics.v8.utils.groupAndProcessEvents(model,isBlinkGarbageCollectionEvent,blinkGarbageCollectionEventName,function(name,events){var cpuDuration=createNumericForTopEventTime(name);events.forEach(function(event){cpuDuration.addSample(event.cpuDuration);});values.addHistogram(cpuDuration);});}function addTotalDurationOfTopEvents(values,model){tr.metrics.v8.utils.groupAndProcessEvents(model,isBlinkGarbageCollectionEvent,event=>'blink-gc-total',function(name,events){var cpuDuration=createNumericForTopEventTime(name);events.forEach(function(event){cpuDuration.addSample(event.cpuDuration);});values.addHistogram(cpuDuration);});}function addIdleTimesOfTopEvents(values,model){tr.metrics.v8.utils.groupAndProcessEvents(model,isBlinkGarbageCollectionEvent,blinkGarbageCollectionEventName,function(name,events){addIdleTimes(values,model,name,events);});}function addTotalIdleTimesOfTopEvents(values,model){tr.metrics.v8.utils.groupAndProcessEvents(model,isBlinkGarbageCollectionEvent,event=>'blink-gc-total',function(name,events){addIdleTimes(values,model,name,events);});}function addIdleTimes(values,model,name,events){var cpuDuration=createNumericForIdleTime(name+'_cpu');var insideIdle=createNumericForIdleTime(name+'_inside_idle');var outsideIdle=createNumericForIdleTime(name+'_outside_idle');var idleDeadlineOverrun=createNumericForIdleTime(name+'_idle_deadline_overrun');events.forEach(function(event){var idleTask=tr.metrics.v8.utils.findParent(event,tr.metrics.v8.utils.isIdleTask);var inside=0;var overrun=0;if(idleTask){var allottedTime=idleTask['args']['allotted_time_ms'];if(event.duration>allottedTime){overrun=event.duration-allottedTime;inside=event.cpuDuration*allottedTime/event.duration;}else{inside=event.cpuDuration;}}cpuDuration.addSample(event.cpuDuration);insideIdle.addSample(inside);outsideIdle.addSample(event.cpuDuration-inside);idleDeadlineOverrun.addSample(overrun);});values.addHistogram(idleDeadlineOverrun);values.addHistogram(outsideIdle);var percentage=createPercentage(name+'_percentage_idle',insideIdle.sum,cpuDuration.sum);values.addHistogram(percentage);}return{blinkGcMetric:blinkGcMetric};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../../base/range.js":53,"../../base/unit.js":63,"../../value/histogram.js":195,"../metric_registry.js":89,"../v8/utils.js":105}],88:[function(require,module,exports){(function(global){"use strict";var _slicedToArray=function(){function sliceIterator(arr,i){var _arr=[];var _n=true;var _d=false;var _e=undefined;try{for(var _i=arr[Symbol.iterator](),_s;!(_n=(_s=_i.next()).done);_n=true){_arr.push(_s.value);if(i&&_arr.length===i)break;}}catch(err){_d=true;_e=err;}finally{try{if(!_n&&_i["return"])_i["return"]();}finally{if(_d)throw _e;}}return _arr;}return function(arr,i){if(Array.isArray(arr)){return arr;}else if(Symbol.iterator in Object(arr)){return sliceIterator(arr,i);}else{throw new TypeError("Invalid attempt to destructure non-iterable instance");}};}();require("./metric_registry.js");require("../value/histogram.js");'use strict';global.tr.exportTo('tr.metrics.sh',function(){function getCpuSnapshotsFromModel(model){var snapshots=[];for(var pid in model.processes){var snapshotInstances=model.processes[pid].objects.getAllInstancesNamed('CPUSnapshots');if(!snapshotInstances)continue;for(var object of snapshotInstances[0].snapshots)snapshots.push(object.args.processes);}return snapshots;}function getProcessSumsFromSnapshot(snapshot){var processSums=new Map();for(var processData of snapshot){var processName=processData.name;if(!processSums.has(processName))processSums.set(processName,{sum:0.0,paths:new Set()});processSums.get(processName).sum+=parseFloat(processData.pCpu);if(processData.path)processSums.get(processName).paths.add(processData.path);}return processSums;}function buildNumericsFromSnapshots(snapshots){var processNumerics=new Map();for(var snapshot of snapshots){var processSums=getProcessSumsFromSnapshot(snapshot);for(var _ref of processSums.entries()){var _ref2=_slicedToArray(_ref,2);var processName=_ref2[0];var processData=_ref2[1];if(!processNumerics.has(processName)){processNumerics.set(processName,{numeric:new tr.v.Histogram('cpu:percent:'+processName,tr.b.Unit.byName.normalizedPercentage_smallerIsBetter),paths:new Set()});}processNumerics.get(processName).numeric.addSample(processData.sum/100.0);for(var path of processData.paths)processNumerics.get(processName).paths.add(path);}}return processNumerics;}function cpuProcessMetric(values,model){var snapshots=getCpuSnapshotsFromModel(model);var processNumerics=buildNumericsFromSnapshots(snapshots);for(var _ref3 of processNumerics){var _ref4=_slicedToArray(_ref3,2);var processName=_ref4[0];var processData=_ref4[1];var numeric=processData.numeric;var missingSnapshotCount=snapshots.length-numeric.numValues;for(var i=0;i<missingSnapshotCount;i++)numeric.addSample(0);numeric.diagnostics.set('paths',new tr.v.d.Generic([...processData.paths]));values.addHistogram(numeric);}}tr.metrics.MetricRegistry.register(cpuProcessMetric);return{cpuProcessMetric:cpuProcessMetric};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../value/histogram.js":195,"./metric_registry.js":89}],89:[function(require,module,exports){(function(global){"use strict";require("../base/base.js");require("../base/extension_registry.js");require("../base/iteration_helpers.js");'use strict';global.tr.exportTo('tr.metrics',function(){function MetricRegistry(){}var options=new tr.b.ExtensionRegistryOptions(tr.b.BASIC_REGISTRY_MODE);options.defaultMetadata={};tr.b.decorateExtensionRegistry(MetricRegistry,options);MetricRegistry.addEventListener('will-register',function(e){var metric=e.typeInfo.constructor;if(!(metric instanceof Function))throw new Error('Metrics must be functions');if(metric.length<2){throw new Error('Metrics take a ValueSet and a Model and '+'optionally an options dictionary');}});return{MetricRegistry:MetricRegistry};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/base.js":34,"../base/extension_registry.js":41,"../base/iteration_helpers.js":47}],90:[function(require,module,exports){(function(global){"use strict";require("../base/range.js");require("./metric_registry.js");require("../value/histogram.js");'use strict';global.tr.exportTo('tr.metrics',function(){function sampleMetric(values,model){var hist=new tr.v.Histogram('foo',tr.b.Unit.byName.sizeInBytes_smallerIsBetter);hist.addSample(9);hist.addSample(91,{bar:new tr.v.d.Generic({hello:42})});for(var expectation of model.userModel.expectations){if(expectation instanceof tr.model.um.ResponseExpectation){}else if(expectation instanceof tr.model.um.AnimationExpectation){}else if(expectation instanceof tr.model.um.IdleExpectation){}else if(expectation instanceof tr.model.um.LoadExpectation){}}var chromeHelper=model.getOrCreateHelper(tr.model.helpers.ChromeModelHelper);tr.b.iterItems(model.processes,function(pid,process){});values.addHistogram(hist);}tr.metrics.MetricRegistry.register(sampleMetric);return{sampleMetric:sampleMetric};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/range.js":53,"../value/histogram.js":195,"./metric_registry.js":89}],91:[function(require,module,exports){(function(global){"use strict";require("../metric_registry.js");require("./utils.js");require("../../model/model.js");require("../../value/histogram.js");'use strict';global.tr.exportTo('tr.metrics.sh',function(){function syncIsComplete(markers){return markers.length===2;}function syncInvolvesTelemetry(markers){for(var marker of markers)if(marker.domainId===tr.model.ClockDomainId.TELEMETRY)return true;return false;}function clockSyncLatencyMetric(values,model){for(var markers of model.clockSyncManager.markersBySyncId.values()){var latency=undefined;var targetDomain=undefined;if(!syncIsComplete(markers)||!syncInvolvesTelemetry(markers))continue;for(var marker of markers){var domain=marker.domainId;if(domain===tr.model.ClockDomainId.TELEMETRY)latency=marker.endTs-marker.startTs;else targetDomain=domain.toLowerCase();}var hist=new tr.v.Histogram('clock_sync_latency_'+targetDomain,tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,tr.v.HistogramBinBoundaries.createExponential(1e-3,1e3,30));hist.description='Clock sync latency for domain '+targetDomain;hist.addSample(latency);values.addHistogram(hist);}}tr.metrics.MetricRegistry.register(clockSyncLatencyMetric);return{clockSyncLatencyMetric:clockSyncLatencyMetric};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../../model/model.js":141,"../../value/histogram.js":195,"../metric_registry.js":89,"./utils.js":100}],92:[function(require,module,exports){(function(global){"use strict";require("../metric_registry.js");require("../../value/histogram.js");'use strict';global.tr.exportTo('tr.metrics.sh',function(){var CPU_TIME_PERCENTAGE_BOUNDARIES=tr.v.HistogramBinBoundaries.createExponential(0.01,50,200);function cpuTimeMetric(values,model,opt_options){var rangeOfInterest=model.bounds;if(opt_options&&opt_options.rangeOfInterest)rangeOfInterest=opt_options.rangeOfInterest;var allProcessCpuTime=0;for(var pid in model.processes){var process=model.processes[pid];var processCpuTime=0;for(var tid in process.threads){var thread=process.threads[tid];var threadCpuTime=0;thread.sliceGroup.topLevelSlices.forEach(function(slice){if(slice.duration===0)return;if(!slice.cpuDuration)return;var sliceRange=tr.b.Range.fromExplicitRange(slice.start,slice.end);var intersection=rangeOfInterest.findIntersection(sliceRange);var fractionOfSliceInsideRangeOfInterest=intersection.duration/slice.duration;threadCpuTime+=slice.cpuDuration*fractionOfSliceInsideRangeOfInterest;});processCpuTime+=threadCpuTime;}allProcessCpuTime+=processCpuTime;}var normalizedAllProcessCpuTime=0;if(rangeOfInterest.duration>0){normalizedAllProcessCpuTime=allProcessCpuTime/rangeOfInterest.duration;}var unit=tr.b.Unit.byName.normalizedPercentage_smallerIsBetter;var cpuTimeHist=new tr.v.Histogram('cpu_time_percentage',unit,CPU_TIME_PERCENTAGE_BOUNDARIES);cpuTimeHist.description='Percent CPU utilization, normalized against a single core. Can be '+'greater than 100% if machine has multiple cores.';cpuTimeHist.addSample(normalizedAllProcessCpuTime);values.addHistogram(cpuTimeHist);}tr.metrics.MetricRegistry.register(cpuTimeMetric,{supportsRangeOfInterest:true});return{cpuTimeMetric:cpuTimeMetric};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../../value/histogram.js":195,"../metric_registry.js":89}],93:[function(require,module,exports){(function(global){"use strict";require("../metric_registry.js");require("./long_tasks_metric.js");require("../../value/numeric.js");'use strict';global.tr.exportTo('tr.metrics.sh',function(){var MS_PER_S=1000;var RESPONSE_RISK=tr.b.Statistics.LogNormalDistribution.fromMedianAndDiminishingReturns(100/MS_PER_S,50/MS_PER_S);function computeResponsivenessRisk(durationMs){durationMs+=16;return RESPONSE_RISK.computePercentile(durationMs/MS_PER_S);}function perceptualBlendSmallerIsBetter(hazardScore){return Math.exp(hazardScore);}function computeHazardForLongTasksInRangeOnThread(thread,opt_range){var taskHazardScores=[];tr.metrics.sh.iterateLongTopLevelTasksOnThreadInRange(thread,opt_range,function(task){taskHazardScores.push(computeResponsivenessRisk(task.duration));});return tr.b.Statistics.weightedMean(taskHazardScores,perceptualBlendSmallerIsBetter);}function computeHazardForLongTasks(model){var threadHazardScores=[];tr.metrics.sh.iterateRendererMainThreads(model,function(thread){threadHazardScores.push(computeHazardForLongTasksInRangeOnThread(thread));});return tr.b.Statistics.weightedMean(threadHazardScores,perceptualBlendSmallerIsBetter);}function hazardMetric(values,model){var overallHazard=computeHazardForLongTasks(model);if(overallHazard===undefined)overallHazard=0;var hist=new tr.v.Histogram('hazard',tr.b.Unit.byName.normalizedPercentage_smallerIsBetter);hist.addSample(overallHazard);values.addHistogram(hist);}tr.metrics.MetricRegistry.register(hazardMetric);return{hazardMetric:hazardMetric,computeHazardForLongTasksInRangeOnThread:computeHazardForLongTasksInRangeOnThread,computeHazardForLongTasks:computeHazardForLongTasks,computeResponsivenessRisk:computeResponsivenessRisk};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../../value/numeric.js":196,"../metric_registry.js":89,"./long_tasks_metric.js":95}],94:[function(require,module,exports){(function(global){"use strict";require("../../base/category_util.js");require("../../base/statistics.js");require("../metric_registry.js");require("./utils.js");require("../../model/helpers/chrome_model_helper.js");require("../../model/timed_event.js");require("../../value/histogram.js");require("../../value/numeric.js");'use strict';global.tr.exportTo('tr.metrics.sh',function(){var RESPONSIVENESS_THRESHOLD=50;var INTERACTIVE_WINDOW_SIZE=5*1000;var timeDurationInMs_smallerIsBetter=tr.b.Unit.byName.timeDurationInMs_smallerIsBetter;var RelatedEventSet=tr.v.d.RelatedEventSet;function hasCategoryAndName(event,category,title){return event.title===title&&event.category&&tr.b.getCategoryParts(event.category).indexOf(category)!==-1;}function findTargetRendererHelper(chromeHelper){var largestPid=-1;for(var pid in chromeHelper.rendererHelpers){var rendererHelper=chromeHelper.rendererHelpers[pid];if(rendererHelper.isChromeTracingUI)continue;if(pid>largestPid)largestPid=pid;}if(largestPid===-1)return undefined;return chromeHelper.rendererHelpers[largestPid];}function createBreakdownDiagnostic(rendererHelper,start,end){var breakdownDict=rendererHelper.generateTimeBreakdownTree(start,end);var breakdownDiagnostic=new tr.v.d.Breakdown();breakdownDiagnostic.colorScheme=tr.v.d.COLOR_SCHEME_CHROME_USER_FRIENDLY_CATEGORY_DRIVER;for(var label in breakdownDict){breakdownDiagnostic.set(label,breakdownDict[label].total);}return breakdownDiagnostic;}function NavigationStartFinder(rendererHelper){this.navigationStartsForFrameId_={};for(var ev of rendererHelper.mainThread.sliceGroup.childEvents()){if(!hasCategoryAndName(ev,'blink.user_timing','navigationStart'))continue;var frameIdRef=ev.args['frame'];var list=this.navigationStartsForFrameId_[frameIdRef];if(list===undefined)this.navigationStartsForFrameId_[frameIdRef]=list=[];list.unshift(ev);}}NavigationStartFinder.prototype={findNavigationStartEventForFrameBeforeTimestamp:function(frameIdRef,ts){var list=this.navigationStartsForFrameId_[frameIdRef];if(list===undefined){console.warn('No navigationStartEvent found for frame id "'+frameIdRef+'"');return undefined;}var eventBeforeTimestamp;for(var ev of list){if(ev.start>ts)continue;if(eventBeforeTimestamp===undefined)eventBeforeTimestamp=ev;}if(eventBeforeTimestamp===undefined){console.warn('Failed to find navigationStartEvent.');return undefined;}return eventBeforeTimestamp;}};var FIRST_PAINT_BOUNDARIES=tr.v.HistogramBinBoundaries.createLinear(0,1e3,20).addLinearBins(3e3,20).addExponentialBins(20e3,20);function createHistogram(name){var histogram=new tr.v.Histogram(name,timeDurationInMs_smallerIsBetter,FIRST_PAINT_BOUNDARIES);histogram.customizeSummaryOptions({avg:true,count:false,max:true,min:true,std:true,sum:false,percentile:[0.90,0.95,0.99]});return histogram;}function findFrameLoaderSnapshotAt(rendererHelper,frameIdRef,ts){var snapshot;var objects=rendererHelper.process.objects;var frameLoaderInstances=objects.instancesByTypeName_['FrameLoader'];if(frameLoaderInstances===undefined){console.warn('Failed to find FrameLoader for frameId "'+frameIdRef+'" at ts '+ts+', the trace maybe incomplete or from an old'+'Chrome.');return undefined;}var snapshot;for(var instance of frameLoaderInstances){if(!instance.isAliveAt(ts))continue;var maybeSnapshot=instance.getSnapshotAt(ts);if(frameIdRef!==maybeSnapshot.args['frame']['id_ref'])continue;snapshot=maybeSnapshot;}return snapshot;}function findAllUserTimingEvents(rendererHelper,title){var targetEvents=[];for(var ev of rendererHelper.process.getDescendantEvents()){if(!hasCategoryAndName(ev,'blink.user_timing',title))continue;targetEvents.push(ev);}return targetEvents;}function findFirstMeaningfulPaintCandidates(rendererHelper){var isTelemetryInternalEvent=prepareTelemetryInternalEventPredicate(rendererHelper);var candidatesForFrameId={};for(var ev of rendererHelper.process.getDescendantEvents()){if(!hasCategoryAndName(ev,'loading','firstMeaningfulPaintCandidate'))continue;if(isTelemetryInternalEvent(ev))continue;var frameIdRef=ev.args['frame'];if(frameIdRef===undefined)continue;var list=candidatesForFrameId[frameIdRef];if(list===undefined)candidatesForFrameId[frameIdRef]=list=[];list.push(ev);}return candidatesForFrameId;}function prepareTelemetryInternalEventPredicate(rendererHelper){var ignoreRegions=[];var internalRegionStart;for(var slice of rendererHelper.mainThread.asyncSliceGroup.getDescendantEvents()){if(!!slice.title.match(/^telemetry\.internal\.[^.]*\.start$/))internalRegionStart=slice.start;if(!!slice.title.match(/^telemetry\.internal\.[^.]*\.end$/)){var timedEvent=new tr.model.TimedEvent(internalRegionStart);timedEvent.duration=slice.end-internalRegionStart;ignoreRegions.push(timedEvent);}}return function isTelemetryInternalEvent(slice){for(var region of ignoreRegions)if(region.bounds(slice))return true;return false;};}var URL_BLACKLIST=['about:blank','data:text/html,pluginplaceholderdata'];function shouldIgnoreURL(url){return URL_BLACKLIST.indexOf(url)>=0;}var METRICS=[{valueName:'timeToFirstContentfulPaint',title:'firstContentfulPaint',description:'time to first contentful paint'},{valueName:'timeToOnload',title:'loadEventStart',description:'time to onload. '+'This is temporary metric used for PCv1/v2 sanity checking'}];function timeToFirstContentfulPaintMetric(values,model){var chromeHelper=model.getOrCreateHelper(tr.model.helpers.ChromeModelHelper);var rendererHelper=findTargetRendererHelper(chromeHelper);var isTelemetryInternalEvent=prepareTelemetryInternalEventPredicate(rendererHelper);var navigationStartFinder=new NavigationStartFinder(rendererHelper);for(var metric of METRICS){var histogram=createHistogram(metric.valueName);histogram.description=metric.description;var targetEvents=findAllUserTimingEvents(rendererHelper,metric.title);for(var ev of targetEvents){if(isTelemetryInternalEvent(ev))continue;var frameIdRef=ev.args['frame'];var snapshot=findFrameLoaderSnapshotAt(rendererHelper,frameIdRef,ev.start);if(snapshot===undefined||!snapshot.args.isLoadingMainFrame)continue;var url=snapshot.args.documentLoaderURL;if(shouldIgnoreURL(url))continue;var navigationStartEvent=navigationStartFinder.findNavigationStartEventForFrameBeforeTimestamp(frameIdRef,ev.start);if(navigationStartEvent===undefined)continue;var timeToEvent=ev.start-navigationStartEvent.start;histogram.addSample(timeToEvent,{url:new tr.v.d.Generic(url)});}values.addHistogram(histogram);}}function addTimeToInteractiveSampleToHistogram(histogram,rendererHelper,navigationStart,firstMeaningfulPaint,url){if(shouldIgnoreURL(url))return;var navigationStartTime=navigationStart.start;var firstInteractive=Infinity;var firstInteractiveCandidate=firstMeaningfulPaint;var lastLongTaskEvent=undefined;for(var ev of[...rendererHelper.mainThread.sliceGroup.childEvents()]){if(ev.start<firstInteractiveCandidate)continue;var interactiveDurationSoFar=ev.start-firstInteractiveCandidate;if(interactiveDurationSoFar>=INTERACTIVE_WINDOW_SIZE){firstInteractive=firstInteractiveCandidate;break;}if(ev.title==='TaskQueueManager::ProcessTaskFromWorkQueue'&&ev.duration>RESPONSIVENESS_THRESHOLD){firstInteractiveCandidate=ev.end-50;lastLongTaskEvent=ev;}}var breakdownDiagnostic=createBreakdownDiagnostic(rendererHelper,navigationStartTime,firstInteractive);var timeToFirstInteractive=firstInteractive-navigationStartTime;histogram.addSample(timeToFirstInteractive,{"Start":new RelatedEventSet(navigationStart),"Last long task":new RelatedEventSet(lastLongTaskEvent),"Navigation infos":new tr.v.d.Generic({url:url,pid:rendererHelper.pid,start:navigationStartTime,interactive:firstInteractive}),"Breakdown of [navStart, Interactive]":breakdownDiagnostic});}function timeToFirstMeaningfulPaintAndTimeToInteractiveMetrics(values,model){var chromeHelper=model.getOrCreateHelper(tr.model.helpers.ChromeModelHelper);var rendererHelper=findTargetRendererHelper(chromeHelper);var navigationStartFinder=new NavigationStartFinder(rendererHelper);var firstMeaningfulPaintHistogram=createHistogram('timeToFirstMeaningfulPaint');firstMeaningfulPaintHistogram.description='time to first meaningful paint';var firstInteractiveHistogram=createHistogram('timeToFirstInteractive');firstInteractiveHistogram.description='time to first interactive';function addFirstMeaningfulPaintSampleToHistogram(frameIdRef,navigationStart,fmpMarkerEvent){var snapshot=findFrameLoaderSnapshotAt(rendererHelper,frameIdRef,fmpMarkerEvent.start);if(snapshot===undefined||!snapshot.args.isLoadingMainFrame)return;var url=snapshot.args.documentLoaderURL;if(shouldIgnoreURL(url))return;var timeToFirstMeaningfulPaint=fmpMarkerEvent.start-navigationStart.start;var extraDiagnostic={url:url,pid:rendererHelper.pid};var breakdownDiagnostic=createBreakdownDiagnostic(rendererHelper,navigationStart.start,fmpMarkerEvent.start);firstMeaningfulPaintHistogram.addSample(timeToFirstMeaningfulPaint,{"Breakdown of [navStart, FMP]":breakdownDiagnostic,"Start":new RelatedEventSet(navigationStart),"End":new RelatedEventSet(fmpMarkerEvent),"Navigation infos":new tr.v.d.Generic({url:url,pid:rendererHelper.pid,start:navigationStart.start,fmp:fmpMarkerEvent.start})});return{firstMeaningfulPaint:fmpMarkerEvent.start,url:url};}var candidatesForFrameId=findFirstMeaningfulPaintCandidates(rendererHelper);for(var frameIdRef in candidatesForFrameId){var navigationStart;var lastCandidate;for(var ev of candidatesForFrameId[frameIdRef]){var navigationStartForThisCandidate=navigationStartFinder.findNavigationStartEventForFrameBeforeTimestamp(frameIdRef,ev.start);if(navigationStartForThisCandidate===undefined)continue;if(navigationStart!==navigationStartForThisCandidate){if(navigationStart!==undefined&&lastCandidate!==undefined){data=addFirstMeaningfulPaintSampleToHistogram(frameIdRef,navigationStart,lastCandidate);if(data!==undefined)addTimeToInteractiveSampleToHistogram(firstInteractiveHistogram,rendererHelper,navigationStart,data.firstMeaningfulPaint,data.url);}navigationStart=navigationStartForThisCandidate;}lastCandidate=ev;}if(lastCandidate!==undefined){var data=addFirstMeaningfulPaintSampleToHistogram(frameIdRef,navigationStart,lastCandidate);if(data!==undefined)addTimeToInteractiveSampleToHistogram(firstInteractiveHistogram,rendererHelper,navigationStart,data.firstMeaningfulPaint,data.url);}}values.addHistogram(firstMeaningfulPaintHistogram);values.addHistogram(firstInteractiveHistogram);}function loadingMetric(values,model){timeToFirstContentfulPaintMetric(values,model);timeToFirstMeaningfulPaintAndTimeToInteractiveMetrics(values,model);}tr.metrics.MetricRegistry.register(loadingMetric);return{loadingMetric:loadingMetric};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../../base/category_util.js":36,"../../base/statistics.js":59,"../../model/helpers/chrome_model_helper.js":133,"../../model/timed_event.js":166,"../../value/histogram.js":195,"../../value/numeric.js":196,"../metric_registry.js":89,"./utils.js":100}],95:[function(require,module,exports){(function(global){"use strict";require("../../extras/chrome/chrome_user_friendly_category_driver.js");require("../metric_registry.js");require("../../model/helpers/chrome_model_helper.js");require("../../value/histogram.js");'use strict';global.tr.exportTo('tr.metrics.sh',function(){var LONG_TASK_MS=50;var LONGEST_TASK_MS=1000;function iterateLongTopLevelTasksOnThreadInRange(thread,opt_range,cb,opt_this){thread.sliceGroup.topLevelSlices.forEach(function(slice){if(opt_range&&!opt_range.intersectsExplicitRangeInclusive(slice.start,slice.end))return;if(slice.duration<LONG_TASK_MS)return;cb.call(opt_this,slice);});}function iterateRendererMainThreads(model,cb,opt_this){var modelHelper=model.getOrCreateHelper(tr.model.helpers.ChromeModelHelper);tr.b.dictionaryValues(modelHelper.rendererHelpers).forEach(function(rendererHelper){if(!rendererHelper.mainThread)return;cb.call(opt_this,rendererHelper.mainThread);});}function longTasksMetric(values,model,opt_options){var rangeOfInterest=opt_options?opt_options.rangeOfInterest:undefined;var longTaskHist=new tr.v.Histogram('long tasks',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,tr.v.HistogramBinBoundaries.createLinear(LONG_TASK_MS,LONGEST_TASK_MS,40));longTaskHist.description='durations of long tasks';var slices=new tr.model.EventSet();iterateRendererMainThreads(model,function(thread){iterateLongTopLevelTasksOnThreadInRange(thread,rangeOfInterest,function(task){longTaskHist.addSample(task.duration,{relatedEvents:new tr.v.d.RelatedEventSet([task])});slices.push(task);slices.addEventSet(task.descendentSlices);});});values.addHistogram(longTaskHist);var sampleForEvent=undefined;var breakdown=tr.v.d.RelatedHistogramBreakdown.buildFromEvents(values,'long tasks ',slices,e=>model.getUserFriendlyCategoryFromEvent(e)||'unknown',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,sampleForEvent,tr.v.HistogramBinBoundaries.createExponential(1,LONGEST_TASK_MS,40));breakdown.colorScheme=tr.v.d.COLOR_SCHEME_CHROME_USER_FRIENDLY_CATEGORY_DRIVER;longTaskHist.diagnostics.set('category',breakdown);}tr.metrics.MetricRegistry.register(longTasksMetric,{supportsRangeOfInterest:true});return{longTasksMetric:longTasksMetric,iterateLongTopLevelTasksOnThreadInRange:iterateLongTopLevelTasksOnThreadInRange,iterateRendererMainThreads:iterateRendererMainThreads,LONG_TASK_MS:LONG_TASK_MS,LONGEST_TASK_MS:LONGEST_TASK_MS};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../../extras/chrome/chrome_user_friendly_category_driver.js":69,"../../model/helpers/chrome_model_helper.js":133,"../../value/histogram.js":195,"../metric_registry.js":89}],96:[function(require,module,exports){(function(global){"use strict";require("../../base/iteration_helpers.js");require("../../base/multi_dimensional_view.js");require("../../base/range.js");require("../../base/unit.js");require("../metric_registry.js");require("../../model/container_memory_dump.js");require("../../model/helpers/chrome_model_helper.js");require("../../model/memory_allocator_dump.js");require("../../value/histogram.js");'use strict';global.tr.exportTo('tr.metrics.sh',function(){var BACKGROUND=tr.model.ContainerMemoryDump.LevelOfDetail.BACKGROUND;var LIGHT=tr.model.ContainerMemoryDump.LevelOfDetail.LIGHT;var DETAILED=tr.model.ContainerMemoryDump.LevelOfDetail.DETAILED;var sizeInBytes_smallerIsBetter=tr.b.Unit.byName.sizeInBytes_smallerIsBetter;var count_smallerIsBetter=tr.b.Unit.byName.count_smallerIsBetter;var DISPLAYED_SIZE_NUMERIC_NAME=tr.model.MemoryAllocatorDump.DISPLAYED_SIZE_NUMERIC_NAME;var LEVEL_OF_DETAIL_NAMES=new Map();LEVEL_OF_DETAIL_NAMES.set(BACKGROUND,'background');LEVEL_OF_DETAIL_NAMES.set(LIGHT,'light');LEVEL_OF_DETAIL_NAMES.set(DETAILED,'detailed');var BOUNDARIES_FOR_UNIT_MAP=new WeakMap();BOUNDARIES_FOR_UNIT_MAP.set(count_smallerIsBetter,tr.v.HistogramBinBoundaries.createLinear(0,20,20));BOUNDARIES_FOR_UNIT_MAP.set(sizeInBytes_smallerIsBetter,new tr.v.HistogramBinBoundaries(0).addBinBoundary(1024).addExponentialBins(16*1024*1024*1024,4*24));function memoryMetric(values,model,opt_options){var rangeOfInterest=opt_options?opt_options.rangeOfInterest:undefined;var browserNameToGlobalDumps=splitGlobalDumpsByBrowserName(model,rangeOfInterest);addGeneralMemoryDumpValues(browserNameToGlobalDumps,values);addDetailedMemoryDumpValues(browserNameToGlobalDumps,values);addMemoryDumpCountValues(browserNameToGlobalDumps,values);}function splitGlobalDumpsByBrowserName(model,opt_rangeOfInterest){var chromeModelHelper=model.getOrCreateHelper(tr.model.helpers.ChromeModelHelper);var browserNameToGlobalDumps=new Map();var globalDumpToBrowserHelper=new WeakMap();if(chromeModelHelper){chromeModelHelper.browserHelpers.forEach(function(helper){var globalDumps=skipDumpsThatDoNotIntersectRange(helper.process.memoryDumps.map(d=>d.globalMemoryDump),opt_rangeOfInterest);globalDumps.forEach(function(globalDump){var existingHelper=globalDumpToBrowserHelper.get(globalDump);if(existingHelper!==undefined){throw new Error('Memory dump ID clash across multiple browsers '+'with PIDs: '+existingHelper.pid+' and '+helper.pid);}globalDumpToBrowserHelper.set(globalDump,helper);});makeKeyUniqueAndSet(browserNameToGlobalDumps,canonicalizeName(helper.browserName),globalDumps);});}var unclassifiedGlobalDumps=skipDumpsThatDoNotIntersectRange(model.globalMemoryDumps.filter(g=>!globalDumpToBrowserHelper.has(g)),opt_rangeOfInterest);if(unclassifiedGlobalDumps.length>0){makeKeyUniqueAndSet(browserNameToGlobalDumps,'unknown_browser',unclassifiedGlobalDumps);}return browserNameToGlobalDumps;}function skipDumpsThatDoNotIntersectRange(dumps,opt_range){if(!opt_range)return dumps;return dumps.filter(d=>opt_range.intersectsExplicitRangeInclusive(d.start,d.end));}function canonicalizeName(name){return name.toLowerCase().replace(' ','_');}var USER_FRIENDLY_BROWSER_NAMES={'chrome':'Chrome','webview':'WebView','unknown_browser':'an unknown browser'};function convertBrowserNameToUserFriendlyName(browserName){for(var baseName in USER_FRIENDLY_BROWSER_NAMES){if(!browserName.startsWith(baseName))continue;var userFriendlyBaseName=USER_FRIENDLY_BROWSER_NAMES[baseName];var suffix=browserName.substring(baseName.length);if(suffix.length===0)return userFriendlyBaseName;else if(/^\d+$/.test(suffix))return userFriendlyBaseName+'('+suffix+')';}return'\''+browserName+'\' browser';}function canonicalizeProcessName(rawProcessName){if(!rawProcessName)return'unknown_processes';var baseCanonicalName=canonicalizeName(rawProcessName);switch(baseCanonicalName){case'renderer':return'renderer_processes';case'browser':return'browser_process';default:return baseCanonicalName;}}function convertProcessNameToUserFriendlyName(processName,opt_requirePlural){switch(processName){case'browser_process':return opt_requirePlural?'browser processes':'the browser process';case'renderer_processes':return'renderer processes';case'gpu_process':return opt_requirePlural?'GPU processes':'the GPU process';case'ppapi_process':return opt_requirePlural?'PPAPI processes':'the PPAPI process';case'all_processes':return'all processes';case'unknown_processes':return'unknown processes';default:return'\''+processName+'\' processes';}}function makeKeyUniqueAndSet(map,key,value){var uniqueKey=key;var nextIndex=2;while(map.has(uniqueKey)){uniqueKey=key+nextIndex;nextIndex++;}map.set(uniqueKey,value);}function addGeneralMemoryDumpValues(browserNameToGlobalDumps,values){addMemoryDumpValues(browserNameToGlobalDumps,gmd=>true,function(processDump,addProcessScalar){addProcessScalar({source:'process_count',value:1,unit:count_smallerIsBetter,descriptionPrefixBuilder:buildProcessCountDescriptionPrefix});if(processDump.totals!==undefined){tr.b.iterItems(SYSTEM_TOTAL_VALUE_PROPERTIES,function(propertyName,propertySpec){addProcessScalar({source:'reported_by_os',property:propertyName,component:['system_memory'],value:propertySpec.getPropertyFunction(processDump),unit:sizeInBytes_smallerIsBetter,descriptionPrefixBuilder:propertySpec.descriptionPrefixBuilder});});}if(processDump.memoryAllocatorDumps===undefined)return;processDump.memoryAllocatorDumps.forEach(function(rootAllocatorDump){tr.b.iterItems(CHROME_VALUE_PROPERTIES,function(propertyName,descriptionPrefixBuilder){addProcessScalar({source:'reported_by_chrome',component:[rootAllocatorDump.name],property:propertyName,value:rootAllocatorDump.numerics[propertyName],descriptionPrefixBuilder:descriptionPrefixBuilder});});if(rootAllocatorDump.numerics['allocated_objects_size']===undefined){var allocatedObjectsDump=rootAllocatorDump.getDescendantDumpByFullName('allocated_objects');if(allocatedObjectsDump!==undefined){addProcessScalar({source:'reported_by_chrome',component:[rootAllocatorDump.name],property:'allocated_objects_size',value:allocatedObjectsDump.numerics['size'],descriptionPrefixBuilder:CHROME_VALUE_PROPERTIES['allocated_objects_size']});}}});addV8MemoryDumpValues(processDump,addProcessScalar);},function(componentTree){var tracingNode=componentTree.children[1].get('tracing');if(tracingNode===undefined)return;for(var i=0;i<componentTree.values.length;i++)componentTree.values[i].total-=tracingNode.values[i].total;},values);}function addV8MemoryDumpValues(processDump,addProcessScalar){var v8Dump=processDump.getMemoryAllocatorDumpByFullName('v8');if(v8Dump===undefined)return;v8Dump.children.forEach(function(isolateDump){var mallocDump=isolateDump.getDescendantDumpByFullName('malloc');if(mallocDump!==undefined){addV8ComponentValues(mallocDump,['v8','allocated_by_malloc'],addProcessScalar);}var heapDump=isolateDump.getDescendantDumpByFullName('heap_spaces');if(heapDump!==undefined){addV8ComponentValues(heapDump,['v8','heap'],addProcessScalar);heapDump.children.forEach(function(spaceDump){if(spaceDump.name==='other_spaces')return;addV8ComponentValues(spaceDump,['v8','heap',spaceDump.name],addProcessScalar);});}});addProcessScalar({source:'reported_by_chrome',component:['v8'],property:'code_and_metadata_size',value:v8Dump.numerics['code_and_metadata_size'],descriptionPrefixBuilder:buildCodeAndMetadataSizeValueDescriptionPrefix});addProcessScalar({source:'reported_by_chrome',component:['v8'],property:'code_and_metadata_size',value:v8Dump.numerics['bytecode_and_metadata_size'],descriptionPrefixBuilder:buildCodeAndMetadataSizeValueDescriptionPrefix});}function addV8ComponentValues(componentDump,componentPath,addProcessScalar){tr.b.iterItems(CHROME_VALUE_PROPERTIES,function(propertyName,descriptionPrefixBuilder){addProcessScalar({source:'reported_by_chrome',component:componentPath,property:propertyName,value:componentDump.numerics[propertyName],descriptionPrefixBuilder:descriptionPrefixBuilder});});}function buildProcessCountDescriptionPrefix(componentPath,processName){if(componentPath.length>0){throw new Error('Unexpected process count non-empty component path: '+componentPath.join(':'));}return'total number of '+convertProcessNameToUserFriendlyName(processName,true);}function buildChromeValueDescriptionPrefix(formatSpec,componentPath,processName){var nameParts=[];if(componentPath.length===0){nameParts.push('total');if(formatSpec.totalUserFriendlyPropertyName){nameParts.push(formatSpec.totalUserFriendlyPropertyName);}else{if(formatSpec.userFriendlyPropertyNamePrefix)nameParts.push(formatSpec.userFriendlyPropertyNamePrefix);nameParts.push(formatSpec.userFriendlyPropertyName);}nameParts.push('reported by Chrome for');}else{if(formatSpec.componentPreposition===undefined){if(formatSpec.userFriendlyPropertyNamePrefix)nameParts.push(formatSpec.userFriendlyPropertyNamePrefix);nameParts.push(componentPath.join(':'));nameParts.push(formatSpec.userFriendlyPropertyName);}else{if(formatSpec.userFriendlyPropertyNamePrefix)nameParts.push(formatSpec.userFriendlyPropertyNamePrefix);nameParts.push(formatSpec.userFriendlyPropertyName);nameParts.push(formatSpec.componentPreposition);if(componentPath[componentPath.length-1]==='allocated_by_malloc'){nameParts.push('objects allocated by malloc for');nameParts.push(componentPath.slice(0,componentPath.length-1).join(':'));}else{nameParts.push(componentPath.join(':'));}}nameParts.push('in');}nameParts.push(convertProcessNameToUserFriendlyName(processName));return nameParts.join(' ');}var CHROME_VALUE_PROPERTIES={'effective_size':buildChromeValueDescriptionPrefix.bind(undefined,{userFriendlyPropertyName:'effective size',componentPreposition:'of'}),'allocated_objects_size':buildChromeValueDescriptionPrefix.bind(undefined,{userFriendlyPropertyName:'size of all objects allocated',totalUserFriendlyPropertyName:'size of all allocated objects',componentPreposition:'by'}),'locked_size':buildChromeValueDescriptionPrefix.bind(undefined,{userFriendlyPropertyName:'locked (pinned) size',componentPreposition:'of'}),'peak_size':buildChromeValueDescriptionPrefix.bind(undefined,{userFriendlyPropertyName:'peak size',componentPreposition:'of'})};var SYSTEM_TOTAL_VALUE_PROPERTIES={'resident_size':{getPropertyFunction:function(processDump){return processDump.totals.residentBytes;},descriptionPrefixBuilder:buildOsValueDescriptionPrefix.bind(undefined,'resident set size (RSS)')},'peak_resident_size':{getPropertyFunction:function(processDump){return processDump.totals.peakResidentBytes;},descriptionPrefixBuilder:buildOsValueDescriptionPrefix.bind(undefined,'peak resident set size')}};function addDetailedMemoryDumpValues(browserNameToGlobalDumps,values){addMemoryDumpValues(browserNameToGlobalDumps,g=>g.levelOfDetail===DETAILED,function(processDump,addProcessScalar){tr.b.iterItems(SYSTEM_VALUE_COMPONENTS,function(componentName,componentSpec){tr.b.iterItems(SYSTEM_VALUE_PROPERTIES,function(propertyName,propertySpec){var node=getDescendantVmRegionClassificationNode(processDump.vmRegions,componentSpec.classificationPath);var componentPath=['system_memory'];if(componentName)componentPath.push(componentName);addProcessScalar({source:'reported_by_os',component:componentPath,property:propertyName,value:node===undefined?0:node.byteStats[propertySpec.byteStat]||0,unit:sizeInBytes_smallerIsBetter,descriptionPrefixBuilder:propertySpec.descriptionPrefixBuilder});});});var memtrackDump=processDump.getMemoryAllocatorDumpByFullName('gpu/android_memtrack');if(memtrackDump!==undefined){var descriptionPrefixBuilder=SYSTEM_VALUE_PROPERTIES['proportional_resident_size'].descriptionPrefixBuilder;memtrackDump.children.forEach(function(memtrackChildDump){var childName=memtrackChildDump.name;addProcessScalar({source:'reported_by_os',component:['gpu_memory',childName],property:'proportional_resident_size',value:memtrackChildDump.numerics['memtrack_pss'],descriptionPrefixBuilder:descriptionPrefixBuilder});});}},function(componentTree){},values);}var SYSTEM_VALUE_COMPONENTS={'':{classificationPath:[]},'java_heap':{classificationPath:['Android','Java runtime','Spaces'],userFriendlyName:'the Java heap'},'ashmem':{classificationPath:['Android','Ashmem'],userFriendlyName:'ashmem'},'native_heap':{classificationPath:['Native heap'],userFriendlyName:'the native heap'}};var SYSTEM_VALUE_PROPERTIES={'proportional_resident_size':{byteStat:'proportionalResident',descriptionPrefixBuilder:buildOsValueDescriptionPrefix.bind(undefined,'proportional resident size (PSS)')},'private_dirty_size':{byteStat:'privateDirtyResident',descriptionPrefixBuilder:buildOsValueDescriptionPrefix.bind(undefined,'private dirty size')}};function buildOsValueDescriptionPrefix(userFriendlyPropertyName,componentPath,processName){if(componentPath.length>2){throw new Error('OS value component path for \''+userFriendlyPropertyName+'\' too long: '+componentPath.join(':'));}var nameParts=[];if(componentPath.length<2)nameParts.push('total');nameParts.push(userFriendlyPropertyName);if(componentPath.length>0){switch(componentPath[0]){case'system_memory':if(componentPath.length>1){var userFriendlyComponentName=SYSTEM_VALUE_COMPONENTS[componentPath[1]].userFriendlyName;if(userFriendlyComponentName===undefined){throw new Error('System value sub-component for \''+userFriendlyPropertyName+'\' unknown: '+componentPath.join(':'));}nameParts.push('of',userFriendlyComponentName,'in');}else{nameParts.push('of system memory (RAM) used by');}break;case'gpu_memory':if(componentPath.length>1){nameParts.push('of the',componentPath[1]);nameParts.push('Android memtrack component in');}else{nameParts.push('of GPU memory (Android memtrack) used by');}break;default:throw new Error('OS value component for \''+userFriendlyPropertyName+'\' unknown: '+componentPath.join(':'));}}else{nameParts.push('reported by the OS for');}nameParts.push(convertProcessNameToUserFriendlyName(processName));return nameParts.join(' ');}function buildCodeAndMetadataSizeValueDescriptionPrefix(componentPath,processName){return buildChromeValueDescriptionPrefix({userFriendlyPropertyNamePrefix:'size of',userFriendlyPropertyName:'code and metadata'},componentPath,processName);}function getDescendantVmRegionClassificationNode(node,path){for(var i=0;i<path.length;i++){if(node===undefined)break;node=tr.b.findFirstInArray(node.children,c=>c.title===path[i]);}return node;}function addMemoryDumpCountValues(browserNameToGlobalDumps,values){browserNameToGlobalDumps.forEach(function(globalDumps,browserName){var totalDumpCount=0;var levelOfDetailNameToDumpCount={};LEVEL_OF_DETAIL_NAMES.forEach(function(levelOfDetailName){levelOfDetailNameToDumpCount[levelOfDetailName]=0;});globalDumps.forEach(function(globalDump){totalDumpCount++;var levelOfDetailName=LEVEL_OF_DETAIL_NAMES.get(globalDump.levelOfDetail);if(!(levelOfDetailName in levelOfDetailNameToDumpCount))return;levelOfDetailNameToDumpCount[levelOfDetailName]++;});reportMemoryDumpCountAsValue(browserName,undefined,totalDumpCount,values);tr.b.iterItems(levelOfDetailNameToDumpCount,function(levelOfDetailName,levelOfDetailDumpCount){reportMemoryDumpCountAsValue(browserName,levelOfDetailName,levelOfDetailDumpCount,values);});});}function reportMemoryDumpCountAsValue(browserName,levelOfDetailName,levelOfDetailDumpCount,values){var nameParts=['memory',browserName,'all_processes','dump_count'];if(levelOfDetailName!==undefined)nameParts.push(levelOfDetailName);var name=nameParts.join(':');var histogram=new tr.v.Histogram(name,count_smallerIsBetter,BOUNDARIES_FOR_UNIT_MAP.get(count_smallerIsBetter));histogram.addSample(levelOfDetailDumpCount);histogram.description=['total number of',levelOfDetailName||'all','memory dumps added by',convertBrowserNameToUserFriendlyName(browserName),'to the trace'].join(' ');values.addHistogram(histogram);}function addMemoryDumpValues(browserNameToGlobalDumps,customGlobalDumpFilter,customProcessDumpValueExtractor,customComponentTreeModifier,values){browserNameToGlobalDumps.forEach(function(globalDumps,browserName){var filteredGlobalDumps=globalDumps.filter(customGlobalDumpFilter);var sourceToPropertyToData=extractDataFromGlobalDumps(filteredGlobalDumps,customProcessDumpValueExtractor);reportDataAsValues(sourceToPropertyToData,browserName,customComponentTreeModifier,values);});}function extractDataFromGlobalDumps(globalDumps,customProcessDumpValueExtractor){var sourceToPropertyToData=new Map();var dumpCount=globalDumps.length;globalDumps.forEach(function(globalDump,dumpIndex){tr.b.iterItems(globalDump.processMemoryDumps,function(_,processDump){extractDataFromProcessDump(processDump,sourceToPropertyToData,dumpIndex,dumpCount,customProcessDumpValueExtractor);});});return sourceToPropertyToData;}function extractDataFromProcessDump(processDump,sourceToPropertyToData,dumpIndex,dumpCount,customProcessDumpValueExtractor){var rawProcessName=processDump.process.name;var processNamePath=[canonicalizeProcessName(rawProcessName)];customProcessDumpValueExtractor(processDump,function addProcessScalar(spec){if(spec.value===undefined)return;var component=spec.component||[];function createDetailsForErrorMessage(){var propertyUserFriendlyName=spec.property===undefined?'(undefined)':spec.property;var componentUserFriendlyName=component.length===0?'(empty)':component.join(':');return['source=',spec.source,', property=',propertyUserFriendlyName,', component=',componentUserFriendlyName,' in ',processDump.process.userFriendlyName].join('');}var value,unit;if(spec.value instanceof tr.v.ScalarNumeric){value=spec.value.value;unit=spec.value.unit;if(spec.unit!==undefined){throw new Error('Histogram value for '+createDetailsForErrorMessage()+' already specifies a unit');}}else{value=spec.value;unit=spec.unit;}var propertyToData=sourceToPropertyToData.get(spec.source);if(propertyToData===undefined){propertyToData=new Map();sourceToPropertyToData.set(spec.source,propertyToData);}var data=propertyToData.get(spec.property);if(data===undefined){data={processAndComponentTreeBuilder:new tr.b.MultiDimensionalViewBuilder(2,dumpCount),unit:unit,descriptionPrefixBuilder:spec.descriptionPrefixBuilder};propertyToData.set(spec.property,data);}else if(data.unit!==unit){throw new Error('Multiple units provided for '+createDetailsForErrorMessage()+':'+data.unit.unitName+' and '+unit.unitName);}else if(data.descriptionPrefixBuilder!==spec.descriptionPrefixBuilder){throw new Error('Multiple description prefix builders provided for'+createDetailsForErrorMessage());}var values=new Array(dumpCount);values[dumpIndex]=value;data.processAndComponentTreeBuilder.addPath([processNamePath,component],values,tr.b.MultiDimensionalViewBuilder.ValueKind.TOTAL);});}function reportDataAsValues(sourceToPropertyToData,browserName,customComponentTreeModifier,values){sourceToPropertyToData.forEach(function(propertyToData,sourceName){propertyToData.forEach(function(data,propertyName){var tree=data.processAndComponentTreeBuilder.buildTopDownTreeView();var unit=data.unit;var descriptionPrefixBuilder=data.descriptionPrefixBuilder;customComponentTreeModifier(tree);reportComponentDataAsValues(browserName,sourceName,propertyName,'all_processes',[],tree,unit,descriptionPrefixBuilder,values);tree.children[0].forEach(function(processTree,processName){if(processTree.children[0].size>0){throw new Error('Multi-dimensional view node for source='+sourceName+', property='+(propertyName===undefined?'(undefined)':propertyName)+', process='+processName+' has children wrt the process name dimension');}customComponentTreeModifier(processTree);reportComponentDataAsValues(browserName,sourceName,propertyName,processName,[],processTree,unit,descriptionPrefixBuilder,values);});});});}function reportComponentDataAsValues(browserName,sourceName,propertyName,processName,componentPath,componentNode,unit,descriptionPrefixBuilder,values){var nameParts=['memory',browserName,processName,sourceName].concat(componentPath);if(propertyName!==undefined)nameParts.push(propertyName);var name=nameParts.join(':');var numeric=buildMemoryNumericFromNode(name,componentNode,unit);numeric.description=[descriptionPrefixBuilder(componentPath,processName),'in',convertBrowserNameToUserFriendlyName(browserName)].join(' ');values.addHistogram(numeric);var depth=componentPath.length;componentPath.push(undefined);componentNode.children[1].forEach(function(childNode,childName){componentPath[depth]=childName;reportComponentDataAsValues(browserName,sourceName,propertyName,processName,componentPath,childNode,unit,descriptionPrefixBuilder,values);});componentPath.pop();}function buildMemoryNumericFromNode(name,node,unit){var histogram=new tr.v.Histogram(name,unit,BOUNDARIES_FOR_UNIT_MAP.get(unit));node.values.forEach(v=>histogram.addSample(v.total));return histogram;}tr.metrics.MetricRegistry.register(memoryMetric,{supportsRangeOfInterest:true});return{memoryMetric:memoryMetric};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../../base/iteration_helpers.js":47,"../../base/multi_dimensional_view.js":49,"../../base/range.js":53,"../../base/unit.js":63,"../../model/container_memory_dump.js":115,"../../model/helpers/chrome_model_helper.js":133,"../../model/memory_allocator_dump.js":140,"../../value/histogram.js":195,"../metric_registry.js":89}],97:[function(require,module,exports){(function(global){"use strict";require("../../base/statistics.js");require("../metric_registry.js");require("./loading_metric.js");require("../../value/histogram.js");'use strict';global.tr.exportTo('tr.metrics.sh',function(){var FRAMES_PER_SEC=60;var FRAME_MS=tr.b.convertUnit(1.0/FRAMES_PER_SEC,tr.b.UnitScale.Metric.NONE,tr.b.UnitScale.Metric.MILLI);function getPowerData_(model,start,end){var durationInMs=end-start;var durationInS=tr.b.convertUnit(durationInMs,tr.b.UnitScale.Metric.MILLI,tr.b.UnitScale.Metric.NONE);var energyInJ=model.device.powerSeries.getEnergyConsumedInJ(start,end);var powerInW=energyInJ/durationInS;return{duration:durationInMs,energy:energyInJ,power:powerInW};}function getNavigationTTIIntervals_(model){var values=new tr.v.ValueSet();tr.metrics.sh.loadingMetric(values,model);var ttiValues=values.getValuesNamed('timeToFirstInteractive');var intervals=[];for(var bin of tr.b.getOnlyElement(ttiValues).allBins){for(var diagnostics of bin.diagnosticMaps){var breakdown=diagnostics.get('Navigation infos');intervals.push(tr.b.Range.fromExplicitRange(breakdown.value.start,breakdown.value.interactive));}}return intervals.sort((x,y)=>x.min-y.min);}function makeTimeHistogram_(values,title,description){var hist=new tr.v.Histogram(title+':time',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter);hist.customizeSummaryOptions({avg:false,count:false,max:true,min:true,std:false,sum:true});hist.description='Time spent in '+description;values.addHistogram(hist);return hist;}function makeEnergyHistogram_(values,title,description){var hist=new tr.v.Histogram(title+':energy',tr.b.Unit.byName.energyInJoules_smallerIsBetter);hist.customizeSummaryOptions({avg:false,count:false,max:true,min:true,std:false,sum:true});hist.description='Energy consumed in '+description;values.addHistogram(hist);return hist;}function makePowerHistogram_(values,title,description){var hist=new tr.v.Histogram(title+':power',tr.b.Unit.byName.powerInWatts_smallerIsBetter);hist.customizeSummaryOptions({avg:true,count:false,max:true,min:true,std:false,sum:false});hist.description='Energy consumption rate in '+description;values.addHistogram(hist);return hist;}function storePowerData_(data,timeHist,energyHist,powerHist){if(timeHist!==undefined)timeHist.addSample(data.duration);if(energyHist!==undefined)energyHist.addSample(data.energy);if(powerHist!==undefined)powerHist.addSample(data.power);}function createHistograms_(model,values){var hists={};hists.railStageToTimeHist=new Map();hists.railStageToEnergyHist=new Map();hists.railStageToPowerHist=new Map();hists.scrollTimeHist=makeTimeHistogram_(values,'scroll','scrolling');hists.scrollEnergyHist=makeEnergyHistogram_(values,'scroll','scrolling');hists.scrollPowerHist=makePowerHistogram_(values,'scroll','scrolling');hists.loadTimeHist=makeTimeHistogram_(values,'load','page loads');hists.loadEnergyHist=makeEnergyHistogram_(values,'load','page loads');hists.afterLoadTimeHist=makeTimeHistogram_(values,'after_load','period after load');hists.afterLoadPowerHist=makePowerHistogram_(values,'after_load','period after load');hists.videoPowerHist=makePowerHistogram_(values,'video','video playback');hists.frameEnergyHist=makeEnergyHistogram_(values,'per_frame','each frame');for(var exp of model.userModel.expectations){var currTitle=exp.title.toLowerCase().replace(' ','_');if(!hists.railStageToTimeHist.has(currTitle)){var timeHist=makeTimeHistogram_(values,currTitle,'RAIL stage '+currTitle);var energyHist=makeEnergyHistogram_(values,currTitle,'RAIL stage '+currTitle);var powerHist=makePowerHistogram_(values,currTitle,'RAIL stage '+currTitle);hists.railStageToTimeHist.set(currTitle,timeHist);hists.railStageToEnergyHist.set(currTitle,energyHist);hists.railStageToPowerHist.set(currTitle,powerHist);}}return hists;}function processInteractionRecord_(exp,model,hists){var currTitle=exp.title.toLowerCase().replace(' ','_');var data=getPowerData_(model,exp.start,exp.end);storePowerData_(data,hists.railStageToTimeHist.get(currTitle),hists.railStageToEnergyHist.get(currTitle),hists.railStageToPowerHist.get(currTitle));if(exp.title.indexOf("Scroll")!==-1){storePowerData_(data,hists.scrollTimeHist,hists.scrollEnergyHist,hists.scrollPowerHist);}if(exp.title.indexOf("Video")!==-1)storePowerData_(data,undefined,undefined,hists.videoPowerHist);}function computeLoadingMetric_(model,hists){var intervals=getNavigationTTIIntervals_(model);var lastLoadTime=undefined;for(var interval of intervals){var loadData=getPowerData_(model,interval.min,interval.max);storePowerData_(loadData,hists.loadTimeHist,hists.loadEnergyHist,undefined);lastLoadTime=lastLoadTime==undefined?interval.max:Math.max(lastLoadTime,interval.max);}if(lastLoadTime!==undefined){var afterLoadData=getPowerData_(model,lastLoadTime,model.bounds.max);storePowerData_(afterLoadData,hists.afterLoadTimeHist,undefined,hists.afterLoadPowerHist);}}function computeFrameBasedPowerMetric_(model,hists){model.device.powerSeries.updateBounds();var currentTime=model.device.powerSeries.bounds.min;while(currentTime<model.device.powerSeries.bounds.max){var frameData=getPowerData_(model,currentTime,currentTime+FRAME_MS);hists.frameEnergyHist.addSample(frameData.energy);currentTime+=FRAME_MS;}}function powerMetric(values,model){if(!model.device.powerSeries)return;var hists=createHistograms_(model,values);for(var exp of model.userModel.expectations)processInteractionRecord_(exp,model,hists);computeLoadingMetric_(model,hists);computeFrameBasedPowerMetric_(model,hists);}tr.metrics.MetricRegistry.register(powerMetric);return{powerMetric:powerMetric};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../../base/statistics.js":59,"../../value/histogram.js":195,"../metric_registry.js":89,"./loading_metric.js":94}],98:[function(require,module,exports){(function(global){"use strict";require("../../base/statistics.js");require("../metric_registry.js");require("./utils.js");require("../../model/user_model/animation_expectation.js");require("../../model/user_model/load_expectation.js");require("../../model/user_model/response_expectation.js");require("../../value/histogram.js");'use strict';global.tr.exportTo('tr.metrics.sh',function(){function computeAnimationThroughput(animationExpectation){if(animationExpectation.frameEvents===undefined||animationExpectation.frameEvents.length===0)throw new Error('Animation missing frameEvents '+animationExpectation.stableId);var durationInS=tr.b.convertUnit(animationExpectation.duration,tr.b.UnitScale.Metric.MILLI,tr.b.UnitScale.Metric.NONE);return animationExpectation.frameEvents.length/durationInS;}function computeAnimationframeTimeDiscrepancy(animationExpectation){if(animationExpectation.frameEvents===undefined||animationExpectation.frameEvents.length===0)throw new Error('Animation missing frameEvents '+animationExpectation.stableId);var frameTimestamps=animationExpectation.frameEvents;frameTimestamps=frameTimestamps.toArray().map(function(event){return event.start;});var absolute=true;return tr.b.Statistics.timestampsDiscrepancy(frameTimestamps,absolute);}function responsivenessMetric(values,model,opt_options){var responseNumeric=new tr.v.Histogram('response latency',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,tr.v.HistogramBinBoundaries.createLinear(100,1e3,50));var throughputNumeric=new tr.v.Histogram('animation throughput',tr.b.Unit.byName.unitlessNumber_biggerIsBetter,tr.v.HistogramBinBoundaries.createLinear(10,60,10));var frameTimeDiscrepancyNumeric=new tr.v.Histogram('animation frameTimeDiscrepancy',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,tr.v.HistogramBinBoundaries.createLinear(0,1e3,50).addExponentialBins(1e4,10));var latencyNumeric=new tr.v.Histogram('animation latency',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,tr.v.HistogramBinBoundaries.createLinear(0,300,60));model.userModel.expectations.forEach(function(ue){if(opt_options&&opt_options.rangeOfInterest&&!opt_options.rangeOfInterest.intersectsExplicitRangeInclusive(ue.start,ue.end))return;var sampleDiagnosticMap=tr.v.d.DiagnosticMap.fromObject({relatedEvents:new tr.v.d.RelatedEventSet([ue])});if(ue instanceof tr.model.um.IdleExpectation){return;}else if(ue instanceof tr.model.um.StartupExpectation){return;}else if(ue instanceof tr.model.um.LoadExpectation){}else if(ue instanceof tr.model.um.ResponseExpectation){responseNumeric.addSample(ue.duration,sampleDiagnosticMap);}else if(ue instanceof tr.model.um.AnimationExpectation){if(ue.frameEvents===undefined||ue.frameEvents.length===0){return;}var throughput=computeAnimationThroughput(ue);if(throughput===undefined)throw new Error('Missing throughput for '+ue.stableId);throughputNumeric.addSample(throughput,sampleDiagnosticMap);var frameTimeDiscrepancy=computeAnimationframeTimeDiscrepancy(ue);if(frameTimeDiscrepancy===undefined)throw new Error('Missing frameTimeDiscrepancy for '+ue.stableId);frameTimeDiscrepancyNumeric.addSample(frameTimeDiscrepancy,sampleDiagnosticMap);ue.associatedEvents.forEach(function(event){if(!(event instanceof tr.e.cc.InputLatencyAsyncSlice))return;latencyNumeric.addSample(event.duration,sampleDiagnosticMap);});}else{throw new Error('Unrecognized stage for '+ue.stableId);}});[responseNumeric,throughputNumeric,frameTimeDiscrepancyNumeric,latencyNumeric].forEach(function(numeric){numeric.customizeSummaryOptions({avg:true,max:true,min:true,std:true});});values.addHistogram(responseNumeric);values.addHistogram(throughputNumeric);values.addHistogram(frameTimeDiscrepancyNumeric);values.addHistogram(latencyNumeric);}tr.metrics.MetricRegistry.register(responsivenessMetric,{supportsRangeOfInterest:true});return{responsivenessMetric:responsivenessMetric};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../../base/statistics.js":59,"../../model/user_model/animation_expectation.js":167,"../../model/user_model/load_expectation.js":169,"../../model/user_model/response_expectation.js":170,"../../value/histogram.js":195,"../metric_registry.js":89,"./utils.js":100}],99:[function(require,module,exports){(function(global){"use strict";require("./cpu_time_metric.js");require("./hazard_metric.js");require("./long_tasks_metric.js");require("./power_metric.js");'use strict';global.tr.exportTo('tr.metrics.sh',function(){function systemHealthMetrics(values,model){tr.metrics.sh.responsivenessMetric(values,model);tr.metrics.sh.longTasksMetric(values,model);tr.metrics.sh.hazardMetric(values,model);tr.metrics.sh.powerMetric(values,model);tr.metrics.sh.cpuTimeMetric(values,model);}tr.metrics.MetricRegistry.register(systemHealthMetrics);return{systemHealthMetrics:systemHealthMetrics};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./cpu_time_metric.js":92,"./hazard_metric.js":93,"./long_tasks_metric.js":95,"./power_metric.js":97}],100:[function(require,module,exports){(function(global){"use strict";require("../../model/user_model/user_expectation.js");'use strict';global.tr.exportTo('tr.metrics.sh',function(){function perceptualBlend(ir,index,score){return Math.exp(1-score);}function filterExpectationsByRange(irs,opt_range){var filteredExpectations=[];irs.forEach(function(ir){if(!(ir instanceof tr.model.um.UserExpectation))return;if(!opt_range||opt_range.intersectsExplicitRangeInclusive(ir.start,ir.end))filteredExpectations.push(ir);});return filteredExpectations;}return{perceptualBlend:perceptualBlend,filterExpectationsByRange:filterExpectationsByRange};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../../model/user_model/user_expectation.js":172}],101:[function(require,module,exports){(function(global){"use strict";require("../metric_registry.js");require("./utils.js");require("../../value/histogram.js");'use strict';global.tr.exportTo('tr.metrics.sh',function(){function webviewStartupMetric(values,model){var startupWallHist=new tr.v.Histogram('webview_startup_wall_time',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter);startupWallHist.description='WebView startup wall time';var startupCPUHist=new tr.v.Histogram('webview_startup_cpu_time',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter);startupCPUHist.description='WebView startup CPU time';var loadWallHist=new tr.v.Histogram('webview_url_load_wall_time',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter);loadWallHist.description='WebView blank URL load wall time';var loadCPUHist=new tr.v.Histogram('webview_url_load_cpu_time',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter);loadCPUHist.description='WebView blank URL load CPU time';for(var slice of model.getDescendantEvents()){if(!(slice instanceof tr.model.ThreadSlice))continue;if(slice.title==='WebViewStartupInterval'){startupWallHist.addSample(slice.duration);startupCPUHist.addSample(slice.cpuDuration);}if(slice.title==='WebViewBlankUrlLoadInterval'){loadWallHist.addSample(slice.duration);loadCPUHist.addSample(slice.cpuDuration);}}values.addHistogram(startupWallHist);values.addHistogram(startupCPUHist);values.addHistogram(loadWallHist);values.addHistogram(loadCPUHist);}tr.metrics.MetricRegistry.register(webviewStartupMetric);return{webviewStartupMetric:webviewStartupMetric};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../../value/histogram.js":195,"../metric_registry.js":89,"./utils.js":100}],102:[function(require,module,exports){(function(global){"use strict";require("../base/iteration_helpers.js");require("./metric_registry.js");require("../value/diagnostics/diagnostic_map.js");require("../value/histogram.js");'use strict';global.tr.exportTo('tr.metrics',function(){var MEMORY_INFRA_TRACING_CATEGORY='disabled-by-default-memory-infra';var TIME_BOUNDARIES=tr.v.HistogramBinBoundaries.createExponential(1e-3,1e5,30);var BYTE_BOUNDARIES=tr.v.HistogramBinBoundaries.createExponential(1,1e9,30);var COUNT_BOUNDARIES=tr.v.HistogramBinBoundaries.createExponential(1,1e5,30);function addTimeDurationValue(valueName,duration,allValues){var hist=new tr.v.Histogram(valueName,tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,TIME_BOUNDARIES);hist.addSample(duration);allValues.addHistogram(hist);}function addMemoryInfraValues(values,model,categoryNamesToTotalEventSizes){var memoryDumpCount=model.globalMemoryDumps.length;if(memoryDumpCount===0)return;var totalOverhead=0;var nonMemoryInfraThreadOverhead=0;var overheadByProvider={};tr.b.iterItems(model.processes,function(pid,process){tr.b.iterItems(process.threads,function(tid,thread){tr.b.iterItems(thread.sliceGroup.slices,(unusedSliceId,slice)=>{if(slice.category!==MEMORY_INFRA_TRACING_CATEGORY)return;totalOverhead+=slice.duration;if(thread.name!=='MemoryInfra')nonMemoryInfraThreadOverhead+=slice.duration;if(slice.args&&slice.args['dump_provider.name']){var providerName=slice.args['dump_provider.name'];var durationAndCount=overheadByProvider[providerName];if(durationAndCount===undefined){overheadByProvider[providerName]=durationAndCount={duration:0,count:0};}durationAndCount.duration+=slice.duration;durationAndCount.count++;}});});});addTimeDurationValue('Average CPU overhead on all threads per memory-infra dump',totalOverhead/memoryDumpCount,values);addTimeDurationValue('Average CPU overhead on non-memory-infra threads per memory-infra '+'dump',nonMemoryInfraThreadOverhead/memoryDumpCount,values);tr.b.iterItems(overheadByProvider,function(providerName,overhead){addTimeDurationValue('Average CPU overhead of '+providerName+' per OnMemoryDump call',overhead.duration/overhead.count,values);});var memoryInfraEventsSize=categoryNamesToTotalEventSizes.get(MEMORY_INFRA_TRACING_CATEGORY);var memoryInfraTraceBytesValue=new tr.v.Histogram('Total trace size of memory-infra dumps in bytes',tr.b.Unit.byName.sizeInBytes_smallerIsBetter,BYTE_BOUNDARIES);memoryInfraTraceBytesValue.addSample(memoryInfraEventsSize);values.addHistogram(memoryInfraTraceBytesValue);var traceBytesPerDumpValue=new tr.v.Histogram('Average trace size of memory-infra dumps in bytes',tr.b.Unit.byName.sizeInBytes_smallerIsBetter,BYTE_BOUNDARIES);traceBytesPerDumpValue.addSample(memoryInfraEventsSize/memoryDumpCount);values.addHistogram(traceBytesPerDumpValue);}function tracingMetric(values,model){if(!model.stats.hasEventSizesinBytes){throw new Error('Model stats does not have event size information. '+'Please enable ImportOptions.trackDetailedModelStats.');}var eventStats=model.stats.allTraceEventStatsInTimeIntervals;eventStats.sort(function(a,b){return a.timeInterval-b.timeInterval;});var totalTraceBytes=eventStats.reduce((a,b)=>a+b.totalEventSizeinBytes,0);var maxEventCountPerSec=0;var maxEventBytesPerSec=0;var INTERVALS_PER_SEC=Math.floor(1000/model.stats.TIME_INTERVAL_SIZE_IN_MS);var runningEventNumPerSec=0;var runningEventBytesPerSec=0;var start=0;var end=0;while(end<eventStats.length){runningEventNumPerSec+=eventStats[end].numEvents;runningEventBytesPerSec+=eventStats[end].totalEventSizeinBytes;end++;while(eventStats[end-1].timeInterval-eventStats[start].timeInterval>=INTERVALS_PER_SEC){runningEventNumPerSec-=eventStats[start].numEvents;runningEventBytesPerSec-=eventStats[start].totalEventSizeinBytes;start++;}maxEventCountPerSec=Math.max(maxEventCountPerSec,runningEventNumPerSec);maxEventBytesPerSec=Math.max(maxEventBytesPerSec,runningEventBytesPerSec);}var stats=model.stats.allTraceEventStats;var categoryNamesToTotalEventSizes=stats.reduce((map,stat)=>map.set(stat.category,(map.get(stat.category)||0)+stat.totalEventSizeinBytes),new Map());var maxCatNameAndBytes=Array.from(categoryNamesToTotalEventSizes.entries()).reduce((a,b)=>b[1]>=a[1]?b:a);var maxEventBytesPerCategory=maxCatNameAndBytes[1];var categoryWithMaxEventBytes=maxCatNameAndBytes[0];var maxEventCountPerSecValue=new tr.v.Histogram('Max number of events per second',tr.b.Unit.byName.count_smallerIsBetter,COUNT_BOUNDARIES);maxEventCountPerSecValue.addSample(maxEventCountPerSec);var maxEventBytesPerSecValue=new tr.v.Histogram('Max event size in bytes per second',tr.b.Unit.byName.sizeInBytes_smallerIsBetter,BYTE_BOUNDARIES);maxEventBytesPerSecValue.addSample(maxEventBytesPerSec);var totalTraceBytesValue=new tr.v.Histogram('Total trace size in bytes',tr.b.Unit.byName.sizeInBytes_smallerIsBetter,BYTE_BOUNDARIES);totalTraceBytesValue.addSample(totalTraceBytes);var biggestCategory={name:categoryWithMaxEventBytes,size_in_bytes:maxEventBytesPerCategory};totalTraceBytesValue.diagnostics.set('category_with_max_event_size',new tr.v.d.Generic(biggestCategory));values.addHistogram(totalTraceBytesValue);maxEventCountPerSecValue.diagnostics.set('category_with_max_event_size',new tr.v.d.Generic(biggestCategory));values.addHistogram(maxEventCountPerSecValue);maxEventBytesPerSecValue.diagnostics.set('category_with_max_event_size',new tr.v.d.Generic(biggestCategory));values.addHistogram(maxEventBytesPerSecValue);addMemoryInfraValues(values,model,categoryNamesToTotalEventSizes);}tr.metrics.MetricRegistry.register(tracingMetric);return{tracingMetric:tracingMetric,MEMORY_INFRA_TRACING_CATEGORY:MEMORY_INFRA_TRACING_CATEGORY};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/iteration_helpers.js":47,"../value/diagnostics/diagnostic_map.js":185,"../value/histogram.js":195,"./metric_registry.js":89}],103:[function(require,module,exports){(function(global){"use strict";require("../../base/range.js");require("../../base/unit.js");require("../metric_registry.js");require("../../value/histogram.js");'use strict';global.tr.exportTo('tr.metrics.v8',function(){var CUSTOM_BOUNDARIES=tr.v.HistogramBinBoundaries.createLinear(4,200,100);function computeExecuteMetrics(values,model){var cpuTotalExecution=new tr.v.Histogram('v8_execution_cpu_total',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,CUSTOM_BOUNDARIES);cpuTotalExecution.description='cpu total time spent in script execution';var wallTotalExecution=new tr.v.Histogram('v8_execution_wall_total',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,CUSTOM_BOUNDARIES);wallTotalExecution.description='wall total time spent in script execution';var cpuSelfExecution=new tr.v.Histogram('v8_execution_cpu_self',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,CUSTOM_BOUNDARIES);cpuSelfExecution.description='cpu self time spent in script execution';var wallSelfExecution=new tr.v.Histogram('v8_execution_wall_self',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,CUSTOM_BOUNDARIES);wallSelfExecution.description='wall self time spent in script execution';for(var e of model.findTopmostSlicesNamed('V8.Execute')){cpuTotalExecution.addSample(e.cpuDuration);wallTotalExecution.addSample(e.duration);cpuSelfExecution.addSample(e.cpuSelfTime);wallSelfExecution.addSample(e.selfTime);}values.addHistogram(cpuTotalExecution);values.addHistogram(wallTotalExecution);values.addHistogram(cpuSelfExecution);values.addHistogram(wallSelfExecution);}function computeParseLazyMetrics(values,model){var cpuSelfParseLazy=new tr.v.Histogram('v8_parse_lazy_cpu_self',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,CUSTOM_BOUNDARIES);cpuSelfParseLazy.description='cpu self time spent performing lazy parsing';var wallSelfParseLazy=new tr.v.Histogram('v8_parse_lazy_wall_self',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,CUSTOM_BOUNDARIES);wallSelfParseLazy.description='wall self time spent performing lazy parsing';for(var e of model.findTopmostSlicesNamed('V8.ParseLazyMicroSeconds')){cpuSelfParseLazy.addSample(e.cpuSelfTime);wallSelfParseLazy.addSample(e.selfTime);}for(var e of model.findTopmostSlicesNamed('V8.ParseLazy')){cpuSelfParseLazy.addSample(e.cpuSelfTime);wallSelfParseLazy.addSample(e.selfTime);}values.addHistogram(cpuSelfParseLazy);values.addHistogram(wallSelfParseLazy);}function computeCompileFullCodeMetrics(values,model){var cpuSelfCompileFullCode=new tr.v.Histogram('v8_compile_full_code_cpu_self',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,CUSTOM_BOUNDARIES);cpuSelfCompileFullCode.description='cpu self time spent performing compiling full code';var wallSelfCompileFullCode=new tr.v.Histogram('v8_compile_full_code_wall_self',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,CUSTOM_BOUNDARIES);wallSelfCompileFullCode.description='wall self time spent performing compiling full code';for(var e of model.findTopmostSlicesNamed('V8.CompileFullCode')){cpuSelfCompileFullCode.addSample(e.cpuSelfTime);wallSelfCompileFullCode.addSample(e.selfTime);}values.addHistogram(cpuSelfCompileFullCode);values.addHistogram(wallSelfCompileFullCode);}function computeCompileIgnitionMetrics(values,model){var cpuSelfCompileIgnition=new tr.v.Histogram('v8_compile_ignition_cpu_self',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,CUSTOM_BOUNDARIES);cpuSelfCompileIgnition.description='cpu self time spent in compile ignition';var wallSelfCompileIgnition=new tr.v.Histogram('v8_compile_ignition_wall_self',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,CUSTOM_BOUNDARIES);wallSelfCompileIgnition.description='wall self time spent in compile ignition';for(var e of model.findTopmostSlicesNamed('V8.CompileIgnition')){cpuSelfCompileIgnition.addSample(e.cpuSelfTime);wallSelfCompileIgnition.addSample(e.selfTime);}values.addHistogram(cpuSelfCompileIgnition);values.addHistogram(wallSelfCompileIgnition);}function computeRecompileMetrics(values,model){var cpuTotalRecompileSynchronous=new tr.v.Histogram('v8_recompile_synchronous_cpu_total',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,CUSTOM_BOUNDARIES);cpuTotalRecompileSynchronous.description='cpu total time spent in synchronous recompilation';var wallTotalRecompileSynchronous=new tr.v.Histogram('v8_recompile_synchronous_wall_total',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,CUSTOM_BOUNDARIES);wallTotalRecompileSynchronous.description='wall total time spent in synchronous recompilation';var cpuTotalRecompileConcurrent=new tr.v.Histogram('v8_recompile_concurrent_cpu_total',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,CUSTOM_BOUNDARIES);cpuTotalRecompileConcurrent.description='cpu total time spent in concurrent recompilation';var wallTotalRecompileConcurrent=new tr.v.Histogram('v8_recompile_concurrent_wall_total',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,CUSTOM_BOUNDARIES);wallTotalRecompileConcurrent.description='wall total time spent in concurrent recompilation';var cpuTotalRecompileOverall=new tr.v.Histogram('v8_recompile_overall_cpu_total',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,CUSTOM_BOUNDARIES);cpuTotalRecompileOverall.description='cpu total time spent in synchronous or concurrent recompilation';var wallTotalRecompileOverall=new tr.v.Histogram('v8_recompile_overall_wall_total',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,CUSTOM_BOUNDARIES);wallTotalRecompileOverall.description='wall total time spent in synchronous or concurrent recompilation';for(var e of model.findTopmostSlicesNamed('V8.RecompileSynchronous')){cpuTotalRecompileSynchronous.addSample(e.cpuDuration);wallTotalRecompileSynchronous.addSample(e.duration);cpuTotalRecompileOverall.addSample(e.cpuDuration);wallTotalRecompileOverall.addSample(e.duration);}values.addHistogram(cpuTotalRecompileSynchronous);values.addHistogram(wallTotalRecompileSynchronous);for(var e of model.findTopmostSlicesNamed('V8.RecompileConcurrent')){cpuTotalRecompileConcurrent.addSample(e.cpuDuration);wallTotalRecompileConcurrent.addSample(e.duration);cpuTotalRecompileOverall.addSample(e.cpuDuration);wallTotalRecompileOverall.addSample(e.duration);}values.addHistogram(cpuTotalRecompileConcurrent);values.addHistogram(wallTotalRecompileConcurrent);values.addHistogram(cpuTotalRecompileOverall);values.addHistogram(wallTotalRecompileOverall);}function computeOptimizeCodeMetrics(values,model){var cpuTotalOptimizeCode=new tr.v.Histogram('v8_optimize_code_cpu_total',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,CUSTOM_BOUNDARIES);cpuTotalOptimizeCode.description='cpu total time spent in code optimization';var wallTotalOptimizeCode=new tr.v.Histogram('v8_optimize_code_wall_total',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,CUSTOM_BOUNDARIES);wallTotalOptimizeCode.description='wall total time spent in code optimization';for(var e of model.findTopmostSlicesNamed('V8.OptimizeCode')){cpuTotalOptimizeCode.addSample(e.cpuDuration);wallTotalOptimizeCode.addSample(e.duration);}values.addHistogram(cpuTotalOptimizeCode);values.addHistogram(wallTotalOptimizeCode);}function computeDeoptimizeCodeMetrics(values,model){var cpuTotalDeoptimizeCode=new tr.v.Histogram('v8_deoptimize_code_cpu_total',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,CUSTOM_BOUNDARIES);cpuTotalDeoptimizeCode.description='cpu total time spent in code deoptimization';var wallTotalDeoptimizeCode=new tr.v.Histogram('v8_deoptimize_code_wall_total',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,CUSTOM_BOUNDARIES);wallTotalDeoptimizeCode.description='wall total time spent in code deoptimization';for(var e of model.findTopmostSlicesNamed('V8.DeoptimizeCode')){cpuTotalDeoptimizeCode.addSample(e.cpuDuration);wallTotalDeoptimizeCode.addSample(e.duration);}values.addHistogram(cpuTotalDeoptimizeCode);values.addHistogram(wallTotalDeoptimizeCode);}function executionMetric(values,model){computeExecuteMetrics(values,model);computeParseLazyMetrics(values,model);computeCompileIgnitionMetrics(values,model);computeCompileFullCodeMetrics(values,model);computeRecompileMetrics(values,model);computeOptimizeCodeMetrics(values,model);computeDeoptimizeCodeMetrics(values,model);}tr.metrics.MetricRegistry.register(executionMetric);return{executionMetric:executionMetric};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../../base/range.js":53,"../../base/unit.js":63,"../../value/histogram.js":195,"../metric_registry.js":89}],104:[function(require,module,exports){(function(global){"use strict";require("../../base/range.js");require("../../base/unit.js");require("../metric_registry.js");require("./utils.js");require("../../value/histogram.js");'use strict';global.tr.exportTo('tr.metrics.v8',function(){var TARGET_FPS=60;var MS_PER_SECOND=1000;var WINDOW_SIZE_MS=MS_PER_SECOND/TARGET_FPS;function gcMetric(values,model){addDurationOfTopEvents(values,model);addTotalDurationOfTopEvents(values,model);addDurationOfSubEvents(values,model);addIdleTimesOfTopEvents(values,model);addTotalIdleTimesOfTopEvents(values,model);addPercentageInV8ExecuteOfTopEvents(values,model);addTotalPercentageInV8Execute(values,model);addV8ExecuteMutatorUtilization(values,model);}tr.metrics.MetricRegistry.register(gcMetric);var timeDurationInMs_smallerIsBetter=tr.b.Unit.byName.timeDurationInMs_smallerIsBetter;var percentage_biggerIsBetter=tr.b.Unit.byName.normalizedPercentage_biggerIsBetter;var percentage_smallerIsBetter=tr.b.Unit.byName.normalizedPercentage_smallerIsBetter;var CUSTOM_BOUNDARIES=tr.v.HistogramBinBoundaries.createLinear(0,20,200).addExponentialBins(200,100);function createNumericForTopEventTime(name){var n=new tr.v.Histogram(name,timeDurationInMs_smallerIsBetter,CUSTOM_BOUNDARIES);n.customizeSummaryOptions({avg:true,count:true,max:true,min:false,std:true,sum:true,percentile:[0.90]});return n;}function createNumericForSubEventTime(name){var n=new tr.v.Histogram(name,timeDurationInMs_smallerIsBetter,CUSTOM_BOUNDARIES);n.customizeSummaryOptions({avg:true,count:false,max:true,min:false,std:false,sum:false,percentile:[0.90]});return n;}function createNumericForIdleTime(name){var n=new tr.v.Histogram(name,timeDurationInMs_smallerIsBetter,CUSTOM_BOUNDARIES);n.customizeSummaryOptions({avg:true,count:false,max:true,min:false,std:false,sum:true,percentile:[]});return n;}function createPercentage(name,numerator,denominator,unit){var hist=new tr.v.Histogram(name,unit);if(denominator===0)hist.addSample(0);else hist.addSample(numerator/denominator);hist.customizeSummaryOptions({avg:true,count:false,max:false,min:false,std:false,sum:false,percentile:[]});return hist;}function isNotForcedTopGarbageCollectionEvent(event){return tr.metrics.v8.utils.isTopGarbageCollectionEvent(event)&&!tr.metrics.v8.utils.isForcedGarbageCollectionEvent(event);}function isNotForcedSubGarbageCollectionEvent(event){return tr.metrics.v8.utils.isSubGarbageCollectionEvent(event)&&!tr.metrics.v8.utils.isForcedGarbageCollectionEvent(event);}function addDurationOfTopEvents(values,model){tr.metrics.v8.utils.groupAndProcessEvents(model,isNotForcedTopGarbageCollectionEvent,tr.metrics.v8.utils.topGarbageCollectionEventName,function(name,events){var cpuDuration=createNumericForTopEventTime(name);events.forEach(function(event){cpuDuration.addSample(event.cpuDuration);});values.addHistogram(cpuDuration);});}function addTotalDurationOfTopEvents(values,model){tr.metrics.v8.utils.groupAndProcessEvents(model,isNotForcedTopGarbageCollectionEvent,event=>'v8-gc-total',function(name,events){var cpuDuration=createNumericForTopEventTime(name);events.forEach(function(event){cpuDuration.addSample(event.cpuDuration);});values.addHistogram(cpuDuration);});}function addDurationOfSubEvents(values,model){tr.metrics.v8.utils.groupAndProcessEvents(model,isNotForcedSubGarbageCollectionEvent,tr.metrics.v8.utils.subGarbageCollectionEventName,function(name,events){var cpuDuration=createNumericForSubEventTime(name);events.forEach(function(event){cpuDuration.addSample(event.cpuDuration);});values.addHistogram(cpuDuration);});}function addIdleTimesOfTopEvents(values,model){tr.metrics.v8.utils.groupAndProcessEvents(model,isNotForcedTopGarbageCollectionEvent,tr.metrics.v8.utils.topGarbageCollectionEventName,function(name,events){addIdleTimes(values,model,name,events);});}function addTotalIdleTimesOfTopEvents(values,model){tr.metrics.v8.utils.groupAndProcessEvents(model,isNotForcedTopGarbageCollectionEvent,event=>'v8-gc-total',function(name,events){addIdleTimes(values,model,name,events);});}function addIdleTimes(values,model,name,events){var cpuDuration=createNumericForIdleTime();var insideIdle=createNumericForIdleTime();var outsideIdle=createNumericForIdleTime(name+'_outside_idle');var idleDeadlineOverrun=createNumericForIdleTime(name+'_idle_deadline_overrun');events.forEach(function(event){var idleTask=tr.metrics.v8.utils.findParent(event,tr.metrics.v8.utils.isIdleTask);var inside=0;var overrun=0;if(idleTask){var allottedTime=idleTask['args']['allotted_time_ms'];if(event.duration>allottedTime){overrun=event.duration-allottedTime;inside=event.cpuDuration*allottedTime/event.duration;}else{inside=event.cpuDuration;}}cpuDuration.addSample(event.cpuDuration);insideIdle.addSample(inside);outsideIdle.addSample(event.cpuDuration-inside);idleDeadlineOverrun.addSample(overrun);});values.addHistogram(idleDeadlineOverrun);values.addHistogram(outsideIdle);var percentage=createPercentage(name+'_percentage_idle',insideIdle.sum,cpuDuration.sum,percentage_biggerIsBetter);values.addHistogram(percentage);}function addPercentageInV8ExecuteOfTopEvents(values,model){tr.metrics.v8.utils.groupAndProcessEvents(model,isNotForcedTopGarbageCollectionEvent,tr.metrics.v8.utils.topGarbageCollectionEventName,function(name,events){addPercentageInV8Execute(values,model,name,events);});}function addTotalPercentageInV8Execute(values,model){tr.metrics.v8.utils.groupAndProcessEvents(model,isNotForcedTopGarbageCollectionEvent,event=>'v8-gc-total',function(name,events){addPercentageInV8Execute(values,model,name,events);});}function addPercentageInV8Execute(values,model,name,events){var cpuDurationInV8Execute=0;var cpuDurationTotal=0;events.forEach(function(event){var v8Execute=tr.metrics.v8.utils.findParent(event,tr.metrics.v8.utils.isV8ExecuteEvent);if(v8Execute){cpuDurationInV8Execute+=event.cpuDuration;}cpuDurationTotal+=event.cpuDuration;});var percentage=createPercentage(name+'_percentage_in_v8_execute',cpuDurationInV8Execute,cpuDurationTotal,percentage_smallerIsBetter);values.addHistogram(percentage);}function addV8ExecuteMutatorUtilization(values,model){tr.metrics.v8.utils.groupAndProcessEvents(model,tr.metrics.v8.utils.isTopV8ExecuteEvent,event=>'v8-execute',function(name,events){events.sort((a,b)=>a.start-b.start);var time=0;var pauses=[];for(var topEvent of events){for(var e of topEvent.enumerateAllDescendents()){if(isNotForcedTopGarbageCollectionEvent(e)){pauses.push({start:e.start-topEvent.start+time,end:e.end-topEvent.start+time});}}time+=topEvent.duration;}var mutatorUtilization=tr.metrics.v8.utils.mutatorUtilization(0,time,WINDOW_SIZE_MS,pauses);[0.90,0.95,0.99].forEach(function(percent){var hist=new tr.v.Histogram('v8-execute-mutator-utilization_pct_0'+percent*100,percentage_biggerIsBetter);hist.addSample(mutatorUtilization.percentile(1.0-percent));values.addHistogram(hist);});var hist=new tr.v.Histogram('v8-execute-mutator-utilization_min',percentage_biggerIsBetter);hist.addSample(mutatorUtilization.min);values.addHistogram(hist);});}return{gcMetric:gcMetric,WINDOW_SIZE_MS:WINDOW_SIZE_MS};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../../base/range.js":53,"../../base/unit.js":63,"../../value/histogram.js":195,"../metric_registry.js":89,"./utils.js":105}],105:[function(require,module,exports){(function(global){"use strict";require("../../base/piecewise_linear_function.js");require("../../base/range.js");require("../../base/range_utils.js");require("../../base/unit.js");require("../metric_registry.js");require("../../value/histogram.js");'use strict';global.tr.exportTo('tr.metrics.v8.utils',function(){var IDLE_TASK_EVENT='SingleThreadIdleTaskRunner::RunTask';var V8_EXECUTE='V8.Execute';var GC_EVENT_PREFIX='V8.GC';var FULL_GC_EVENT='V8.GCCompactor';var LOW_MEMORY_EVENT='V8.GCLowMemoryNotification';var MAJOR_GC_EVENT='MajorGC';var MINOR_GC_EVENT='MinorGC';var TOP_GC_EVENTS={'V8.GCCompactor':'v8-gc-full-mark-compactor','V8.GCFinalizeMC':'v8-gc-latency-mark-compactor','V8.GCFinalizeMCReduceMemory':'v8-gc-memory-mark-compactor','V8.GCIncrementalMarking':'v8-gc-incremental-step','V8.GCIncrementalMarkingFinalize':'v8-gc-incremental-finalize','V8.GCIncrementalMarkingStart':'v8-gc-incremental-start','V8.GCPhantomHandleProcessingCallback':'v8-gc-phantom-handle-callback','V8.GCScavenger':'v8-gc-scavenger'};var LOW_MEMORY_MARK_COMPACTOR='v8-gc-low-memory-mark-compactor';function findParent(event,predicate){var parent=event.parentSlice;while(parent){if(predicate(parent)){return parent;}parent=parent.parentSlice;}return null;}function isIdleTask(event){return event.title===IDLE_TASK_EVENT;}function isLowMemoryEvent(event){return event.title===LOW_MEMORY_EVENT;}function isV8ExecuteEvent(event){return event.title===V8_EXECUTE;}function isTopV8ExecuteEvent(event){return isV8ExecuteEvent(event)&&findParent(isV8ExecuteEvent)===null;}function isGarbageCollectionEvent(event){return event.title&&event.title.startsWith(GC_EVENT_PREFIX)&&event.title!=LOW_MEMORY_EVENT;}function isTopGarbageCollectionEvent(event){return event.title in TOP_GC_EVENTS;}function isForcedGarbageCollectionEvent(event){return findParent(event,isLowMemoryEvent)!==null;}function isSubGarbageCollectionEvent(event){return isGarbageCollectionEvent(event)&&event.parentSlice&&(isTopGarbageCollectionEvent(event.parentSlice)||event.parentSlice.title===MAJOR_GC_EVENT||event.parentSlice.title===MINOR_GC_EVENT);}function topGarbageCollectionEventName(event){if(event.title===FULL_GC_EVENT){if(findParent(event,isLowMemoryEvent)){return LOW_MEMORY_MARK_COMPACTOR;}}return TOP_GC_EVENTS[event.title];}function subGarbageCollectionEventName(event){var topEvent=findParent(event,isTopGarbageCollectionEvent);var prefix=topEvent?topGarbageCollectionEventName(topEvent):'unknown';var name=event.title.replace('V8.GC_MC_','').replace('V8.GC_SCAVENGER_','').replace('V8.GC_','').replace(/_/g,'-').toLowerCase();return prefix+'-'+name;}function groupAndProcessEvents(model,filterCallback,nameCallback,processCallback){var nameToEvents={};for(var event of model.getDescendantEvents()){if(!filterCallback(event))continue;var name=nameCallback(event);nameToEvents[name]=nameToEvents[name]||[];nameToEvents[name].push(event);}tr.b.iterItems(nameToEvents,function(name,events){processCallback(name,events);});}function unionOfIntervals(intervals){if(intervals.length===0)return[];return tr.b.mergeRanges(intervals.map(x=>({min:x.start,max:x.end})),1e-6,function(ranges){return{start:ranges.reduce((acc,x)=>Math.min(acc,x.min),ranges[0].min),end:ranges.reduce((acc,x)=>Math.max(acc,x.max),ranges[0].max)};});}function WindowEndpoint(start,points){this.points=points;this.lastIndex=-1;this.position=start;this.distanceUntilNextPoint=points[0].position-start;this.cummulativePause=0;this.stackDepth=0;}WindowEndpoint.prototype={advance:function(delta){var points=this.points;if(delta<this.distanceUntilNextPoint){this.position+=delta;this.cummulativePause+=this.stackDepth>0?delta:0;this.distanceUntilNextPoint=points[this.lastIndex+1].position-this.position;}else{this.position+=this.distanceUntilNextPoint;this.cummulativePause+=this.stackDepth>0?this.distanceUntilNextPoint:0;this.distanceUntilNextPoint=0;this.lastIndex++;if(this.lastIndex<points.length){this.stackDepth+=points[this.lastIndex].delta;if(this.lastIndex+1<points.length)this.distanceUntilNextPoint=points[this.lastIndex+1].position-this.position;}}}};function mutatorUtilization(start,end,timeWindow,intervals){var mu=new tr.b.PiecewiseLinearFunction();if(end-start<=timeWindow)return mu;if(intervals.length===0){mu.push(start,1.0,end-timeWindow,1.0);return mu;}intervals=unionOfIntervals(intervals);var points=[];intervals.forEach(function(interval){points.push({position:interval.start,delta:1});points.push({position:interval.end,delta:-1});});points.sort((a,b)=>a.position-b.position);points.push({position:end,delta:0});var left=new WindowEndpoint(start,points);var right=new WindowEndpoint(start,points);while(right.position-left.position<timeWindow)right.advance(timeWindow-(right.position-left.position));while(right.lastIndex<points.length){var distanceUntilNextPoint=Math.min(left.distanceUntilNextPoint,right.distanceUntilNextPoint);var position1=left.position;var value1=right.cummulativePause-left.cummulativePause;left.advance(distanceUntilNextPoint);right.advance(distanceUntilNextPoint);if(distanceUntilNextPoint>0){var position2=left.position;var value2=right.cummulativePause-left.cummulativePause;mu.push(position1,1.0-value1/timeWindow,position2,1.0-value2/timeWindow);}}return mu;}function hasV8Stats(globalMemoryDump){var v8stats=undefined;globalMemoryDump.iterateContainerDumps(function(dump){v8stats=v8stats||dump.getMemoryAllocatorDumpByFullName('v8');});return!!v8stats;}function rangeForMemoryDumps(model){var startOfFirstDumpWithV8=model.globalMemoryDumps.filter(hasV8Stats).reduce((start,dump)=>Math.min(start,dump.start),Infinity);if(startOfFirstDumpWithV8===Infinity)return new tr.b.Range();return tr.b.Range.fromExplicitRange(startOfFirstDumpWithV8,Infinity);}return{findParent:findParent,groupAndProcessEvents:groupAndProcessEvents,isForcedGarbageCollectionEvent:isForcedGarbageCollectionEvent,isGarbageCollectionEvent:isGarbageCollectionEvent,isIdleTask:isIdleTask,isLowMemoryEvent:isLowMemoryEvent,isSubGarbageCollectionEvent:isSubGarbageCollectionEvent,isTopGarbageCollectionEvent:isTopGarbageCollectionEvent,isTopV8ExecuteEvent:isTopV8ExecuteEvent,isV8ExecuteEvent:isV8ExecuteEvent,mutatorUtilization:mutatorUtilization,subGarbageCollectionEventName:subGarbageCollectionEventName,topGarbageCollectionEventName:topGarbageCollectionEventName,rangeForMemoryDumps:rangeForMemoryDumps,unionOfIntervals:unionOfIntervals};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../../base/piecewise_linear_function.js":50,"../../base/range.js":53,"../../base/range_utils.js":54,"../../base/unit.js":63,"../../value/histogram.js":195,"../metric_registry.js":89}],106:[function(require,module,exports){(function(global){"use strict";require("../metric_registry.js");require("../system_health/memory_metric.js");require("./execution_metric.js");require("./gc_metric.js");'use strict';global.tr.exportTo('tr.metrics.v8',function(){function v8AndMemoryMetrics(values,model){tr.metrics.v8.executionMetric(values,model);tr.metrics.v8.gcMetric(values,model);tr.metrics.sh.memoryMetric(values,model,{rangeOfInterest:tr.metrics.v8.utils.rangeForMemoryDumps(model)});}tr.metrics.MetricRegistry.register(v8AndMemoryMetrics);return{v8AndMemoryMetrics:v8AndMemoryMetrics};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../metric_registry.js":89,"../system_health/memory_metric.js":96,"./execution_metric.js":103,"./gc_metric.js":104}],107:[function(require,module,exports){(function(global){"use strict";require("../base/unit.js");require("./event_info.js");require("./event_set.js");require("./timed_event.js");'use strict';global.tr.exportTo('tr.model',function(){function Alert(info,start,opt_associatedEvents,opt_args){tr.model.TimedEvent.call(this,start);this.info=info;this.args=opt_args||{};this.associatedEvents=new tr.model.EventSet(opt_associatedEvents);this.associatedEvents.forEach(function(event){event.addAssociatedAlert(this);},this);}Alert.prototype={__proto__:tr.model.TimedEvent.prototype,get title(){return this.info.title;},get colorId(){return this.info.colorId;},get userFriendlyName(){return'Alert '+this.title+' at '+tr.b.Unit.byName.timeStampInMs.format(this.start);}};tr.model.EventRegistry.register(Alert,{name:'alert',pluralName:'alerts'});return{Alert:Alert};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/unit.js":63,"./event_info.js":124,"./event_set.js":126,"./timed_event.js":166}],108:[function(require,module,exports){(function(global){"use strict";require("../base/extension_registry.js");require("../base/guid.js");'use strict';global.tr.exportTo('tr.model',function(){function Annotation(){this.guid_=tr.b.GUID.allocateSimple();this.view_=undefined;};Annotation.fromDictIfPossible=function(args){if(args.typeName===undefined)throw new Error('Missing typeName argument');var typeInfo=Annotation.findTypeInfoMatching(function(typeInfo){return typeInfo.metadata.typeName===args.typeName;});if(typeInfo===undefined)return undefined;return typeInfo.constructor.fromDict(args);};Annotation.fromDict=function(){throw new Error('Not implemented');};Annotation.prototype={get guid(){return this.guid_;},onRemove:function(){},toDict:function(){throw new Error('Not implemented');},getOrCreateView:function(viewport){if(!this.view_)this.view_=this.createView_(viewport);return this.view_;},createView_:function(){throw new Error('Not implemented');}};var options=new tr.b.ExtensionRegistryOptions(tr.b.BASIC_REGISTRY_MODE);tr.b.decorateExtensionRegistry(Annotation,options);Annotation.addEventListener('will-register',function(e){if(!e.typeInfo.constructor.hasOwnProperty('fromDict'))throw new Error('Must have fromDict method');if(!e.typeInfo.metadata.typeName)throw new Error('Registered Annotations must provide typeName');});return{Annotation:Annotation};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/extension_registry.js":41,"../base/guid.js":45}],109:[function(require,module,exports){(function(global){"use strict";require("../base/unit.js");require("./timed_event.js");'use strict';global.tr.exportTo('tr.model',function(){function AsyncSlice(category,title,colorId,start,args,duration,opt_isTopLevel,opt_cpuStart,opt_cpuDuration,opt_argsStripped){tr.model.TimedEvent.call(this,start);this.category=category||'';this.originalTitle=title;this.title=title;this.colorId=colorId;this.args=args;this.startStackFrame=undefined;this.endStackFrame=undefined;this.didNotFinish=false;this.important=false;this.subSlices=[];this.parentContainer_=undefined;this.id=undefined;this.startThread=undefined;this.endThread=undefined;this.cpuStart=undefined;this.cpuDuration=undefined;this.argsStripped=false;this.startStackFrame=undefined;this.endStackFrame=undefined;this.duration=duration;this.isTopLevel=opt_isTopLevel===true;if(opt_cpuStart!==undefined)this.cpuStart=opt_cpuStart;if(opt_cpuDuration!==undefined)this.cpuDuration=opt_cpuDuration;if(opt_argsStripped!==undefined)this.argsStripped=opt_argsStripped;}AsyncSlice.prototype={__proto__:tr.model.TimedEvent.prototype,get analysisTypeName(){return this.title;},get parentContainer(){return this.parentContainer_;},set parentContainer(parentContainer){this.parentContainer_=parentContainer;for(var i=0;i<this.subSlices.length;i++){var subSlice=this.subSlices[i];if(subSlice.parentContainer===undefined)subSlice.parentContainer=parentContainer;}},get viewSubGroupTitle(){return this.title;},get userFriendlyName(){return'Async slice '+this.title+' at '+tr.b.Unit.byName.timeStampInMs.format(this.start);},get stableId(){var parentAsyncSliceGroup=this.parentContainer.asyncSliceGroup;return parentAsyncSliceGroup.stableId+'.'+parentAsyncSliceGroup.slices.indexOf(this);},findTopmostSlicesRelativeToThisSlice:function*(eventPredicate,opt_this){if(eventPredicate(this)){yield this;return;}for(var s of this.subSlices)yield*s.findTopmostSlicesRelativeToThisSlice(eventPredicate);},findDescendentSlice:function(targetTitle){if(!this.subSlices)return undefined;for(var i=0;i<this.subSlices.length;i++){if(this.subSlices[i].title==targetTitle)return this.subSlices[i];var slice=this.subSlices[i].findDescendentSlice(targetTitle);if(slice)return slice;}return undefined;},enumerateAllDescendents:function*(){for(var slice of this.subSlices)yield slice;for(var slice of this.subSlices)yield*slice.enumerateAllDescendents();},compareTo:function(that){return this.title.localeCompare(that.title);}};tr.model.EventRegistry.register(AsyncSlice,{name:'asyncSlice',pluralName:'asyncSlices'});return{AsyncSlice:AsyncSlice};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/unit.js":63,"./timed_event.js":166}],110:[function(require,module,exports){(function(global){"use strict";require("../base/guid.js");require("../base/range.js");require("./async_slice.js");require("./event_container.js");'use strict';global.tr.exportTo('tr.model',function(){function AsyncSliceGroup(parentContainer,opt_name){tr.model.EventContainer.call(this);this.parentContainer_=parentContainer;this.slices=[];this.name_=opt_name;this.viewSubGroups_=undefined;}AsyncSliceGroup.prototype={__proto__:tr.model.EventContainer.prototype,get parentContainer(){return this.parentContainer_;},get model(){return this.parentContainer_.parent.model;},get stableId(){return this.parentContainer_.stableId+'.AsyncSliceGroup';},getSettingsKey:function(){if(!this.name_)return undefined;var parentKey=this.parentContainer_.getSettingsKey();if(!parentKey)return undefined;return parentKey+'.'+this.name_;},push:function(slice){slice.parentContainer=this.parentContainer;this.slices.push(slice);return slice;},get length(){return this.slices.length;},shiftTimestampsForward:function(amount){for(var sI=0;sI<this.slices.length;sI++){var slice=this.slices[sI];slice.start=slice.start+amount;var shiftSubSlices=function(subSlices){if(subSlices===undefined||subSlices.length===0)return;for(var sJ=0;sJ<subSlices.length;sJ++){subSlices[sJ].start+=amount;shiftSubSlices(subSlices[sJ].subSlices);}};shiftSubSlices(slice.subSlices);}},updateBounds:function(){this.bounds.reset();for(var i=0;i<this.slices.length;i++){this.bounds.addValue(this.slices[i].start);this.bounds.addValue(this.slices[i].end);}},get viewSubGroups(){if(this.viewSubGroups_===undefined){var prefix='';if(this.name!==undefined)prefix=this.name+'.';else prefix='';var subGroupsByTitle={};for(var i=0;i<this.slices.length;++i){var slice=this.slices[i];var subGroupTitle=slice.viewSubGroupTitle;if(!subGroupsByTitle[subGroupTitle]){subGroupsByTitle[subGroupTitle]=new AsyncSliceGroup(this.parentContainer_,prefix+subGroupTitle);}subGroupsByTitle[subGroupTitle].push(slice);}this.viewSubGroups_=tr.b.dictionaryValues(subGroupsByTitle);this.viewSubGroups_.sort(function(a,b){return a.slices[0].compareTo(b.slices[0]);});}return this.viewSubGroups_;},findTopmostSlicesInThisContainer:function*(eventPredicate,opt_this){for(var slice of this.slices){if(slice.isTopLevel){yield*slice.findTopmostSlicesRelativeToThisSlice(eventPredicate,opt_this);}}},childEvents:function*(){for(var slice of this.slices){yield slice;if(slice.subSlices)yield*slice.subSlices;}},childEventContainers:function*(){}};return{AsyncSliceGroup:AsyncSliceGroup};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/guid.js":45,"../base/range.js":53,"./async_slice.js":109,"./event_container.js":123}],111:[function(require,module,exports){(function(global){"use strict";require("../base/iteration_helpers.js");'use strict';global.tr.exportTo('tr.model',function(){var ClockDomainId={BATTOR:'BATTOR',UNKNOWN_CHROME_LEGACY:'UNKNOWN_CHROME_LEGACY',LINUX_CLOCK_MONOTONIC:'LINUX_CLOCK_MONOTONIC',LINUX_FTRACE_GLOBAL:'LINUX_FTRACE_GLOBAL',MAC_MACH_ABSOLUTE_TIME:'MAC_MACH_ABSOLUTE_TIME',WIN_ROLLOVER_PROTECTED_TIME_GET_TIME:'WIN_ROLLOVER_PROTECTED_TIME_GET_TIME',WIN_QPC:'WIN_QPC',TELEMETRY:'TELEMETRY'};var POSSIBLE_CHROME_CLOCK_DOMAINS=new Set([ClockDomainId.UNKNOWN_CHROME_LEGACY,ClockDomainId.LINUX_CLOCK_MONOTONIC,ClockDomainId.MAC_MACH_ABSOLUTE_TIME,ClockDomainId.WIN_ROLLOVER_PROTECTED_TIME_GET_TIME,ClockDomainId.WIN_QPC]);var BATTOR_FAST_SYNC_THRESHOLD_MS=3;function ClockSyncManager(){this.domainsSeen_=new Set();this.markersBySyncId_=new Map();this.transformerMapByDomainId_={};}ClockSyncManager.prototype={addClockSyncMarker:function(domainId,syncId,startTs,opt_endTs){this.onDomainSeen_(domainId);if(tr.b.dictionaryValues(ClockDomainId).indexOf(domainId)<0){throw new Error('"'+domainId+'" is not in the list of known '+'clock domain IDs.');}if(this.modelDomainId_){throw new Error('Cannot add new clock sync markers after getting '+'a model time transformer.');}var marker=new ClockSyncMarker(domainId,startTs,opt_endTs);if(!this.markersBySyncId_.has(syncId)){this.markersBySyncId_.set(syncId,[marker]);return;}var markers=this.markersBySyncId_.get(syncId);if(markers.length===2){throw new Error('Clock sync with ID "'+syncId+'" is already '+'complete - cannot add a third clock sync marker to it.');}if(markers[0].domainId===domainId)throw new Error('A clock domain cannot sync with itself.');markers.push(marker);this.onSyncCompleted_(markers[0],marker);},get markersBySyncId(){return this.markersBySyncId_;},get domainsSeen(){return this.domainsSeen_;},getModelTimeTransformer:function(domainId){return this.getModelTimeTransformerRaw_(domainId).fn;},getModelTimeTransformerError:function(domainId){return this.getModelTimeTransformerRaw_(domainId).error;},getModelTimeTransformerRaw_:function(domainId){this.onDomainSeen_(domainId);if(!this.modelDomainId_)this.selectModelDomainId_();var transformer=this.getTransformerBetween_(domainId,this.modelDomainId_);if(!transformer){throw new Error('No clock sync markers exist pairing clock domain "'+domainId+'" '+'with model clock domain "'+this.modelDomainId_+'".');}return transformer;},getTransformerBetween_:function(fromDomainId,toDomainId){var visitedDomainIds=new Set();var queue=[{domainId:fromDomainId,transformer:Transformer.IDENTITY}];while(queue.length>0){queue.sort((domain1,domain2)=>domain1.transformer.error-domain2.transformer.error);var current=queue.shift();if(current.domainId===toDomainId)return current.transformer;if(visitedDomainIds.has(current.domainId))continue;visitedDomainIds.add(current.domainId);var outgoingTransformers=this.transformerMapByDomainId_[current.domainId];if(!outgoingTransformers)continue;for(var outgoingDomainId in outgoingTransformers){var toNextDomainTransformer=outgoingTransformers[outgoingDomainId];var toCurrentDomainTransformer=current.transformer;queue.push({domainId:outgoingDomainId,transformer:Transformer.compose(toNextDomainTransformer,toCurrentDomainTransformer)});}}return undefined;},selectModelDomainId_:function(){this.ensureAllDomainsAreConnected_();for(var chromeDomainId of POSSIBLE_CHROME_CLOCK_DOMAINS){if(this.domainsSeen_.has(chromeDomainId)){this.modelDomainId_=chromeDomainId;return;}}var domainsSeenArray=Array.from(this.domainsSeen_);domainsSeenArray.sort();this.modelDomainId_=domainsSeenArray[0];},ensureAllDomainsAreConnected_:function(){var firstDomainId=undefined;for(var domainId of this.domainsSeen_){if(!firstDomainId){firstDomainId=domainId;continue;}if(!this.getTransformerBetween_(firstDomainId,domainId)){throw new Error('Unable to select a master clock domain because no '+'path can be found from "'+firstDomainId+'" to "'+domainId+'".');}}return true;},onDomainSeen_:function(domainId){if(domainId===ClockDomainId.UNKNOWN_CHROME_LEGACY&&!this.domainsSeen_.has(ClockDomainId.UNKNOWN_CHROME_LEGACY)){for(var chromeDomainId of POSSIBLE_CHROME_CLOCK_DOMAINS){if(chromeDomainId===ClockDomainId.UNKNOWN_CHROME_LEGACY)continue;this.collapseDomains_(ClockDomainId.UNKNOWN_CHROME_LEGACY,chromeDomainId);}}this.domainsSeen_.add(domainId);},onSyncCompleted_:function(marker1,marker2){var forwardTransformer=Transformer.fromMarkers(marker1,marker2);var backwardTransformer=Transformer.fromMarkers(marker2,marker1);var existingTransformer=this.getOrCreateTransformerMap_(marker1.domainId)[marker2.domainId];if(!existingTransformer||forwardTransformer.error<existingTransformer.error){this.getOrCreateTransformerMap_(marker1.domainId)[marker2.domainId]=forwardTransformer;this.getOrCreateTransformerMap_(marker2.domainId)[marker1.domainId]=backwardTransformer;}},collapseDomains_:function(domain1Id,domain2Id){this.getOrCreateTransformerMap_(domain1Id)[domain2Id]=this.getOrCreateTransformerMap_(domain2Id)[domain1Id]=Transformer.IDENTITY;},getOrCreateTransformerMap_:function(domainId){if(!this.transformerMapByDomainId_[domainId])this.transformerMapByDomainId_[domainId]={};return this.transformerMapByDomainId_[domainId];}};function ClockSyncMarker(domainId,startTs,opt_endTs){this.domainId=domainId;this.startTs=startTs;this.endTs=opt_endTs===undefined?startTs:opt_endTs;}ClockSyncMarker.prototype={get duration(){return this.endTs-this.startTs;},get ts(){return this.startTs+this.duration/2;}};function Transformer(fn,error){this.fn=fn;this.error=error;}Transformer.IDENTITY=new Transformer(tr.b.identity,0);Transformer.compose=function(aToB,bToC){return new Transformer(ts=>bToC.fn(aToB.fn(ts)),aToB.error+bToC.error);};Transformer.fromMarkers=function(fromMarker,toMarker){var fromTs=fromMarker.ts,toTs=toMarker.ts;if(fromMarker.domainId===ClockDomainId.BATTOR&&toMarker.duration>BATTOR_FAST_SYNC_THRESHOLD_MS){toTs=toMarker.startTs;}else if(toMarker.domainId===ClockDomainId.BATTOR&&fromMarker.duration>BATTOR_FAST_SYNC_THRESHOLD_MS){fromTs=fromMarker.startTs;}var tsShift=toTs-fromTs;return new Transformer(ts=>ts+tsShift,fromMarker.duration+toMarker.duration);};return{ClockDomainId:ClockDomainId,ClockSyncManager:ClockSyncManager};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/iteration_helpers.js":47}],112:[function(require,module,exports){(function(global){"use strict";require("./location.js");require("./annotation.js");require("./rect_annotation.js");require("../ui/annotations/comment_box_annotation_view.js");'use strict';global.tr.exportTo('tr.model',function(){function CommentBoxAnnotation(location,text){tr.model.Annotation.apply(this,arguments);this.location=location;this.text=text;}CommentBoxAnnotation.fromDict=function(dict){var args=dict.args;var location=new tr.model.Location(args.location.xWorld,args.location.yComponents);return new tr.model.CommentBoxAnnotation(location,args.text);};CommentBoxAnnotation.prototype={__proto__:tr.model.Annotation.prototype,onRemove:function(){this.view_.removeTextArea();},toDict:function(){return{typeName:'comment_box',args:{text:this.text,location:this.location.toDict()}};},createView_:function(viewport){return new tr.ui.annotations.CommentBoxAnnotationView(viewport,this);}};tr.model.Annotation.register(CommentBoxAnnotation,{typeName:'comment_box'});return{CommentBoxAnnotation:CommentBoxAnnotation};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../ui/annotations/comment_box_annotation_view.js":177,"./annotation.js":108,"./location.js":139,"./rect_annotation.js":152}],113:[function(require,module,exports){(function(global){"use strict";require("../base/base.js");'use strict';global.tr.exportTo('tr.model',function(){var CompoundEventSelectionState={NOT_SELECTED:0,EVENT_SELECTED:0x1,SOME_ASSOCIATED_EVENTS_SELECTED:0x2,ALL_ASSOCIATED_EVENTS_SELECTED:0x4,EVENT_AND_SOME_ASSOCIATED_SELECTED:0x1|0x2,EVENT_AND_ALL_ASSOCIATED_SELECTED:0x1|0x4};return{CompoundEventSelectionState:CompoundEventSelectionState};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/base.js":34}],114:[function(require,module,exports){(function(global){"use strict";require("../base/base.js");'use strict';global.tr.exportTo('tr.model',function(){return{BROWSER_PROCESS_PID_REF:-1,OBJECT_DEFAULT_SCOPE:'ptr'};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/base.js":34}],115:[function(require,module,exports){(function(global){"use strict";require("./timed_event.js");'use strict';global.tr.exportTo('tr.model',function(){function ContainerMemoryDump(start){tr.model.TimedEvent.call(this,start);this.levelOfDetail=undefined;this.memoryAllocatorDumps_=undefined;this.memoryAllocatorDumpsByFullName_=undefined;};ContainerMemoryDump.LevelOfDetail={BACKGROUND:0,LIGHT:1,DETAILED:2};ContainerMemoryDump.prototype={__proto__:tr.model.TimedEvent.prototype,shiftTimestampsForward:function(amount){this.start+=amount;},get memoryAllocatorDumps(){return this.memoryAllocatorDumps_;},set memoryAllocatorDumps(memoryAllocatorDumps){this.memoryAllocatorDumps_=memoryAllocatorDumps;this.forceRebuildingMemoryAllocatorDumpByFullNameIndex();},getMemoryAllocatorDumpByFullName:function(fullName){if(this.memoryAllocatorDumps_===undefined)return undefined;if(this.memoryAllocatorDumpsByFullName_===undefined){var index={};function addDumpsToIndex(dumps){dumps.forEach(function(dump){index[dump.fullName]=dump;addDumpsToIndex(dump.children);});};addDumpsToIndex(this.memoryAllocatorDumps_);this.memoryAllocatorDumpsByFullName_=index;}return this.memoryAllocatorDumpsByFullName_[fullName];},forceRebuildingMemoryAllocatorDumpByFullNameIndex:function(){this.memoryAllocatorDumpsByFullName_=undefined;},iterateRootAllocatorDumps:function(fn,opt_this){if(this.memoryAllocatorDumps===undefined)return;this.memoryAllocatorDumps.forEach(fn,opt_this||this);}};return{ContainerMemoryDump:ContainerMemoryDump};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./timed_event.js":166}],116:[function(require,module,exports){(function(global){"use strict";require("../base/guid.js");require("../base/range.js");require("./counter_series.js");require("./event_container.js");'use strict';global.tr.exportTo('tr.model',function(){function Counter(parent,id,category,name){tr.model.EventContainer.call(this);this.parent_=parent;this.id_=id;this.category_=category||'';this.name_=name;this.series_=[];this.totals=[];}Counter.prototype={__proto__:tr.model.EventContainer.prototype,get parent(){return this.parent_;},get id(){return this.id_;},get category(){return this.category_;},get name(){return this.name_;},childEvents:function*(){},childEventContainers:function*(){yield*this.series;},set timestamps(arg){throw new Error('Bad counter API. No cookie.');},set seriesNames(arg){throw new Error('Bad counter API. No cookie.');},set seriesColors(arg){throw new Error('Bad counter API. No cookie.');},set samples(arg){throw new Error('Bad counter API. No cookie.');},addSeries:function(series){series.counter=this;series.seriesIndex=this.series_.length;this.series_.push(series);return series;},getSeries:function(idx){return this.series_[idx];},get series(){return this.series_;},get numSeries(){return this.series_.length;},get numSamples(){if(this.series_.length===0)return 0;return this.series_[0].length;},get timestamps(){if(this.series_.length===0)return[];return this.series_[0].timestamps;},getSampleStatistics:function(sampleIndices){sampleIndices.sort();var ret=[];this.series_.forEach(function(series){ret.push(series.getStatistics(sampleIndices));});return ret;},shiftTimestampsForward:function(amount){for(var i=0;i<this.series_.length;++i)this.series_[i].shiftTimestampsForward(amount);},updateBounds:function(){this.totals=[];this.maxTotal=0;this.bounds.reset();if(this.series_.length===0)return;var firstSeries=this.series_[0];var lastSeries=this.series_[this.series_.length-1];this.bounds.addValue(firstSeries.getTimestamp(0));this.bounds.addValue(lastSeries.getTimestamp(lastSeries.length-1));var numSeries=this.numSeries;this.maxTotal=-Infinity;for(var i=0;i<firstSeries.length;++i){var total=0;this.series_.forEach(function(series){total+=series.getSample(i).value;this.totals.push(total);}.bind(this));this.maxTotal=Math.max(total,this.maxTotal);}}};Counter.compare=function(x,y){var tmp=x.parent.compareTo(y);if(tmp!=0)return tmp;var tmp=x.name.localeCompare(y.name);if(tmp==0)return x.tid-y.tid;return tmp;};return{Counter:Counter};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/guid.js":45,"../base/range.js":53,"./counter_series.js":118,"./event_container.js":123}],117:[function(require,module,exports){(function(global){"use strict";require("../base/iteration_helpers.js");require("../base/sorted_array_utils.js");require("../base/unit.js");require("./event.js");require("./event_registry.js");'use strict';global.tr.exportTo('tr.model',function(){function CounterSample(series,timestamp,value){tr.model.Event.call(this);this.series_=series;this.timestamp_=timestamp;this.value_=value;}CounterSample.groupByTimestamp=function(samples){var samplesByTimestamp=tr.b.group(samples,function(sample){return sample.timestamp;});var timestamps=tr.b.dictionaryKeys(samplesByTimestamp);timestamps.sort();var groups=[];for(var i=0;i<timestamps.length;i++){var ts=timestamps[i];var group=samplesByTimestamp[ts];group.sort(function(x,y){return x.series.seriesIndex-y.series.seriesIndex;});groups.push(group);}return groups;};CounterSample.prototype={__proto__:tr.model.Event.prototype,get series(){return this.series_;},get timestamp(){return this.timestamp_;},get value(){return this.value_;},set timestamp(timestamp){this.timestamp_=timestamp;},addBoundsToRange:function(range){range.addValue(this.timestamp);},getSampleIndex:function(){return tr.b.findLowIndexInSortedArray(this.series.timestamps,function(x){return x;},this.timestamp_);},get userFriendlyName(){return'Counter sample from '+this.series_.title+' at '+tr.b.Unit.byName.timeStampInMs.format(this.timestamp);}};tr.model.EventRegistry.register(CounterSample,{name:'counterSample',pluralName:'counterSamples'});return{CounterSample:CounterSample};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/iteration_helpers.js":47,"../base/sorted_array_utils.js":58,"../base/unit.js":63,"./event.js":122,"./event_registry.js":125}],118:[function(require,module,exports){(function(global){"use strict";require("./counter_sample.js");require("./event_container.js");'use strict';global.tr.exportTo('tr.model',function(){var CounterSample=tr.model.CounterSample;function CounterSeries(name,color){tr.model.EventContainer.call(this);this.name_=name;this.color_=color;this.timestamps_=[];this.samples_=[];this.counter=undefined;this.seriesIndex=undefined;}CounterSeries.prototype={__proto__:tr.model.EventContainer.prototype,get length(){return this.timestamps_.length;},get name(){return this.name_;},get color(){return this.color_;},get samples(){return this.samples_;},get timestamps(){return this.timestamps_;},getSample:function(idx){return this.samples_[idx];},getTimestamp:function(idx){return this.timestamps_[idx];},addCounterSample:function(ts,val){var sample=new CounterSample(this,ts,val);this.addSample(sample);return sample;},addSample:function(sample){this.timestamps_.push(sample.timestamp);this.samples_.push(sample);},getStatistics:function(sampleIndices){var sum=0;var min=Number.MAX_VALUE;var max=-Number.MAX_VALUE;for(var i=0;i<sampleIndices.length;++i){var sample=this.getSample(sampleIndices[i]).value;sum+=sample;min=Math.min(sample,min);max=Math.max(sample,max);}return{min:min,max:max,avg:sum/sampleIndices.length,start:this.getSample(sampleIndices[0]).value,end:this.getSample(sampleIndices.length-1).value};},shiftTimestampsForward:function(amount){for(var i=0;i<this.timestamps_.length;++i){this.timestamps_[i]+=amount;this.samples_[i].timestamp=this.timestamps_[i];}},childEvents:function*(){yield*this.samples_;},childEventContainers:function*(){}};return{CounterSeries:CounterSeries};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./counter_sample.js":117,"./event_container.js":123}],119:[function(require,module,exports){(function(global){"use strict";require("../base/range.js");require("./counter.js");require("./cpu_slice.js");require("./process_base.js");require("./thread_time_slice.js");'use strict';global.tr.exportTo('tr.model',function(){var ColorScheme=tr.b.ColorScheme;var Counter=tr.model.Counter;var CpuSlice=tr.model.CpuSlice;function Cpu(kernel,number){if(kernel===undefined||number===undefined)throw new Error('Missing arguments');this.kernel=kernel;this.cpuNumber=number;this.slices=[];this.counters={};this.bounds_=new tr.b.Range();this.samples_=undefined;this.lastActiveTimestamp_=undefined;this.lastActiveThread_=undefined;this.lastActiveName_=undefined;this.lastActiveArgs_=undefined;}Cpu.prototype={__proto__:tr.model.EventContainer.prototype,get samples(){return this.samples_;},get userFriendlyName(){return'CPU '+this.cpuNumber;},findTopmostSlicesInThisContainer:function*(eventPredicate,opt_this){for(var s of this.slices){yield*s.findTopmostSlicesRelativeToThisSlice(eventPredicate,opt_this);}},childEvents:function*(){yield*this.slices;if(this.samples_)yield*this.samples_;},childEventContainers:function*(){yield*tr.b.dictionaryValues(this.counters);},getOrCreateCounter:function(cat,name){var id=cat+'.'+name;if(!this.counters[id])this.counters[id]=new Counter(this,id,cat,name);return this.counters[id];},getCounter:function(cat,name){var id=cat+'.'+name;if(!this.counters[id])return undefined;return this.counters[id];},shiftTimestampsForward:function(amount){for(var sI=0;sI<this.slices.length;sI++)this.slices[sI].start=this.slices[sI].start+amount;for(var id in this.counters)this.counters[id].shiftTimestampsForward(amount);},updateBounds:function(){this.bounds_.reset();if(this.slices.length){this.bounds_.addValue(this.slices[0].start);this.bounds_.addValue(this.slices[this.slices.length-1].end);}for(var id in this.counters){this.counters[id].updateBounds();this.bounds_.addRange(this.counters[id].bounds);}if(this.samples_&&this.samples_.length){this.bounds_.addValue(this.samples_[0].start);this.bounds_.addValue(this.samples_[this.samples_.length-1].end);}},createSubSlices:function(){this.samples_=this.kernel.model.samples.filter(function(sample){return sample.cpu==this;},this);},addCategoriesToDict:function(categoriesDict){for(var i=0;i<this.slices.length;i++)categoriesDict[this.slices[i].category]=true;for(var id in this.counters)categoriesDict[this.counters[id].category]=true;for(var i=0;i<this.samples_.length;i++)categoriesDict[this.samples_[i].category]=true;},indexOf:function(cpuSlice){var i=tr.b.findLowIndexInSortedArray(this.slices,function(slice){return slice.start;},cpuSlice.start);if(this.slices[i]!==cpuSlice)return undefined;return i;},closeActiveThread:function(endTimestamp,args){if(this.lastActiveThread_==undefined||this.lastActiveThread_==0)return;if(endTimestamp<this.lastActiveTimestamp_){throw new Error('The end timestamp of a thread running on CPU '+this.cpuNumber+' is before its start timestamp.');}for(var key in args){this.lastActiveArgs_[key]=args[key];}var duration=endTimestamp-this.lastActiveTimestamp_;var slice=new tr.model.CpuSlice('',this.lastActiveName_,ColorScheme.getColorIdForGeneralPurposeString(this.lastActiveName_),this.lastActiveTimestamp_,this.lastActiveArgs_,duration);slice.cpu=this;this.slices.push(slice);this.lastActiveTimestamp_=undefined;this.lastActiveThread_=undefined;this.lastActiveName_=undefined;this.lastActiveArgs_=undefined;},switchActiveThread:function(timestamp,oldThreadArgs,newThreadId,newThreadName,newThreadArgs){this.closeActiveThread(timestamp,oldThreadArgs);this.lastActiveTimestamp_=timestamp;this.lastActiveThread_=newThreadId;this.lastActiveName_=newThreadName;this.lastActiveArgs_=newThreadArgs;},getFreqStatsForRange:function(range){var stats={};function addStatsForFreq(freqSample,index){var freqEnd=index<freqSample.series_.length-1?freqSample.series_.samples_[index+1].timestamp:range.max;var freqRange=tr.b.Range.fromExplicitRange(freqSample.timestamp,freqEnd);var intersection=freqRange.findIntersection(range);if(!(freqSample.value in stats))stats[freqSample.value]=0;stats[freqSample.value]+=intersection.duration;}var freqCounter=this.getCounter('','Clock Frequency');if(freqCounter!==undefined){var freqSeries=freqCounter.getSeries(0);if(!freqSeries)return;tr.b.iterateOverIntersectingIntervals(freqSeries.samples_,function(x){return x.timestamp;},function(x,index){return index<freqSeries.length-1?freqSeries.samples_[index+1].timestamp:range.max;},range.min,range.max,addStatsForFreq);}return stats;}};Cpu.compare=function(x,y){return x.cpuNumber-y.cpuNumber;};return{Cpu:Cpu};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/range.js":53,"./counter.js":116,"./cpu_slice.js":120,"./process_base.js":150,"./thread_time_slice.js":164}],120:[function(require,module,exports){(function(global){"use strict";require("../base/range.js");require("./thread_time_slice.js");'use strict';global.tr.exportTo('tr.model',function(){var Slice=tr.model.Slice;function CpuSlice(cat,title,colorId,start,args,opt_duration){Slice.apply(this,arguments);this.threadThatWasRunning=undefined;this.cpu=undefined;}CpuSlice.prototype={__proto__:Slice.prototype,get analysisTypeName(){return'tr.ui.analysis.CpuSlice';},getAssociatedTimeslice:function(){if(!this.threadThatWasRunning)return undefined;var timeSlices=this.threadThatWasRunning.timeSlices;for(var i=0;i<timeSlices.length;i++){var timeSlice=timeSlices[i];if(timeSlice.start!==this.start)continue;if(timeSlice.duration!==this.duration)continue;return timeSlice;}return undefined;}};tr.model.EventRegistry.register(CpuSlice,{name:'cpuSlice',pluralName:'cpuSlices'});return{CpuSlice:CpuSlice};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/range.js":53,"./thread_time_slice.js":164}],121:[function(require,module,exports){(function(global){"use strict";require("../base/guid.js");require("../base/range.js");require("./event_container.js");require("./power_series.js");'use strict';global.tr.exportTo('tr.model',function(){function Device(model){if(!model)throw new Error('Must provide a model.');tr.model.EventContainer.call(this);this.powerSeries_=undefined;this.vSyncTimestamps_=[];};Device.compare=function(x,y){return x.guid-y.guid;};Device.prototype={__proto__:tr.model.EventContainer.prototype,compareTo:function(that){return Device.compare(this,that);},get userFriendlyName(){return'Device';},get userFriendlyDetails(){return'Device';},get stableId(){return'Device';},getSettingsKey:function(){return'device';},get powerSeries(){return this.powerSeries_;},set powerSeries(powerSeries){this.powerSeries_=powerSeries;},get vSyncTimestamps(){return this.vSyncTimestamps_;},set vSyncTimestamps(value){this.vSyncTimestamps_=value;},updateBounds:function(){this.bounds.reset();for(var child of this.childEventContainers()){child.updateBounds();this.bounds.addRange(child.bounds);}},shiftTimestampsForward:function(amount){for(var child of this.childEventContainers()){child.shiftTimestampsForward(amount);}for(var i=0;i<this.vSyncTimestamps_.length;i++)this.vSyncTimestamps_[i]+=amount;},addCategoriesToDict:function(categoriesDict){},childEventContainers:function*(){if(this.powerSeries_)yield this.powerSeries_;}};return{Device:Device};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/guid.js":45,"../base/range.js":53,"./event_container.js":123,"./power_series.js":148}],122:[function(require,module,exports){(function(global){"use strict";require("../base/guid.js");require("../base/range.js");require("./event_set.js");require("./selectable_item.js");require("./selection_state.js");'use strict';global.tr.exportTo('tr.model',function(){var SelectableItem=tr.model.SelectableItem;var SelectionState=tr.model.SelectionState;var IMMUTABLE_EMPTY_SET=tr.model.EventSet.IMMUTABLE_EMPTY_SET;function Event(){SelectableItem.call(this,this);this.guid_=tr.b.GUID.allocateSimple();this.selectionState=SelectionState.NONE;this.info=undefined;}Event.prototype={__proto__:SelectableItem.prototype,get guid(){return this.guid_;},get stableId(){return undefined;},get range(){var range=new tr.b.Range();this.addBoundsToRange(range);return range;},associatedAlerts:IMMUTABLE_EMPTY_SET,addAssociatedAlert:function(alert){if(this.associatedAlerts===IMMUTABLE_EMPTY_SET)this.associatedAlerts=new tr.model.EventSet();this.associatedAlerts.push(alert);},addBoundsToRange:function(range){}};return{Event:Event};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/guid.js":45,"../base/range.js":53,"./event_set.js":126,"./selectable_item.js":155,"./selection_state.js":156}],123:[function(require,module,exports){(function(global){"use strict";require("../base/base.js");require("../base/guid.js");require("../base/range.js");'use strict';global.tr.exportTo('tr.model',function(){function EventContainer(){this.guid_=tr.b.GUID.allocateSimple();this.important=true;this.bounds_=new tr.b.Range();}EventContainer.prototype={get guid(){return this.guid_;},get stableId(){throw new Error('Not implemented');},get bounds(){return this.bounds_;},updateBounds:function(){throw new Error('Not implemented');},shiftTimestampsForward:function(amount){throw new Error('Not implemented');},childEvents:function*(){},getDescendantEvents:function*(){yield*this.childEvents();for(var container of this.childEventContainers())yield*container.getDescendantEvents();},childEventContainers:function*(){},getDescendantEventContainers:function*(){yield this;for(var container of this.childEventContainers())yield*container.getDescendantEventContainers();},findTopmostSlicesInThisContainer:function*(eventPredicate,opt_this){},findTopmostSlices:function*(eventPredicate){for(var ec of this.getDescendantEventContainers())yield*ec.findTopmostSlicesInThisContainer(eventPredicate);},findTopmostSlicesNamed:function*(name){yield*this.findTopmostSlices(e=>e.title===name);}};return{EventContainer:EventContainer};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/base.js":34,"../base/guid.js":45,"../base/range.js":53}],124:[function(require,module,exports){(function(global){"use strict";require("../base/color_scheme.js");'use strict';global.tr.exportTo('tr.model',function(){var ColorScheme=tr.b.ColorScheme;function EventInfo(title,description,docLinks){this.title=title;this.description=description;this.docLinks=docLinks;this.colorId=ColorScheme.getColorIdForGeneralPurposeString(title);}return{EventInfo:EventInfo};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/color_scheme.js":38}],125:[function(require,module,exports){(function(global){"use strict";require("../base/extension_registry.js");'use strict';global.tr.exportTo('tr.model',function(){function EventRegistry(){}var options=new tr.b.ExtensionRegistryOptions(tr.b.BASIC_REGISTRY_MODE);tr.b.decorateExtensionRegistry(EventRegistry,options);EventRegistry.addEventListener('will-register',function(e){var metadata=e.typeInfo.metadata;if(metadata.name===undefined)throw new Error('Registered events must provide name metadata');if(metadata.pluralName===undefined)throw new Error('Registered events must provide pluralName metadata');if(metadata.subTypes===undefined){metadata.subTypes={};var options=new tr.b.ExtensionRegistryOptions(tr.b.TYPE_BASED_REGISTRY_MODE);options.mandatoryBaseClass=e.typeInfo.constructor;options.defaultConstructor=e.typeInfo.constructor;tr.b.decorateExtensionRegistry(metadata.subTypes,options);}else{if(!metadata.subTypes.register)throw new Error('metadata.subTypes must be an extension registry.');}e.typeInfo.constructor.subTypes=metadata.subTypes;});var eventsByTypeName=undefined;EventRegistry.getEventTypeInfoByTypeName=function(typeName){if(eventsByTypeName===undefined){eventsByTypeName={};EventRegistry.getAllRegisteredTypeInfos().forEach(function(typeInfo){eventsByTypeName[typeInfo.metadata.name]=typeInfo;});}return eventsByTypeName[typeName];};EventRegistry.addEventListener('registry-changed',function(){eventsByTypeName=undefined;});function convertCamelCaseToTitleCase(name){var result=name.replace(/[A-Z]/g,' $&');result=result.charAt(0).toUpperCase()+result.slice(1);return result;}EventRegistry.getUserFriendlySingularName=function(typeName){var typeInfo=EventRegistry.getEventTypeInfoByTypeName(typeName);var str=typeInfo.metadata.name;return convertCamelCaseToTitleCase(str);};EventRegistry.getUserFriendlyPluralName=function(typeName){var typeInfo=EventRegistry.getEventTypeInfoByTypeName(typeName);var str=typeInfo.metadata.pluralName;return convertCamelCaseToTitleCase(str);};return{EventRegistry:EventRegistry};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/extension_registry.js":41}],126:[function(require,module,exports){(function(global){"use strict";require("../base/event.js");require("../base/guid.js");require("../base/iteration_helpers.js");require("../base/range.js");require("./event_registry.js");'use strict';global.tr.exportTo('tr.model',function(){var EventRegistry=tr.model.EventRegistry;var RequestSelectionChangeEvent=tr.b.Event.bind(undefined,'requestSelectionChange',true,false);function EventSet(opt_events){this.bounds_=new tr.b.Range();this.events_=new Set();if(opt_events){if(opt_events instanceof Array){for(var event of opt_events)this.push(event);}else if(opt_events instanceof EventSet){this.addEventSet(opt_events);}else{this.push(opt_events);}}}EventSet.prototype={__proto__:Object.prototype,get bounds(){return this.bounds_;},get duration(){if(this.bounds_.isEmpty)return 0;return this.bounds_.max-this.bounds_.min;},get length(){return this.events_.size;},get guid(){return this.guid_;},*[Symbol.iterator](){for(var event of this.events_)yield event;},clear:function(){this.bounds_=new tr.b.Range();this.events_.clear();},push:function(event){if(event.guid==undefined)throw new Error('Event must have a GUID');if(!this.events_.has(event)){this.events_.add(event);if(event.addBoundsToRange)if(this.bounds_!==undefined)event.addBoundsToRange(this.bounds_);}return event;},contains:function(event){if(this.events_.has(event))return event;else return undefined;},addEventSet:function(eventSet){for(var event of eventSet)this.push(event);},intersectionIsEmpty:function(otherEventSet){return!this.some(event=>otherEventSet.contains(event));},equals:function(that){if(this.length!==that.length)return false;return this.every(event=>that.contains(event));},sortEvents:function(compare){var ary=this.toArray();ary.sort(compare);this.clear();for(var event of ary)this.push(event);},getEventsOrganizedByBaseType:function(opt_pruneEmpty){var allTypeInfos=EventRegistry.getAllRegisteredTypeInfos();var events=this.getEventsOrganizedByCallback(function(event){var maxEventIndex=-1;var maxEventTypeInfo=undefined;allTypeInfos.forEach(function(eventTypeInfo,eventIndex){if(!(event instanceof eventTypeInfo.constructor))return;if(eventIndex>maxEventIndex){maxEventIndex=eventIndex;maxEventTypeInfo=eventTypeInfo;}});if(maxEventIndex==-1){console.log(event);throw new Error('Unrecognized event type');}return maxEventTypeInfo.metadata.name;});if(!opt_pruneEmpty){allTypeInfos.forEach(function(eventTypeInfo){if(events[eventTypeInfo.metadata.name]===undefined)events[eventTypeInfo.metadata.name]=new EventSet();});}return events;},getEventsOrganizedByTitle:function(){return this.getEventsOrganizedByCallback(function(event){if(event.title===undefined)throw new Error('An event didn\'t have a title!');return event.title;});},getEventsOrganizedByCallback:function(cb,opt_this){var groupedEvents=tr.b.group(this,cb,opt_this||this);return tr.b.mapItems(groupedEvents,(_,events)=>new EventSet(events));},enumEventsOfType:function(type,func){for(var event of this)if(event instanceof type)func(event);},get userFriendlyName(){if(this.length===0){throw new Error('Empty event set');}var eventsByBaseType=this.getEventsOrganizedByBaseType(true);var eventTypeName=tr.b.dictionaryKeys(eventsByBaseType)[0];if(this.length===1){var tmp=EventRegistry.getUserFriendlySingularName(eventTypeName);return tr.b.getOnlyElement(this.events_).userFriendlyName;}var numEventTypes=tr.b.dictionaryLength(eventsByBaseType);if(numEventTypes!==1){return this.length+' events of various types';}var tmp=EventRegistry.getUserFriendlyPluralName(eventTypeName);return this.length+' '+tmp;},filter:function(fn,opt_this){var res=new EventSet();for(var event of this)if(fn.call(opt_this,event))res.push(event);return res;},toArray:function(){var ary=[];for(var event of this)ary.push(event);return ary;},forEach:function(fn,opt_this){for(var event of this)fn.call(opt_this,event);},map:function(fn,opt_this){var res=[];for(var event of this)res.push(fn.call(opt_this,event));return res;},every:function(fn,opt_this){for(var event of this)if(!fn.call(opt_this,event))return false;return true;},some:function(fn,opt_this){for(var event of this)if(fn.call(opt_this,event))return true;return false;},asDict:function(){var stableIds=[];for(var event of this)stableIds.push(event.stableId);return{'events':stableIds};},asSet:function(){return this.events_;}};EventSet.IMMUTABLE_EMPTY_SET=function(){var s=new EventSet();s.push=function(){throw new Error('Cannot push to an immutable event set');};s.addEventSet=function(){throw new Error('Cannot add to an immutable event set');};Object.freeze(s);return s;}();return{EventSet:EventSet,RequestSelectionChangeEvent:RequestSelectionChangeEvent};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/event.js":39,"../base/guid.js":45,"../base/iteration_helpers.js":47,"../base/range.js":53,"./event_registry.js":125}],127:[function(require,module,exports){(function(global){"use strict";require("../base/unit.js");require("./timed_event.js");'use strict';global.tr.exportTo('tr.model',function(){function FlowEvent(category,id,title,colorId,start,args,opt_duration){tr.model.TimedEvent.call(this,start);this.category=category||'';this.title=title;this.colorId=colorId;this.start=start;this.args=args;this.id=id;this.startSlice=undefined;this.endSlice=undefined;this.startStackFrame=undefined;this.endStackFrame=undefined;if(opt_duration!==undefined)this.duration=opt_duration;}FlowEvent.prototype={__proto__:tr.model.TimedEvent.prototype,get userFriendlyName(){return'Flow event named '+this.title+' at '+tr.b.Unit.byName.timeStampInMs.format(this.timestamp);}};tr.model.EventRegistry.register(FlowEvent,{name:'flowEvent',pluralName:'flowEvents'});return{FlowEvent:FlowEvent};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/unit.js":63,"./timed_event.js":166}],128:[function(require,module,exports){(function(global){"use strict";require("../base/color_scheme.js");require("../base/statistics.js");require("./event.js");require("./event_set.js");'use strict';global.tr.exportTo('tr.model',function(){var ColorScheme=tr.b.ColorScheme;var Statistics=tr.b.Statistics;var FRAME_PERF_CLASS={GOOD:'good',BAD:'bad',TERRIBLE:'terrible',NEUTRAL:'generic_work'};function Frame(associatedEvents,threadTimeRanges,opt_args){tr.model.Event.call(this);this.threadTimeRanges=threadTimeRanges;this.associatedEvents=new tr.model.EventSet(associatedEvents);this.args=opt_args||{};this.title='Frame';this.start=Statistics.min(threadTimeRanges,function(x){return x.start;});this.end=Statistics.max(threadTimeRanges,function(x){return x.end;});this.totalDuration=Statistics.sum(threadTimeRanges,function(x){return x.end-x.start;});this.perfClass=FRAME_PERF_CLASS.NEUTRAL;};Frame.prototype={__proto__:tr.model.Event.prototype,set perfClass(perfClass){this.colorId=ColorScheme.getColorIdForReservedName(perfClass);this.perfClass_=perfClass;},get perfClass(){return this.perfClass_;},shiftTimestampsForward:function(amount){this.start+=amount;this.end+=amount;for(var i=0;i<this.threadTimeRanges.length;i++){this.threadTimeRanges[i].start+=amount;this.threadTimeRanges[i].end+=amount;}},addBoundsToRange:function(range){range.addValue(this.start);range.addValue(this.end);}};tr.model.EventRegistry.register(Frame,{name:'frame',pluralName:'frames'});return{Frame:Frame,FRAME_PERF_CLASS:FRAME_PERF_CLASS};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/color_scheme.js":38,"../base/statistics.js":59,"./event.js":122,"./event_set.js":126}],129:[function(require,module,exports){(function(global){"use strict";require("../base/iteration_helpers.js");require("../base/unit.js");require("./container_memory_dump.js");require("./event_registry.js");require("./memory_allocator_dump.js");require("../value/numeric.js");'use strict';global.tr.exportTo('tr.model',function(){function GlobalMemoryDump(model,start){tr.model.ContainerMemoryDump.call(this,start);this.model=model;this.processMemoryDumps={};}var SIZE_NUMERIC_NAME=tr.model.MemoryAllocatorDump.SIZE_NUMERIC_NAME;var EFFECTIVE_SIZE_NUMERIC_NAME=tr.model.MemoryAllocatorDump.EFFECTIVE_SIZE_NUMERIC_NAME;var MemoryAllocatorDumpInfoType=tr.model.MemoryAllocatorDumpInfoType;var PROVIDED_SIZE_LESS_THAN_AGGREGATED_CHILDREN=MemoryAllocatorDumpInfoType.PROVIDED_SIZE_LESS_THAN_AGGREGATED_CHILDREN;var PROVIDED_SIZE_LESS_THAN_LARGEST_OWNER=MemoryAllocatorDumpInfoType.PROVIDED_SIZE_LESS_THAN_LARGEST_OWNER;function inPlaceFilter(array,predicate,opt_this){opt_this=opt_this||this;var nextPosition=0;for(var i=0;i<array.length;i++){if(!predicate.call(opt_this,array[i],i))continue;if(nextPosition<i)array[nextPosition]=array[i];nextPosition++;}if(nextPosition<array.length)array.length=nextPosition;}function getSize(dump){var numeric=dump.numerics[SIZE_NUMERIC_NAME];if(numeric===undefined)return 0;return numeric.value;}function hasSize(dump){return dump.numerics[SIZE_NUMERIC_NAME]!==undefined;}function optional(value,defaultValue){if(value===undefined)return defaultValue;return value;}GlobalMemoryDump.prototype={__proto__:tr.model.ContainerMemoryDump.prototype,get userFriendlyName(){return'Global memory dump at '+tr.b.Unit.byName.timeStampInMs.format(this.start);},get containerName(){return'global space';},finalizeGraph:function(){this.removeWeakDumps();this.setUpTracingOverheadOwnership();this.aggregateNumerics();this.calculateSizes();this.calculateEffectiveSizes();this.discountTracingOverheadFromVmRegions();this.forceRebuildingMemoryAllocatorDumpByFullNameIndices();},removeWeakDumps:function(){this.traverseAllocatorDumpsInDepthFirstPreOrder(function(dump){if(dump.weak)return;if(dump.owns!==undefined&&dump.owns.target.weak||dump.parent!==undefined&&dump.parent.weak){dump.weak=true;}});function removeWeakDumpsFromListRecursively(dumps){inPlaceFilter(dumps,function(dump){if(dump.weak){return false;}removeWeakDumpsFromListRecursively(dump.children);inPlaceFilter(dump.ownedBy,function(ownershipLink){return!ownershipLink.source.weak;});return true;});}this.iterateContainerDumps(function(containerDump){var memoryAllocatorDumps=containerDump.memoryAllocatorDumps;if(memoryAllocatorDumps!==undefined)removeWeakDumpsFromListRecursively(memoryAllocatorDumps);});},calculateSizes:function(){this.traverseAllocatorDumpsInDepthFirstPostOrder(this.calculateMemoryAllocatorDumpSize_.bind(this));},calculateMemoryAllocatorDumpSize_:function(dump){var shouldDefineSize=false;function getDependencySize(dependencyDump){var numeric=dependencyDump.numerics[SIZE_NUMERIC_NAME];if(numeric===undefined)return 0;shouldDefineSize=true;return numeric.value;}var sizeNumeric=dump.numerics[SIZE_NUMERIC_NAME];var size=0;var checkDependencySizeIsConsistent=function(){};if(sizeNumeric!==undefined){size=sizeNumeric.value;shouldDefineSize=true;if(sizeNumeric.unit!==tr.b.Unit.byName.sizeInBytes_smallerIsBetter){this.model.importWarning({type:'memory_dump_parse_error',message:'Invalid unit of \'size\' numeric of memory allocator '+'dump '+dump.quantifiedName+': '+sizeNumeric.unit.unitName+'.'});}checkDependencySizeIsConsistent=function(dependencySize,dependencyInfoType,dependencyName){if(size>=dependencySize)return;this.model.importWarning({type:'memory_dump_parse_error',message:'Size provided by memory allocator dump \''+dump.fullName+'\''+tr.b.Unit.byName.sizeInBytes.format(size)+') is less than '+dependencyName+' ('+tr.b.Unit.byName.sizeInBytes.format(dependencySize)+').'});dump.infos.push({type:dependencyInfoType,providedSize:size,dependencySize:dependencySize});}.bind(this);}var aggregatedChildrenSize=0;var allOverlaps={};dump.children.forEach(function(childDump){function aggregateDescendantDump(descendantDump){var ownedDumpLink=descendantDump.owns;if(ownedDumpLink!==undefined&&ownedDumpLink.target.isDescendantOf(dump)){var ownedChildDump=ownedDumpLink.target;while(ownedChildDump.parent!==dump)ownedChildDump=ownedChildDump.parent;if(childDump!==ownedChildDump){var ownedBySiblingSize=getDependencySize(descendantDump);if(ownedBySiblingSize>0){var previousTotalOwnedBySiblingSize=ownedChildDump.ownedBySiblingSizes.get(childDump)||0;var updatedTotalOwnedBySiblingSize=previousTotalOwnedBySiblingSize+ownedBySiblingSize;ownedChildDump.ownedBySiblingSizes.set(childDump,updatedTotalOwnedBySiblingSize);}}return;}if(descendantDump.children.length===0){aggregatedChildrenSize+=getDependencySize(descendantDump);return;}descendantDump.children.forEach(aggregateDescendantDump);}aggregateDescendantDump(childDump);});checkDependencySizeIsConsistent(aggregatedChildrenSize,PROVIDED_SIZE_LESS_THAN_AGGREGATED_CHILDREN,'the aggregated size of its children');var largestOwnerSize=0;dump.ownedBy.forEach(function(ownershipLink){var owner=ownershipLink.source;var ownerSize=getDependencySize(owner);largestOwnerSize=Math.max(largestOwnerSize,ownerSize);});checkDependencySizeIsConsistent(largestOwnerSize,PROVIDED_SIZE_LESS_THAN_LARGEST_OWNER,'the size of its largest owner');if(!shouldDefineSize){delete dump.numerics[SIZE_NUMERIC_NAME];return;}size=Math.max(size,aggregatedChildrenSize,largestOwnerSize);dump.numerics[SIZE_NUMERIC_NAME]=new tr.v.ScalarNumeric(tr.b.Unit.byName.sizeInBytes_smallerIsBetter,size);if(aggregatedChildrenSize<size&&dump.children!==undefined&&dump.children.length>0){var virtualChild=new tr.model.MemoryAllocatorDump(dump.containerMemoryDump,dump.fullName+'/<unspecified>');virtualChild.parent=dump;dump.children.unshift(virtualChild);virtualChild.numerics[SIZE_NUMERIC_NAME]=new tr.v.ScalarNumeric(tr.b.Unit.byName.sizeInBytes_smallerIsBetter,size-aggregatedChildrenSize);}},calculateEffectiveSizes:function(){this.traverseAllocatorDumpsInDepthFirstPostOrder(this.calculateDumpSubSizes_.bind(this));this.traverseAllocatorDumpsInDepthFirstPostOrder(this.calculateDumpOwnershipCoefficient_.bind(this));this.traverseAllocatorDumpsInDepthFirstPreOrder(this.calculateDumpCumulativeOwnershipCoefficient_.bind(this));this.traverseAllocatorDumpsInDepthFirstPostOrder(this.calculateDumpEffectiveSize_.bind(this));},calculateDumpSubSizes_:function(dump){if(!hasSize(dump))return;if(dump.children===undefined||dump.children.length===0){var size=getSize(dump);dump.notOwningSubSize_=size;dump.notOwnedSubSize_=size;return;}var notOwningSubSize=0;dump.children.forEach(function(childDump){if(childDump.owns!==undefined)return;notOwningSubSize+=optional(childDump.notOwningSubSize_,0);});dump.notOwningSubSize_=notOwningSubSize;var notOwnedSubSize=0;dump.children.forEach(function(childDump){if(childDump.ownedBy.length===0){notOwnedSubSize+=optional(childDump.notOwnedSubSize_,0);return;}var largestChildOwnerSize=0;childDump.ownedBy.forEach(function(ownershipLink){largestChildOwnerSize=Math.max(largestChildOwnerSize,getSize(ownershipLink.source));});notOwnedSubSize+=getSize(childDump)-largestChildOwnerSize;});dump.notOwnedSubSize_=notOwnedSubSize;},calculateDumpOwnershipCoefficient_:function(dump){if(!hasSize(dump))return;if(dump.ownedBy.length===0)return;var owners=dump.ownedBy.map(function(ownershipLink){return{dump:ownershipLink.source,importance:optional(ownershipLink.importance,0),notOwningSubSize:optional(ownershipLink.source.notOwningSubSize_,0)};});owners.sort(function(a,b){if(a.importance===b.importance)return a.notOwningSubSize-b.notOwningSubSize;return b.importance-a.importance;});var currentImportanceStartPos=0;var alreadyAttributedSubSize=0;while(currentImportanceStartPos<owners.length){var currentImportance=owners[currentImportanceStartPos].importance;var nextImportanceStartPos=currentImportanceStartPos+1;while(nextImportanceStartPos<owners.length&&owners[nextImportanceStartPos].importance===currentImportance){nextImportanceStartPos++;}var attributedNotOwningSubSize=0;for(var pos=currentImportanceStartPos;pos<nextImportanceStartPos;pos++){var owner=owners[pos];var notOwningSubSize=owner.notOwningSubSize;if(notOwningSubSize>alreadyAttributedSubSize){attributedNotOwningSubSize+=(notOwningSubSize-alreadyAttributedSubSize)/(nextImportanceStartPos-pos);alreadyAttributedSubSize=notOwningSubSize;}var owningCoefficient=0;if(notOwningSubSize!==0)owningCoefficient=attributedNotOwningSubSize/notOwningSubSize;owner.dump.owningCoefficient_=owningCoefficient;}currentImportanceStartPos=nextImportanceStartPos;}var notOwnedSubSize=optional(dump.notOwnedSubSize_,0);var remainderSubSize=notOwnedSubSize-alreadyAttributedSubSize;var ownedCoefficient=0;if(notOwnedSubSize!==0)ownedCoefficient=remainderSubSize/notOwnedSubSize;dump.ownedCoefficient_=ownedCoefficient;},calculateDumpCumulativeOwnershipCoefficient_:function(dump){if(!hasSize(dump))return;var cumulativeOwnedCoefficient=optional(dump.ownedCoefficient_,1);var parent=dump.parent;if(dump.parent!==undefined)cumulativeOwnedCoefficient*=dump.parent.cumulativeOwnedCoefficient_;dump.cumulativeOwnedCoefficient_=cumulativeOwnedCoefficient;var cumulativeOwningCoefficient;if(dump.owns!==undefined){cumulativeOwningCoefficient=dump.owningCoefficient_*dump.owns.target.cumulativeOwningCoefficient_;}else if(dump.parent!==undefined){cumulativeOwningCoefficient=dump.parent.cumulativeOwningCoefficient_;}else{cumulativeOwningCoefficient=1;}dump.cumulativeOwningCoefficient_=cumulativeOwningCoefficient;},calculateDumpEffectiveSize_:function(dump){if(!hasSize(dump)){delete dump.numerics[EFFECTIVE_SIZE_NUMERIC_NAME];return;}var effectiveSize;if(dump.children===undefined||dump.children.length===0){effectiveSize=getSize(dump)*dump.cumulativeOwningCoefficient_*dump.cumulativeOwnedCoefficient_;}else{effectiveSize=0;dump.children.forEach(function(childDump){if(!hasSize(childDump))return;effectiveSize+=childDump.numerics[EFFECTIVE_SIZE_NUMERIC_NAME].value;});}dump.numerics[EFFECTIVE_SIZE_NUMERIC_NAME]=new tr.v.ScalarNumeric(tr.b.Unit.byName.sizeInBytes_smallerIsBetter,effectiveSize);},aggregateNumerics:function(){this.iterateRootAllocatorDumps(function(dump){dump.aggregateNumericsRecursively(this.model);});this.iterateRootAllocatorDumps(this.propagateNumericsAndDiagnosticsRecursively);tr.b.iterItems(this.processMemoryDumps,function(pid,processMemoryDump){processMemoryDump.iterateRootAllocatorDumps(function(dump){dump.aggregateNumericsRecursively(this.model);},this);},this);},propagateNumericsAndDiagnosticsRecursively:function(globalAllocatorDump){['numerics','diagnostics'].forEach(function(field){tr.b.iterItems(globalAllocatorDump[field],function(name,value){globalAllocatorDump.ownedBy.forEach(function(ownershipLink){var processAllocatorDump=ownershipLink.source;if(processAllocatorDump[field][name]!==undefined){return;}processAllocatorDump[field][name]=value;});});});globalAllocatorDump.children.forEach(this.propagateNumericsAndDiagnosticsRecursively,this);},setUpTracingOverheadOwnership:function(){tr.b.iterItems(this.processMemoryDumps,function(pid,dump){dump.setUpTracingOverheadOwnership(this.model);},this);},discountTracingOverheadFromVmRegions:function(){tr.b.iterItems(this.processMemoryDumps,function(pid,dump){dump.discountTracingOverheadFromVmRegions(this.model);},this);},forceRebuildingMemoryAllocatorDumpByFullNameIndices:function(){this.iterateContainerDumps(function(containerDump){containerDump.forceRebuildingMemoryAllocatorDumpByFullNameIndex();});},iterateContainerDumps:function(fn){fn.call(this,this);tr.b.iterItems(this.processMemoryDumps,function(pid,processDump){fn.call(this,processDump);},this);},iterateAllRootAllocatorDumps:function(fn){this.iterateContainerDumps(function(containerDump){containerDump.iterateRootAllocatorDumps(fn,this);});},traverseAllocatorDumpsInDepthFirstPostOrder:function(fn){var visitedDumps=new WeakSet();var openDumps=new WeakSet();function visit(dump){if(visitedDumps.has(dump))return;if(openDumps.has(dump))throw new Error(dump.userFriendlyName+' contains a cycle');openDumps.add(dump);dump.ownedBy.forEach(function(ownershipLink){visit.call(this,ownershipLink.source);},this);dump.children.forEach(visit,this);fn.call(this,dump);visitedDumps.add(dump);openDumps.delete(dump);}this.iterateAllRootAllocatorDumps(visit);},traverseAllocatorDumpsInDepthFirstPreOrder:function(fn){var visitedDumps=new WeakSet();function visit(dump){if(visitedDumps.has(dump))return;if(dump.owns!==undefined&&!visitedDumps.has(dump.owns.target))return;if(dump.parent!==undefined&&!visitedDumps.has(dump.parent))return;fn.call(this,dump);visitedDumps.add(dump);dump.ownedBy.forEach(function(ownershipLink){visit.call(this,ownershipLink.source);},this);dump.children.forEach(visit,this);}this.iterateAllRootAllocatorDumps(visit);}};tr.model.EventRegistry.register(GlobalMemoryDump,{name:'globalMemoryDump',pluralName:'globalMemoryDumps'});return{GlobalMemoryDump:GlobalMemoryDump};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/iteration_helpers.js":47,"../base/unit.js":63,"../value/numeric.js":196,"./container_memory_dump.js":115,"./event_registry.js":125,"./memory_allocator_dump.js":140}],130:[function(require,module,exports){(function(global){"use strict";require("../base/base.js");'use strict';global.tr.exportTo('tr.model',function(){function HeapEntry(heapDump,leafStackFrame,objectTypeName,size,count){this.heapDump=heapDump;this.leafStackFrame=leafStackFrame;this.objectTypeName=objectTypeName;this.size=size;this.count=count;}function HeapDump(processMemoryDump,allocatorName){this.processMemoryDump=processMemoryDump;this.allocatorName=allocatorName;this.entries=[];}HeapDump.prototype={addEntry:function(leafStackFrame,objectTypeName,size,count){var entry=new HeapEntry(this,leafStackFrame,objectTypeName,size,count);this.entries.push(entry);return entry;}};return{HeapEntry:HeapEntry,HeapDump:HeapDump};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/base.js":34}],131:[function(require,module,exports){(function(global){"use strict";require("../../base/iteration_helpers.js");require("./chrome_process_helper.js");'use strict';global.tr.exportTo('tr.model.helpers',function(){function ChromeBrowserHelper(modelHelper,process){tr.model.helpers.ChromeProcessHelper.call(this,modelHelper,process);this.mainThread_=process.findAtMostOneThreadNamed('CrBrowserMain');if(!process.name)process.name=ChromeBrowserHelper.PROCESS_NAME;}ChromeBrowserHelper.PROCESS_NAME='Browser';ChromeBrowserHelper.isBrowserProcess=function(process){return!!process.findAtMostOneThreadNamed('CrBrowserMain');};ChromeBrowserHelper.prototype={__proto__:tr.model.helpers.ChromeProcessHelper.prototype,get browserName(){var hasInProcessRendererThread=this.process.findAllThreadsNamed('Chrome_InProcRendererThread').length>0;return hasInProcessRendererThread?'webview':'chrome';},get rendererHelpers(){return this.modelHelper.rendererHelpers;},getLoadingEventsInRange:function(rangeOfInterest){return this.getAllAsyncSlicesMatching(function(slice){return slice.title.indexOf('WebContentsImpl Loading')===0&&rangeOfInterest.intersectsExplicitRangeInclusive(slice.start,slice.end);});},getCommitProvisionalLoadEventsInRange:function(rangeOfInterest){return this.getAllAsyncSlicesMatching(function(slice){return slice.title==='RenderFrameImpl::didCommitProvisionalLoad'&&rangeOfInterest.intersectsExplicitRangeInclusive(slice.start,slice.end);});},get hasLatencyEvents(){var hasLatency=false;for(var thread of this.modelHelper.model.getAllThreads())for(var event of thread.getDescendantEvents()){if(!event.isTopLevel)continue;if(!(event instanceof tr.e.cc.InputLatencyAsyncSlice))continue;hasLatency=true;}return hasLatency;},getLatencyEventsInRange:function(rangeOfInterest){return this.getAllAsyncSlicesMatching(function(slice){return slice.title.indexOf('InputLatency')===0&&rangeOfInterest.intersectsExplicitRangeInclusive(slice.start,slice.end);});},getAllAsyncSlicesMatching:function(pred,opt_this){var events=[];this.iterAllThreads(function(thread){for(var slice of thread.getDescendantEvents())if(pred.call(opt_this,slice))events.push(slice);});return events;},getAllNetworkEventsInRange:function(rangeOfInterest){var networkEvents=[];this.modelHelper.model.getAllThreads().forEach(function(thread){thread.asyncSliceGroup.slices.forEach(function(slice){var match=false;if(slice.category=='net'||slice.category=='disabled-by-default-netlog'||slice.category=='netlog'){match=true;}if(!match)return;if(rangeOfInterest.intersectsExplicitRangeInclusive(slice.start,slice.end))networkEvents.push(slice);});});return networkEvents;},iterAllThreads:function(func,opt_this){tr.b.iterItems(this.process.threads,function(tid,thread){func.call(opt_this,thread);});tr.b.iterItems(this.rendererHelpers,function(pid,rendererHelper){var rendererProcess=rendererHelper.process;tr.b.iterItems(rendererProcess.threads,function(tid,thread){func.call(opt_this,thread);});},this);}};return{ChromeBrowserHelper:ChromeBrowserHelper};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../../base/iteration_helpers.js":47,"./chrome_process_helper.js":134}],132:[function(require,module,exports){(function(global){"use strict";require("./chrome_process_helper.js");'use strict';global.tr.exportTo('tr.model.helpers',function(){function ChromeGpuHelper(modelHelper,process){tr.model.helpers.ChromeProcessHelper.call(this,modelHelper,process);this.mainThread_=process.findAtMostOneThreadNamed('CrGpuMain');if(!process.name)process.name=ChromeGpuHelper.PROCESS_NAME;};ChromeGpuHelper.PROCESS_NAME='GPU Process';ChromeGpuHelper.isGpuProcess=function(process){if(process.findAtMostOneThreadNamed('CrBrowserMain')||process.findAtMostOneThreadNamed('CrRendererMain'))return false;return process.findAtMostOneThreadNamed('CrGpuMain');};ChromeGpuHelper.prototype={__proto__:tr.model.helpers.ChromeProcessHelper.prototype,get mainThread(){return this.mainThread_;}};return{ChromeGpuHelper:ChromeGpuHelper};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./chrome_process_helper.js":134}],133:[function(require,module,exports){(function(global){"use strict";require("../../base/guid.js");require("../../base/iteration_helpers.js");require("./chrome_browser_helper.js");require("./chrome_gpu_helper.js");require("./chrome_renderer_helper.js");'use strict';global.tr.exportTo('tr.model.helpers',function(){function findChromeBrowserProcesses(model){return model.getAllProcesses(tr.model.helpers.ChromeBrowserHelper.isBrowserProcess);}function findChromeRenderProcesses(model){return model.getAllProcesses(tr.model.helpers.ChromeRendererHelper.isRenderProcess);}function findChromeGpuProcess(model){var gpuProcesses=model.getAllProcesses(tr.model.helpers.ChromeGpuHelper.isGpuProcess);if(gpuProcesses.length!==1)return undefined;return gpuProcesses[0];}function ChromeModelHelper(model){this.model_=model;var browserProcesses=findChromeBrowserProcesses(model);this.browserHelpers_=browserProcesses.map(p=>new tr.model.helpers.ChromeBrowserHelper(this,p));var gpuProcess=findChromeGpuProcess(model);if(gpuProcess){this.gpuHelper_=new tr.model.helpers.ChromeGpuHelper(this,gpuProcess);}else{this.gpuHelper_=undefined;}var rendererProcesses_=findChromeRenderProcesses(model);this.rendererHelpers_={};rendererProcesses_.forEach(function(renderProcess){var rendererHelper=new tr.model.helpers.ChromeRendererHelper(this,renderProcess);this.rendererHelpers_[rendererHelper.pid]=rendererHelper;},this);}ChromeModelHelper.guid=tr.b.GUID.allocateSimple();ChromeModelHelper.supportsModel=function(model){if(findChromeBrowserProcesses(model).length)return true;if(findChromeRenderProcesses(model).length)return true;return false;};ChromeModelHelper.prototype={get pid(){throw new Error('woah');},get process(){throw new Error('woah');},get model(){return this.model_;},get browserProcess(){if(this.browserHelper===undefined)return undefined;return this.browserHelper.process;},get browserHelper(){return this.browserHelpers_[0];},get browserHelpers(){return this.browserHelpers_;},get gpuHelper(){return this.gpuHelper_;},get rendererHelpers(){return this.rendererHelpers_;}};return{ChromeModelHelper:ChromeModelHelper};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../../base/guid.js":45,"../../base/iteration_helpers.js":47,"./chrome_browser_helper.js":131,"./chrome_gpu_helper.js":132,"./chrome_renderer_helper.js":135}],134:[function(require,module,exports){(function(global){"use strict";require("../../base/base.js");'use strict';global.tr.exportTo('tr.model.helpers',function(){var MAIN_FRAMETIME_TYPE='main_frametime_type';var IMPL_FRAMETIME_TYPE='impl_frametime_type';var MAIN_RENDERING_STATS='BenchmarkInstrumentation::MainThreadRenderingStats';var IMPL_RENDERING_STATS='BenchmarkInstrumentation::ImplThreadRenderingStats';function getSlicesIntersectingRange(rangeOfInterest,slices){var slicesInFilterRange=[];for(var i=0;i<slices.length;i++){var slice=slices[i];if(rangeOfInterest.intersectsExplicitRangeInclusive(slice.start,slice.end))slicesInFilterRange.push(slice);}return slicesInFilterRange;}function ChromeProcessHelper(modelHelper,process){this.modelHelper=modelHelper;this.process=process;}ChromeProcessHelper.prototype={get pid(){return this.process.pid;},getFrameEventsInRange:function(frametimeType,range){var titleToGet=frametimeType===MAIN_FRAMETIME_TYPE?MAIN_RENDERING_STATS:IMPL_RENDERING_STATS;var frameEvents=[];for(var event of this.process.getDescendantEvents())if(event.title===titleToGet)if(range.intersectsExplicitRangeInclusive(event.start,event.end))frameEvents.push(event);frameEvents.sort(function(a,b){return a.start-b.start;});return frameEvents;}};function getFrametimeDataFromEvents(frameEvents){var frametimeData=[];for(var i=1;i<frameEvents.length;i++){var diff=frameEvents[i].start-frameEvents[i-1].start;frametimeData.push({'x':frameEvents[i].start,'frametime':diff});}return frametimeData;}return{ChromeProcessHelper:ChromeProcessHelper,MAIN_FRAMETIME_TYPE:MAIN_FRAMETIME_TYPE,IMPL_FRAMETIME_TYPE:IMPL_FRAMETIME_TYPE,MAIN_RENDERING_STATS:MAIN_RENDERING_STATS,IMPL_RENDERING_STATS:IMPL_RENDERING_STATS,getSlicesIntersectingRange:getSlicesIntersectingRange,getFrametimeDataFromEvents:getFrametimeDataFromEvents};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../../base/base.js":34}],135:[function(require,module,exports){(function(global){"use strict";require("../../base/range.js");require("../../extras/chrome/chrome_user_friendly_category_driver.js");require("./chrome_process_helper.js");'use strict';global.tr.exportTo('tr.model.helpers',function(){function ChromeRendererHelper(modelHelper,process){tr.model.helpers.ChromeProcessHelper.call(this,modelHelper,process);this.mainThread_=process.findAtMostOneThreadNamed('CrRendererMain');this.compositorThread_=process.findAtMostOneThreadNamed('Compositor');this.rasterWorkerThreads_=process.findAllThreadsMatching(function(t){if(t.name===undefined)return false;if(t.name.indexOf('CompositorTileWorker')===0)return true;if(t.name.indexOf('CompositorRasterWorker')===0)return true;return false;});this.isChromeTracingUI_=process.labels!==undefined&&process.labels.length===1&&process.labels[0]==='chrome://tracing';if(!process.name)process.name=ChromeRendererHelper.PROCESS_NAME;}ChromeRendererHelper.PROCESS_NAME='Renderer';ChromeRendererHelper.isRenderProcess=function(process){if(process.findAtMostOneThreadNamed('CrRendererMain'))return true;if(process.findAtMostOneThreadNamed('Compositor'))return true;return false;};ChromeRendererHelper.prototype={__proto__:tr.model.helpers.ChromeProcessHelper.prototype,get mainThread(){return this.mainThread_;},get compositorThread(){return this.compositorThread_;},get rasterWorkerThreads(){return this.rasterWorkerThreads_;},get isChromeTracingUI(){return this.isChromeTracingUI_;},generateTimeBreakdownTree:function(start,end){if(this.mainThread===null)return;var breakdownMap={};var range=tr.b.Range.fromExplicitRange(start,end);for(var title of tr.e.chrome.ChromeUserFriendlyCategoryDriver.ALL_TITLES){breakdownMap[title]={total:0,events:{}};}breakdownMap['idle']={total:0,events:{}};var totalIdleTime=end-start;for(var event of this.mainThread.getDescendantEvents()){if(!range.intersectsExplicitRangeExclusive(event.start,event.end))continue;if(event.selfTime===undefined)continue;var title=tr.e.chrome.ChromeUserFriendlyCategoryDriver.fromEvent(event);var wallTimeIntersectionRatio=0;if(event.duration>0){wallTimeIntersectionRatio=range.findExplicitIntersectionDuration(event.start,event.end)/event.duration;}var v8Runtime=event.args['runtime-call-stat'];if(v8Runtime!==undefined){try{var v8RuntimeObject=JSON.parse(v8Runtime);for(var runtimeCall in v8RuntimeObject){if(v8RuntimeObject[runtimeCall].length==2){if(breakdownMap['v8_runtime'].events[runtimeCall]===undefined){breakdownMap['v8_runtime'].events[runtimeCall]=0;}var runtimeTime=v8RuntimeObject[runtimeCall][1]*wallTimeIntersectionRatio/1000;breakdownMap['v8_runtime'].total+=runtimeTime;breakdownMap['v8_runtime'].events[runtimeCall]+=runtimeTime;}}}catch(e){console.warn(e);}}var approximatedSelfTimeContribution=event.selfTime*wallTimeIntersectionRatio;breakdownMap[title].total+=approximatedSelfTimeContribution;if(breakdownMap[title].events[event.title]===undefined)breakdownMap[title].events[event.title]=0;breakdownMap[title].events[event.title]+=approximatedSelfTimeContribution;totalIdleTime-=approximatedSelfTimeContribution;}breakdownMap['idle'].total=totalIdleTime;return breakdownMap;}};return{ChromeRendererHelper:ChromeRendererHelper};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../../base/range.js":53,"../../extras/chrome/chrome_user_friendly_category_driver.js":69,"./chrome_process_helper.js":134}],136:[function(require,module,exports){(function(global){"use strict";require("../base/unit.js");require("./timed_event.js");'use strict';global.tr.exportTo('tr.model',function(){var InstantEventType={GLOBAL:1,PROCESS:2};function InstantEvent(category,title,colorId,start,args){tr.model.TimedEvent.call(this,start);this.category=category||'';this.title=title;this.colorId=colorId;this.args=args;this.type=undefined;}InstantEvent.prototype={__proto__:tr.model.TimedEvent.prototype};function GlobalInstantEvent(category,title,colorId,start,args){InstantEvent.apply(this,arguments);this.type=InstantEventType.GLOBAL;}GlobalInstantEvent.prototype={__proto__:InstantEvent.prototype,get userFriendlyName(){return'Global instant event '+this.title+' @ '+tr.b.Unit.byName.timeStampInMs.format(start);}};function ProcessInstantEvent(category,title,colorId,start,args){InstantEvent.apply(this,arguments);this.type=InstantEventType.PROCESS;}ProcessInstantEvent.prototype={__proto__:InstantEvent.prototype,get userFriendlyName(){return'Process-level instant event '+this.title+' @ '+tr.b.Unit.byName.timeStampInMs.format(start);}};tr.model.EventRegistry.register(InstantEvent,{name:'instantEvent',pluralName:'instantEvents'});return{GlobalInstantEvent:GlobalInstantEvent,ProcessInstantEvent:ProcessInstantEvent,InstantEventType:InstantEventType,InstantEvent:InstantEvent};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/unit.js":63,"./timed_event.js":166}],137:[function(require,module,exports){(function(global){"use strict";require("../base/iteration_helpers.js");require("./event_set.js");'use strict';global.tr.exportTo('tr.model',function(){function getAssociatedEvents(irs){var allAssociatedEvents=new tr.model.EventSet();irs.forEach(function(ir){ir.associatedEvents.forEach(function(event){if(event instanceof tr.model.FlowEvent)return;allAssociatedEvents.push(event);});});return allAssociatedEvents;}function getUnassociatedEvents(model,associatedEvents){var unassociatedEvents=new tr.model.EventSet();for(var proc of model.getAllProcesses())for(var thread of tr.b.dictionaryValues(proc.threads))for(var event of thread.sliceGroup.getDescendantEvents())if(!associatedEvents.contains(event))unassociatedEvents.push(event);return unassociatedEvents;}function getTotalCpuDuration(events){var cpuMs=0;events.forEach(function(event){if(event.cpuSelfTime)cpuMs+=event.cpuSelfTime;});return cpuMs;}function getIRCoverageFromModel(model){var associatedEvents=getAssociatedEvents(model.userModel.expectations);if(!associatedEvents.length)return undefined;var unassociatedEvents=getUnassociatedEvents(model,associatedEvents);var associatedCpuMs=getTotalCpuDuration(associatedEvents);var unassociatedCpuMs=getTotalCpuDuration(unassociatedEvents);var totalEventCount=associatedEvents.length+unassociatedEvents.length;var totalCpuMs=associatedCpuMs+unassociatedCpuMs;var coveredEventsCpuTimeRatio=undefined;if(totalCpuMs!==0)coveredEventsCpuTimeRatio=associatedCpuMs/totalCpuMs;return{associatedEventsCount:associatedEvents.length,unassociatedEventsCount:unassociatedEvents.length,associatedEventsCpuTimeMs:associatedCpuMs,unassociatedEventsCpuTimeMs:unassociatedCpuMs,coveredEventsCountRatio:associatedEvents.length/totalEventCount,coveredEventsCpuTimeRatio:coveredEventsCpuTimeRatio};}return{getIRCoverageFromModel:getIRCoverageFromModel,getAssociatedEvents:getAssociatedEvents,getUnassociatedEvents:getUnassociatedEvents};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/iteration_helpers.js":47,"./event_set.js":126}],138:[function(require,module,exports){(function(global){"use strict";require("../base/iteration_helpers.js");require("./cpu.js");require("./process_base.js");'use strict';global.tr.exportTo('tr.model',function(){var Cpu=tr.model.Cpu;var ProcessBase=tr.model.ProcessBase;function Kernel(model){ProcessBase.call(this,model);this.cpus={};this.softwareMeasuredCpuCount_=undefined;};Kernel.compare=function(x,y){return 0;};Kernel.prototype={__proto__:ProcessBase.prototype,compareTo:function(that){return Kernel.compare(this,that);},get userFriendlyName(){return'Kernel';},get userFriendlyDetails(){return'Kernel';},get stableId(){return'Kernel';},getOrCreateCpu:function(cpuNumber){if(!this.cpus[cpuNumber])this.cpus[cpuNumber]=new Cpu(this,cpuNumber);return this.cpus[cpuNumber];},get softwareMeasuredCpuCount(){return this.softwareMeasuredCpuCount_;},set softwareMeasuredCpuCount(softwareMeasuredCpuCount){if(this.softwareMeasuredCpuCount_!==undefined&&this.softwareMeasuredCpuCount_!==softwareMeasuredCpuCount){throw new Error('Cannot change the softwareMeasuredCpuCount once it is set');}this.softwareMeasuredCpuCount_=softwareMeasuredCpuCount;},get bestGuessAtCpuCount(){var realCpuCount=tr.b.dictionaryLength(this.cpus);if(realCpuCount!==0)return realCpuCount;return this.softwareMeasuredCpuCount;},updateBounds:function(){ProcessBase.prototype.updateBounds.call(this);for(var cpuNumber in this.cpus){var cpu=this.cpus[cpuNumber];cpu.updateBounds();this.bounds.addRange(cpu.bounds);}},createSubSlices:function(){ProcessBase.prototype.createSubSlices.call(this);for(var cpuNumber in this.cpus){var cpu=this.cpus[cpuNumber];cpu.createSubSlices();}},addCategoriesToDict:function(categoriesDict){ProcessBase.prototype.addCategoriesToDict.call(this,categoriesDict);for(var cpuNumber in this.cpus)this.cpus[cpuNumber].addCategoriesToDict(categoriesDict);},getSettingsKey:function(){return'kernel';},childEventContainers:function*(){yield*ProcessBase.prototype.childEventContainers.call(this);yield*tr.b.dictionaryValues(this.cpus);}};return{Kernel:Kernel};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/iteration_helpers.js":47,"./cpu.js":119,"./process_base.js":150}],139:[function(require,module,exports){(function(global){"use strict";require("../base/base.js");'use strict';global.tr.exportTo('tr.model',function(){function YComponent(stableId,yPercentOffset){this.stableId=stableId;this.yPercentOffset=yPercentOffset;}YComponent.prototype={toDict:function(){return{stableId:this.stableId,yPercentOffset:this.yPercentOffset};}};function Location(xWorld,yComponents){this.xWorld_=xWorld;this.yComponents_=yComponents;};Location.fromViewCoordinates=function(viewport,viewX,viewY){var dt=viewport.currentDisplayTransform;var xWorld=dt.xViewToWorld(viewX);var yComponents=[];var elem=document.elementFromPoint(viewX+viewport.modelTrackContainer.canvas.offsetLeft,viewY+viewport.modelTrackContainer.canvas.offsetTop);while(elem instanceof tr.ui.tracks.Track){if(elem.eventContainer){var boundRect=elem.getBoundingClientRect();var yPercentOffset=(viewY-boundRect.top)/boundRect.height;yComponents.push(new YComponent(elem.eventContainer.stableId,yPercentOffset));}elem=elem.parentElement;}if(yComponents.length==0)return;return new Location(xWorld,yComponents);};Location.fromStableIdAndTimestamp=function(viewport,stableId,ts){var xWorld=ts;var yComponents=[];var containerToTrack=viewport.containerToTrackMap;var elem=containerToTrack.getTrackByStableId(stableId);if(!elem)return;var firstY=elem.getBoundingClientRect().top;while(elem instanceof tr.ui.tracks.Track){if(elem.eventContainer){var boundRect=elem.getBoundingClientRect();var yPercentOffset=(firstY-boundRect.top)/boundRect.height;yComponents.push(new YComponent(elem.eventContainer.stableId,yPercentOffset));}elem=elem.parentElement;}if(yComponents.length==0)return;return new Location(xWorld,yComponents);};Location.prototype={get xWorld(){return this.xWorld_;},getContainingTrack:function(viewport){var containerToTrack=viewport.containerToTrackMap;for(var i in this.yComponents_){var yComponent=this.yComponents_[i];var track=containerToTrack.getTrackByStableId(yComponent.stableId);if(track!==undefined)return track;}},toViewCoordinates:function(viewport){var dt=viewport.currentDisplayTransform;var containerToTrack=viewport.containerToTrackMap;var viewX=dt.xWorldToView(this.xWorld_);var viewY=-1;for(var index in this.yComponents_){var yComponent=this.yComponents_[index];var track=containerToTrack.getTrackByStableId(yComponent.stableId);if(track!==undefined){var boundRect=track.getBoundingClientRect();viewY=yComponent.yPercentOffset*boundRect.height+boundRect.top;break;}}return{viewX:viewX,viewY:viewY};},toDict:function(){return{xWorld:this.xWorld_,yComponents:this.yComponents_};}};return{Location:Location};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/base.js":34}],140:[function(require,module,exports){(function(global){"use strict";require("../base/iteration_helpers.js");require("../base/unit.js");require("../value/numeric.js");'use strict';global.tr.exportTo('tr.model',function(){function MemoryAllocatorDump(containerMemoryDump,fullName,opt_guid){this.fullName=fullName;this.parent=undefined;this.children=[];this.numerics={};this.diagnostics={};this.containerMemoryDump=containerMemoryDump;this.owns=undefined;this.ownedBy=[];this.ownedBySiblingSizes=new Map();this.retains=[];this.retainedBy=[];this.weak=false;this.infos=[];this.guid=opt_guid;}MemoryAllocatorDump.SIZE_NUMERIC_NAME='size';MemoryAllocatorDump.EFFECTIVE_SIZE_NUMERIC_NAME='effective_size';MemoryAllocatorDump.RESIDENT_SIZE_NUMERIC_NAME='resident_size';MemoryAllocatorDump.DISPLAYED_SIZE_NUMERIC_NAME=MemoryAllocatorDump.EFFECTIVE_SIZE_NUMERIC_NAME;MemoryAllocatorDump.prototype={get name(){return this.fullName.substring(this.fullName.lastIndexOf('/')+1);},get quantifiedName(){return'\''+this.fullName+'\' in '+this.containerMemoryDump.containerName;},getDescendantDumpByFullName:function(fullName){return this.containerMemoryDump.getMemoryAllocatorDumpByFullName(this.fullName+'/'+fullName);},isDescendantOf:function(otherDump){var dump=this;while(dump!==undefined){if(dump===otherDump)return true;dump=dump.parent;}return false;},addNumeric:function(name,numeric){if(!(numeric instanceof tr.v.ScalarNumeric))throw new Error('Numeric value must be an instance of ScalarNumeric.');if(name in this.numerics)throw new Error('Duplicate numeric name: '+name+'.');this.numerics[name]=numeric;},addDiagnostic:function(name,text){if(typeof text!=='string')throw new Error('Diagnostic text must be a string.');if(name in this.diagnostics)throw new Error('Duplicate diagnostic name: '+name+'.');this.diagnostics[name]=text;},aggregateNumericsRecursively:function(opt_model){var numericNames=new Set();this.children.forEach(function(child){child.aggregateNumericsRecursively(opt_model);tr.b.iterItems(child.numerics,numericNames.add,numericNames);},this);numericNames.forEach(function(numericName){if(numericName===MemoryAllocatorDump.SIZE_NUMERIC_NAME||numericName===MemoryAllocatorDump.EFFECTIVE_SIZE_NUMERIC_NAME||this.numerics[numericName]!==undefined){return;}this.numerics[numericName]=MemoryAllocatorDump.aggregateNumerics(this.children.map(function(child){return child.numerics[numericName];}),opt_model);},this);}};MemoryAllocatorDump.aggregateNumerics=function(numerics,opt_model){var shouldLogWarning=!!opt_model;var aggregatedUnit=undefined;var aggregatedValue=0;numerics.forEach(function(numeric){if(numeric===undefined)return;var unit=numeric.unit;if(aggregatedUnit===undefined){aggregatedUnit=unit;}else if(aggregatedUnit!==unit){if(shouldLogWarning){opt_model.importWarning({type:'numeric_parse_error',message:'Multiple units provided for numeric: \''+aggregatedUnit.unitName+'\' and \''+unit.unitName+'\'.'});shouldLogWarning=false;}aggregatedUnit=tr.b.Unit.byName.unitlessNumber_smallerIsBetter;}aggregatedValue+=numeric.value;},this);if(aggregatedUnit===undefined)return undefined;return new tr.v.ScalarNumeric(aggregatedUnit,aggregatedValue);};function MemoryAllocatorDumpLink(source,target,opt_importance){this.source=source;this.target=target;this.importance=opt_importance;this.size=undefined;}var MemoryAllocatorDumpInfoType={PROVIDED_SIZE_LESS_THAN_AGGREGATED_CHILDREN:0,PROVIDED_SIZE_LESS_THAN_LARGEST_OWNER:1};return{MemoryAllocatorDump:MemoryAllocatorDump,MemoryAllocatorDumpLink:MemoryAllocatorDumpLink,MemoryAllocatorDumpInfoType:MemoryAllocatorDumpInfoType};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/iteration_helpers.js":47,"../base/unit.js":63,"../value/numeric.js":196}],141:[function(require,module,exports){(function(global){"use strict";require("../base/base.js");require("../base/event.js");require("../base/interval_tree.js");require("../base/quad.js");require("../base/range.js");require("../base/task.js");require("../base/time_display_modes.js");require("../base/unit.js");require("../core/auditor.js");require("../core/filter.js");require("./alert.js");require("./clock_sync_manager.js");require("./constants.js");require("./device.js");require("./flow_event.js");require("./frame.js");require("./global_memory_dump.js");require("./instant_event.js");require("./kernel.js");require("./model_indices.js");require("./model_stats.js");require("./object_snapshot.js");require("./process.js");require("./process_memory_dump.js");require("./sample.js");require("./stack_frame.js");require("./user_model/user_expectation.js");require("./user_model/user_model.js");'use strict';global.tr.exportTo('tr',function(){var Process=tr.model.Process;var Device=tr.model.Device;var Kernel=tr.model.Kernel;var GlobalMemoryDump=tr.model.GlobalMemoryDump;var GlobalInstantEvent=tr.model.GlobalInstantEvent;var FlowEvent=tr.model.FlowEvent;var Alert=tr.model.Alert;var Sample=tr.model.Sample;function Model(){tr.model.EventContainer.call(this);tr.b.EventTarget.decorate(this);this.timestampShiftToZeroAmount_=0;this.faviconHue='blue';this.device=new Device(this);this.kernel=new Kernel(this);this.processes={};this.metadata=[];this.categories=[];this.instantEvents=[];this.flowEvents=[];this.clockSyncManager=new tr.model.ClockSyncManager();this.intrinsicTimeUnit_=undefined;this.stackFrames={};this.samples=[];this.alerts=[];this.userModel=new tr.model.um.UserModel(this);this.flowIntervalTree=new tr.b.IntervalTree(f=>f.start,f=>f.end);this.globalMemoryDumps=[];this.userFriendlyCategoryDrivers_=[];this.annotationsByGuid_={};this.modelIndices=undefined;this.stats=new tr.model.ModelStats();this.importWarnings_=[];this.reportedImportWarnings_={};this.isTimeHighResolution_=true;this.patchupsToApply_=[];this.doesHelperGUIDSupportThisModel_={};this.helpersByConstructorGUID_={};this.eventsByStableId_=undefined;}Model.prototype={__proto__:tr.model.EventContainer.prototype,getEventByStableId:function(stableId){if(this.eventsByStableId_===undefined){this.eventsByStableId_={};for(var event of this.getDescendantEvents()){this.eventsByStableId_[event.stableId]=event;}}return this.eventsByStableId_[stableId];},getOrCreateHelper:function(constructor){if(!constructor.guid)throw new Error('Helper constructors must have GUIDs');if(this.helpersByConstructorGUID_[constructor.guid]===undefined){if(this.doesHelperGUIDSupportThisModel_[constructor.guid]===undefined){this.doesHelperGUIDSupportThisModel_[constructor.guid]=constructor.supportsModel(this);}if(!this.doesHelperGUIDSupportThisModel_[constructor.guid])return undefined;this.helpersByConstructorGUID_[constructor.guid]=new constructor(this);}return this.helpersByConstructorGUID_[constructor.guid];},childEvents:function*(){yield*this.globalMemoryDumps;yield*this.instantEvents;yield*this.flowEvents;yield*this.alerts;yield*this.samples;},childEventContainers:function*(){yield this.userModel;yield this.device;yield this.kernel;yield*tr.b.dictionaryValues(this.processes);},iterateAllPersistableObjects:function(callback){this.kernel.iterateAllPersistableObjects(callback);for(var pid in this.processes)this.processes[pid].iterateAllPersistableObjects(callback);},updateBounds:function(){this.bounds.reset();var bounds=this.bounds;for(var ec of this.childEventContainers()){ec.updateBounds();bounds.addRange(ec.bounds);}for(var event of this.childEvents())event.addBoundsToRange(bounds);},shiftWorldToZero:function(){var shiftAmount=-this.bounds.min;this.timestampShiftToZeroAmount_=shiftAmount;for(var ec of this.childEventContainers())ec.shiftTimestampsForward(shiftAmount);for(var event of this.childEvents())event.start+=shiftAmount;this.updateBounds();},convertTimestampToModelTime:function(sourceClockDomainName,ts){if(sourceClockDomainName!=='traceEventClock')throw new Error('Only traceEventClock is supported.');return tr.b.Unit.timestampFromUs(ts)+this.timestampShiftToZeroAmount_;},get numProcesses(){var n=0;for(var p in this.processes)n++;return n;},getProcess:function(pid){return this.processes[pid];},getOrCreateProcess:function(pid){if(!this.processes[pid])this.processes[pid]=new Process(this,pid);return this.processes[pid];},addStackFrame:function(stackFrame){if(this.stackFrames[stackFrame.id])throw new Error('Stack frame already exists');this.stackFrames[stackFrame.id]=stackFrame;return stackFrame;},updateCategories_:function(){var categoriesDict={};this.userModel.addCategoriesToDict(categoriesDict);this.device.addCategoriesToDict(categoriesDict);this.kernel.addCategoriesToDict(categoriesDict);for(var pid in this.processes)this.processes[pid].addCategoriesToDict(categoriesDict);this.categories=[];for(var category in categoriesDict)if(category!='')this.categories.push(category);},getAllThreads:function(){var threads=[];for(var tid in this.kernel.threads){threads.push(process.threads[tid]);}for(var pid in this.processes){var process=this.processes[pid];for(var tid in process.threads){threads.push(process.threads[tid]);}}return threads;},getAllProcesses:function(opt_predicate){var processes=[];for(var pid in this.processes){var process=this.processes[pid];if(opt_predicate===undefined||opt_predicate(process))processes.push(process);}return processes;},getAllCounters:function(){var counters=[];counters.push.apply(counters,tr.b.dictionaryValues(this.device.counters));counters.push.apply(counters,tr.b.dictionaryValues(this.kernel.counters));for(var pid in this.processes){var process=this.processes[pid];for(var tid in process.counters){counters.push(process.counters[tid]);}}return counters;},getAnnotationByGUID:function(guid){return this.annotationsByGuid_[guid];},addAnnotation:function(annotation){if(!annotation.guid)throw new Error('Annotation with undefined guid given');this.annotationsByGuid_[annotation.guid]=annotation;tr.b.dispatchSimpleEvent(this,'annotationChange');},removeAnnotation:function(annotation){this.annotationsByGuid_[annotation.guid].onRemove();delete this.annotationsByGuid_[annotation.guid];tr.b.dispatchSimpleEvent(this,'annotationChange');},getAllAnnotations:function(){return tr.b.dictionaryValues(this.annotationsByGuid_);},addUserFriendlyCategoryDriver:function(ufcd){this.userFriendlyCategoryDrivers_.push(ufcd);},getUserFriendlyCategoryFromEvent:function(event){for(var i=0;i<this.userFriendlyCategoryDrivers_.length;i++){var ufc=this.userFriendlyCategoryDrivers_[i].fromEvent(event);if(ufc!==undefined)return ufc;}return undefined;},findAllThreadsNamed:function(name){var namedThreads=[];namedThreads.push.apply(namedThreads,this.kernel.findAllThreadsNamed(name));for(var pid in this.processes){namedThreads.push.apply(namedThreads,this.processes[pid].findAllThreadsNamed(name));}return namedThreads;},get importOptions(){return this.importOptions_;},set importOptions(options){this.importOptions_=options;},get intrinsicTimeUnit(){if(this.intrinsicTimeUnit_===undefined)return tr.b.TimeDisplayModes.ms;return this.intrinsicTimeUnit_;},set intrinsicTimeUnit(value){if(this.intrinsicTimeUnit_===value)return;if(this.intrinsicTimeUnit_!==undefined)throw new Error('Intrinsic time unit already set');this.intrinsicTimeUnit_=value;},get isTimeHighResolution(){return this.isTimeHighResolution_;},set isTimeHighResolution(value){this.isTimeHighResolution_=value;},get canonicalUrl(){return this.canonicalUrl_;},set canonicalUrl(value){if(this.canonicalUrl_===value)return;if(this.canonicalUrl_!==undefined)throw new Error('canonicalUrl already set');this.canonicalUrl_=value;},importWarning:function(data){data.showToUser=!!data.showToUser;this.importWarnings_.push(data);if(this.reportedImportWarnings_[data.type]===true)return;if(this.importOptions_.showImportWarnings)console.warn(data.message);this.reportedImportWarnings_[data.type]=true;},get hasImportWarnings(){return this.importWarnings_.length>0;},get importWarnings(){return this.importWarnings_;},get importWarningsThatShouldBeShownToUser(){return this.importWarnings_.filter(function(warning){return warning.showToUser;});},autoCloseOpenSlices:function(){this.samples.sort(function(x,y){return x.start-y.start;});this.updateBounds();this.kernel.autoCloseOpenSlices();for(var pid in this.processes)this.processes[pid].autoCloseOpenSlices();},createSubSlices:function(){this.kernel.createSubSlices();for(var pid in this.processes)this.processes[pid].createSubSlices();},preInitializeObjects:function(){for(var pid in this.processes)this.processes[pid].preInitializeObjects();},initializeObjects:function(){for(var pid in this.processes)this.processes[pid].initializeObjects();},pruneEmptyContainers:function(){this.kernel.pruneEmptyContainers();for(var pid in this.processes)this.processes[pid].pruneEmptyContainers();},mergeKernelWithUserland:function(){for(var pid in this.processes)this.processes[pid].mergeKernelWithUserland();},computeWorldBounds:function(shiftWorldToZero){this.updateBounds();this.updateCategories_();if(shiftWorldToZero)this.shiftWorldToZero();},buildFlowEventIntervalTree:function(){for(var i=0;i<this.flowEvents.length;++i){var flowEvent=this.flowEvents[i];this.flowIntervalTree.insert(flowEvent);}this.flowIntervalTree.updateHighValues();},cleanupUndeletedObjects:function(){for(var pid in this.processes)this.processes[pid].autoDeleteObjects(this.bounds.max);},sortMemoryDumps:function(){this.globalMemoryDumps.sort(function(x,y){return x.start-y.start;});for(var pid in this.processes)this.processes[pid].sortMemoryDumps();},finalizeMemoryGraphs:function(){this.globalMemoryDumps.forEach(function(dump){dump.finalizeGraph();});},buildEventIndices:function(){this.modelIndices=new tr.model.ModelIndices(this);},sortAlerts:function(){this.alerts.sort(function(x,y){return x.start-y.start;});},applyObjectRefPatchups:function(){var unresolved=[];this.patchupsToApply_.forEach(function(patchup){if(patchup.pidRef in this.processes){var snapshot=this.processes[patchup.pidRef].objects.getSnapshotAt(patchup.scopedId,patchup.ts);if(snapshot){patchup.object[patchup.field]=snapshot;snapshot.referencedAt(patchup.item,patchup.object,patchup.field);return;}}unresolved.push(patchup);},this);this.patchupsToApply_=unresolved;},replacePIDRefsInPatchups:function(oldPidRef,newPidRef){this.patchupsToApply_.forEach(function(patchup){if(patchup.pidRef===oldPidRef){patchup.pidRef=newPidRef;}});},joinRefs:function(){this.joinObjectRefs_();this.applyObjectRefPatchups();},joinObjectRefs_:function(){tr.b.iterItems(this.processes,function(pid,process){this.joinObjectRefsForProcess_(pid,process);},this);},joinObjectRefsForProcess_:function(pid,process){tr.b.iterItems(process.threads,function(tid,thread){thread.asyncSliceGroup.slices.forEach(function(item){this.searchItemForIDRefs_(pid,'start',item);},this);thread.sliceGroup.slices.forEach(function(item){this.searchItemForIDRefs_(pid,'start',item);},this);},this);process.objects.iterObjectInstances(function(instance){instance.snapshots.forEach(function(item){this.searchItemForIDRefs_(pid,'ts',item);},this);},this);},searchItemForIDRefs_:function(pid,itemTimestampField,item){if(!item.args&&!item.contexts)return;var patchupsToApply=this.patchupsToApply_;function handleField(object,fieldName,fieldValue){if(!fieldValue||!fieldValue.id_ref&&!fieldValue.idRef)return;var scope=fieldValue.scope||tr.model.OBJECT_DEFAULT_SCOPE;var idRef=fieldValue.id_ref||fieldValue.idRef;var scopedId=new tr.model.ScopedId(scope,idRef);var pidRef=fieldValue.pid_ref||fieldValue.pidRef||pid;var ts=item[itemTimestampField];patchupsToApply.push({item:item,object:object,field:fieldName,pidRef:pidRef,scopedId:scopedId,ts:ts});}function iterObjectFieldsRecursively(object){if(!(object instanceof Object))return;if(object instanceof tr.model.ObjectSnapshot||object instanceof Float32Array||object instanceof tr.b.Quad)return;if(object instanceof Array){for(var i=0;i<object.length;i++){handleField(object,i,object[i]);iterObjectFieldsRecursively(object[i]);}return;}for(var key in object){var value=object[key];handleField(object,key,value);iterObjectFieldsRecursively(value);}}iterObjectFieldsRecursively(item.args);iterObjectFieldsRecursively(item.contexts);}};return{Model:Model};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/base.js":34,"../base/event.js":39,"../base/interval_tree.js":46,"../base/quad.js":51,"../base/range.js":53,"../base/task.js":60,"../base/time_display_modes.js":61,"../base/unit.js":63,"../core/auditor.js":66,"../core/filter.js":67,"./alert.js":107,"./clock_sync_manager.js":111,"./constants.js":114,"./device.js":121,"./flow_event.js":127,"./frame.js":128,"./global_memory_dump.js":129,"./instant_event.js":136,"./kernel.js":138,"./model_indices.js":142,"./model_stats.js":143,"./object_snapshot.js":146,"./process.js":149,"./process_memory_dump.js":151,"./sample.js":153,"./stack_frame.js":161,"./user_model/user_expectation.js":172,"./user_model/user_model.js":173}],142:[function(require,module,exports){(function(global){"use strict";require("../base/base.js");'use strict';global.tr.exportTo('tr.model',function(){function ModelIndices(model){this.flowEventsById_={};model.flowEvents.forEach(function(fe){if(fe.id!==undefined){if(!this.flowEventsById_.hasOwnProperty(fe.id)){this.flowEventsById_[fe.id]=new Array();}this.flowEventsById_[fe.id].push(fe);}},this);}ModelIndices.prototype={addEventWithId:function(id,event){if(!this.flowEventsById_.hasOwnProperty(id)){this.flowEventsById_[id]=new Array();}this.flowEventsById_[id].push(event);},getFlowEventsWithId:function(id){if(!this.flowEventsById_.hasOwnProperty(id))return[];return this.flowEventsById_[id];}};return{ModelIndices:ModelIndices};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/base.js":34}],143:[function(require,module,exports){(function(global){"use strict";require("../base/unit.js");'use strict';global.tr.exportTo('tr.model',function(){function ModelStats(){this.traceEventCountsByKey_=new Map();this.allTraceEventStats_=[];this.traceEventStatsInTimeIntervals_=new Map();this.allTraceEventStatsInTimeIntervals_=[];this.hasEventSizesinBytes_=false;}ModelStats.prototype={TIME_INTERVAL_SIZE_IN_MS:100,willProcessBasicTraceEvent:function(phase,category,title,ts,opt_eventSizeinBytes){var key=phase+'/'+category+'/'+title;var eventStats=this.traceEventCountsByKey_.get(key);if(eventStats===undefined){eventStats={phase:phase,category:category,title:title,numEvents:0,totalEventSizeinBytes:0};this.traceEventCountsByKey_.set(key,eventStats);this.allTraceEventStats_.push(eventStats);}eventStats.numEvents++;var timeIntervalKey=Math.floor(tr.b.Unit.timestampFromUs(ts)/this.TIME_INTERVAL_SIZE_IN_MS);var eventStatsByTimeInverval=this.traceEventStatsInTimeIntervals_.get(timeIntervalKey);if(eventStatsByTimeInverval===undefined){eventStatsByTimeInverval={timeInterval:timeIntervalKey,numEvents:0,totalEventSizeinBytes:0};this.traceEventStatsInTimeIntervals_.set(timeIntervalKey,eventStatsByTimeInverval);this.allTraceEventStatsInTimeIntervals_.push(eventStatsByTimeInverval);}eventStatsByTimeInverval.numEvents++;if(opt_eventSizeinBytes!==undefined){this.hasEventSizesinBytes_=true;eventStats.totalEventSizeinBytes+=opt_eventSizeinBytes;eventStatsByTimeInverval.totalEventSizeinBytes+=opt_eventSizeinBytes;}},get allTraceEventStats(){return this.allTraceEventStats_;},get allTraceEventStatsInTimeIntervals(){return this.allTraceEventStatsInTimeIntervals_;},get hasEventSizesinBytes(){return this.hasEventSizesinBytes_;}};return{ModelStats:ModelStats};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/unit.js":63}],144:[function(require,module,exports){(function(global){"use strict";require("../base/range.js");require("../base/sorted_array_utils.js");require("../base/utils.js");require("./event_container.js");require("./object_instance.js");require("./time_to_object_instance_map.js");'use strict';global.tr.exportTo('tr.model',function(){var ObjectInstance=tr.model.ObjectInstance;var ObjectSnapshot=tr.model.ObjectSnapshot;function ObjectCollection(parent){tr.model.EventContainer.call(this);this.parent=parent;this.instanceMapsByScopedId_={};this.instancesByTypeName_={};this.createObjectInstance_=this.createObjectInstance_.bind(this);}ObjectCollection.prototype={__proto__:tr.model.EventContainer.prototype,childEvents:function*(){for(var instance of this.getAllObjectInstances()){yield instance;yield*instance.snapshots;}},createObjectInstance_:function(parent,scopedId,category,name,creationTs,opt_baseTypeName){var constructor=tr.model.ObjectInstance.subTypes.getConstructor(category,name);var instance=new constructor(parent,scopedId,category,name,creationTs,opt_baseTypeName);var typeName=instance.typeName;var instancesOfTypeName=this.instancesByTypeName_[typeName];if(!instancesOfTypeName){instancesOfTypeName=[];this.instancesByTypeName_[typeName]=instancesOfTypeName;}instancesOfTypeName.push(instance);return instance;},getOrCreateInstanceMap_:function(scopedId){var dict;if(scopedId.scope in this.instanceMapsByScopedId_){dict=this.instanceMapsByScopedId_[scopedId.scope];}else{dict={};this.instanceMapsByScopedId_[scopedId.scope]=dict;}var instanceMap=dict[scopedId.id];if(instanceMap)return instanceMap;instanceMap=new tr.model.TimeToObjectInstanceMap(this.createObjectInstance_,this.parent,scopedId);dict[scopedId.id]=instanceMap;return instanceMap;},idWasCreated:function(scopedId,category,name,ts){var instanceMap=this.getOrCreateInstanceMap_(scopedId);return instanceMap.idWasCreated(category,name,ts);},addSnapshot:function(scopedId,category,name,ts,args,opt_baseTypeName){var instanceMap=this.getOrCreateInstanceMap_(scopedId);var snapshot=instanceMap.addSnapshot(category,name,ts,args,opt_baseTypeName);if(snapshot.objectInstance.category!=category){var msg='Added snapshot name='+name+' with cat='+category+' impossible. It instance was created/snapshotted with cat='+snapshot.objectInstance.category+' name='+snapshot.objectInstance.name;throw new Error(msg);}if(opt_baseTypeName&&snapshot.objectInstance.baseTypeName!=opt_baseTypeName){throw new Error('Could not add snapshot with baseTypeName='+opt_baseTypeName+'. It '+'was previously created with name='+snapshot.objectInstance.baseTypeName);}if(snapshot.objectInstance.name!=name){throw new Error('Could not add snapshot with name='+name+'. It '+'was previously created with name='+snapshot.objectInstance.name);}return snapshot;},idWasDeleted:function(scopedId,category,name,ts){var instanceMap=this.getOrCreateInstanceMap_(scopedId);var deletedInstance=instanceMap.idWasDeleted(category,name,ts);if(!deletedInstance)return;if(deletedInstance.category!=category){var msg='Deleting object '+deletedInstance.name+' with a different category '+'than when it was created. It previous had cat='+deletedInstance.category+' but the delete command '+'had cat='+category;throw new Error(msg);}if(deletedInstance.baseTypeName!=name){throw new Error('Deletion requested for name='+name+' could not proceed: '+'An existing object with baseTypeName='+deletedInstance.baseTypeName+' existed.');}},autoDeleteObjects:function(maxTimestamp){tr.b.iterItems(this.instanceMapsByScopedId_,function(scope,imapById){tr.b.iterItems(imapById,function(id,i2imap){var lastInstance=i2imap.lastInstance;if(lastInstance.deletionTs!=Number.MAX_VALUE)return;i2imap.idWasDeleted(lastInstance.category,lastInstance.name,maxTimestamp);lastInstance.deletionTsWasExplicit=false;});});},getObjectInstanceAt:function(scopedId,ts){var instanceMap;if(scopedId.scope in this.instanceMapsByScopedId_)instanceMap=this.instanceMapsByScopedId_[scopedId.scope][scopedId.id];if(!instanceMap)return undefined;return instanceMap.getInstanceAt(ts);},getSnapshotAt:function(scopedId,ts){var instance=this.getObjectInstanceAt(scopedId,ts);if(!instance)return undefined;return instance.getSnapshotAt(ts);},iterObjectInstances:function(iter,opt_this){opt_this=opt_this||this;tr.b.iterItems(this.instanceMapsByScopedId_,function(scope,imapById){tr.b.iterItems(imapById,function(id,i2imap){i2imap.instances.forEach(iter,opt_this);});});},getAllObjectInstances:function(){var instances=[];this.iterObjectInstances(function(i){instances.push(i);});return instances;},getAllInstancesNamed:function(name){return this.instancesByTypeName_[name];},getAllInstancesByTypeName:function(){return this.instancesByTypeName_;},preInitializeAllObjects:function(){this.iterObjectInstances(function(instance){instance.preInitialize();});},initializeAllObjects:function(){this.iterObjectInstances(function(instance){instance.initialize();});},initializeInstances:function(){this.iterObjectInstances(function(instance){instance.initialize();});},updateBounds:function(){this.bounds.reset();this.iterObjectInstances(function(instance){instance.updateBounds();this.bounds.addRange(instance.bounds);},this);},shiftTimestampsForward:function(amount){this.iterObjectInstances(function(instance){instance.shiftTimestampsForward(amount);});},addCategoriesToDict:function(categoriesDict){this.iterObjectInstances(function(instance){categoriesDict[instance.category]=true;});}};return{ObjectCollection:ObjectCollection};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/range.js":53,"../base/sorted_array_utils.js":58,"../base/utils.js":65,"./event_container.js":123,"./object_instance.js":145,"./time_to_object_instance_map.js":165}],145:[function(require,module,exports){(function(global){"use strict";require("../base/range.js");require("../base/sorted_array_utils.js");require("./event.js");require("./object_snapshot.js");'use strict';global.tr.exportTo('tr.model',function(){var ObjectSnapshot=tr.model.ObjectSnapshot;function ObjectInstance(parent,scopedId,category,name,creationTs,opt_baseTypeName){tr.model.Event.call(this);this.parent=parent;this.scopedId=scopedId;this.category=category;this.baseTypeName=opt_baseTypeName?opt_baseTypeName:name;this.name=name;this.creationTs=creationTs;this.creationTsWasExplicit=false;this.deletionTs=Number.MAX_VALUE;this.deletionTsWasExplicit=false;this.colorId=0;this.bounds=new tr.b.Range();this.snapshots=[];this.hasImplicitSnapshots=false;}ObjectInstance.prototype={__proto__:tr.model.Event.prototype,get typeName(){return this.name;},addBoundsToRange:function(range){range.addRange(this.bounds);},addSnapshot:function(ts,args,opt_name,opt_baseTypeName){if(ts<this.creationTs)throw new Error('Snapshots must be >= instance.creationTs');if(ts>=this.deletionTs)throw new Error('Snapshots cannot be added after '+'an objects deletion timestamp.');var lastSnapshot;if(this.snapshots.length>0){lastSnapshot=this.snapshots[this.snapshots.length-1];if(lastSnapshot.ts==ts)throw new Error('Snapshots already exists at this time!');if(ts<lastSnapshot.ts){throw new Error('Snapshots must be added in increasing timestamp order');}}if(opt_name&&this.name!=opt_name){if(!opt_baseTypeName)throw new Error('Must provide base type name for name update');if(this.baseTypeName!=opt_baseTypeName)throw new Error('Cannot update type name: base types dont match');this.name=opt_name;}var snapshotConstructor=tr.model.ObjectSnapshot.subTypes.getConstructor(this.category,this.name);var snapshot=new snapshotConstructor(this,ts,args);this.snapshots.push(snapshot);return snapshot;},wasDeleted:function(ts){var lastSnapshot;if(this.snapshots.length>0){lastSnapshot=this.snapshots[this.snapshots.length-1];if(lastSnapshot.ts>ts)throw new Error('Instance cannot be deleted at ts='+ts+'. A snapshot exists that is older.');}this.deletionTs=ts;this.deletionTsWasExplicit=true;},preInitialize:function(){for(var i=0;i<this.snapshots.length;i++)this.snapshots[i].preInitialize();},initialize:function(){for(var i=0;i<this.snapshots.length;i++)this.snapshots[i].initialize();},isAliveAt:function(ts){if(ts<this.creationTs&&this.creationTsWasExplicit)return false;if(ts>this.deletionTs)return false;return true;},getSnapshotAt:function(ts){if(ts<this.creationTs){if(this.creationTsWasExplicit)throw new Error('ts must be within lifetime of this instance');return this.snapshots[0];}if(ts>this.deletionTs)throw new Error('ts must be within lifetime of this instance');var snapshots=this.snapshots;var i=tr.b.findIndexInSortedIntervals(snapshots,function(snapshot){return snapshot.ts;},function(snapshot,i){if(i==snapshots.length-1)return snapshots[i].objectInstance.deletionTs;return snapshots[i+1].ts-snapshots[i].ts;},ts);if(i<0){return this.snapshots[0];}if(i>=this.snapshots.length)return this.snapshots[this.snapshots.length-1];return this.snapshots[i];},updateBounds:function(){this.bounds.reset();this.bounds.addValue(this.creationTs);if(this.deletionTs!=Number.MAX_VALUE)this.bounds.addValue(this.deletionTs);else if(this.snapshots.length>0)this.bounds.addValue(this.snapshots[this.snapshots.length-1].ts);},shiftTimestampsForward:function(amount){this.creationTs+=amount;if(this.deletionTs!=Number.MAX_VALUE)this.deletionTs+=amount;this.snapshots.forEach(function(snapshot){snapshot.ts+=amount;});},get userFriendlyName(){return this.typeName+' object '+this.scopedId;}};tr.model.EventRegistry.register(ObjectInstance,{name:'objectInstance',pluralName:'objectInstances'});return{ObjectInstance:ObjectInstance};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/range.js":53,"../base/sorted_array_utils.js":58,"./event.js":122,"./object_snapshot.js":146}],146:[function(require,module,exports){(function(global){"use strict";require("../base/unit.js");require("./event.js");'use strict';global.tr.exportTo('tr.model',function(){function ObjectSnapshot(objectInstance,ts,args){tr.model.Event.call(this);this.objectInstance=objectInstance;this.ts=ts;this.args=args;}ObjectSnapshot.prototype={__proto__:tr.model.Event.prototype,preInitialize:function(){},initialize:function(){},referencedAt:function(item,object,field){},addBoundsToRange:function(range){range.addValue(this.ts);},get userFriendlyName(){return'Snapshot of '+this.objectInstance.typeName+' '+this.objectInstance.id+' @ '+tr.b.Unit.byName.timeStampInMs.format(this.ts);}};tr.model.EventRegistry.register(ObjectSnapshot,{name:'objectSnapshot',pluralName:'objectSnapshots'});return{ObjectSnapshot:ObjectSnapshot};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/unit.js":63,"./event.js":122}],147:[function(require,module,exports){(function(global){"use strict";require("./event.js");require("./event_registry.js");'use strict';global.tr.exportTo('tr.model',function(){var Event=tr.model.Event;var EventRegistry=tr.model.EventRegistry;function PowerSample(series,start,powerInW){Event.call(this);this.series_=series;this.start_=start;this.powerInW_=powerInW;}PowerSample.prototype={__proto__:Event.prototype,get series(){return this.series_;},get start(){return this.start_;},set start(value){this.start_=value;},get powerInW(){return this.powerInW_;},set powerInW(value){this.powerInW_=value;},addBoundsToRange:function(range){range.addValue(this.start);}};EventRegistry.register(PowerSample,{name:'powerSample',pluralName:'powerSamples'});return{PowerSample:PowerSample};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./event.js":122,"./event_registry.js":125}],148:[function(require,module,exports){(function(global){"use strict";require("../base/range.js");require("../base/sorted_array_utils.js");require("../base/unit_scale.js");require("./event_container.js");require("./power_sample.js");'use strict';global.tr.exportTo('tr.model',function(){var PowerSample=tr.model.PowerSample;function PowerSeries(device){tr.model.EventContainer.call(this);this.device_=device;this.samples_=[];}PowerSeries.prototype={__proto__:tr.model.EventContainer.prototype,get device(){return this.device_;},get samples(){return this.samples_;},get stableId(){return this.device_.stableId+'.PowerSeries';},addPowerSample:function(ts,val){var sample=new PowerSample(this,ts,val);this.samples_.push(sample);return sample;},getEnergyConsumedInJ:function(start,end){var measurementRange=tr.b.Range.fromExplicitRange(start,end);var energyConsumedInJ=0;var startIndex=tr.b.findLowIndexInSortedArray(this.samples,x=>x.start,start)-1;var endIndex=tr.b.findLowIndexInSortedArray(this.samples,x=>x.start,end);if(startIndex<0)startIndex=0;for(var i=startIndex;i<endIndex;i++){var sample=this.samples[i];var nextSample=this.samples[i+1];var sampleRange=new tr.b.Range();sampleRange.addValue(sample.start);sampleRange.addValue(nextSample?nextSample.start:sample.start);var intersectionRangeInMs=measurementRange.findIntersection(sampleRange);var durationInS=tr.b.convertUnit(intersectionRangeInMs.duration,tr.b.UnitScale.Metric.MILLI,tr.b.UnitScale.Metric.NONE);energyConsumedInJ+=durationInS*sample.powerInW;}return energyConsumedInJ;},getSamplesWithinRange:function(start,end){var startIndex=tr.b.findLowIndexInSortedArray(this.samples,x=>x.start,start);var endIndex=tr.b.findLowIndexInSortedArray(this.samples,x=>x.start,end);return this.samples.slice(startIndex,endIndex);},shiftTimestampsForward:function(amount){for(var i=0;i<this.samples_.length;++i)this.samples_[i].start+=amount;},updateBounds:function(){this.bounds.reset();if(this.samples_.length===0)return;this.bounds.addValue(this.samples_[0].start);this.bounds.addValue(this.samples_[this.samples_.length-1].start);},childEvents:function*(){yield*this.samples_;}};return{PowerSeries:PowerSeries};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/range.js":53,"../base/sorted_array_utils.js":58,"../base/unit_scale.js":64,"./event_container.js":123,"./power_sample.js":147}],149:[function(require,module,exports){(function(global){"use strict";require("./process_base.js");require("./process_memory_dump.js");'use strict';global.tr.exportTo('tr.model',function(){var ProcessBase=tr.model.ProcessBase;var ProcessInstantEvent=tr.model.ProcessInstantEvent;var Frame=tr.model.Frame;var ProcessMemoryDump=tr.model.ProcessMemoryDump;function Process(model,pid){if(model===undefined)throw new Error('model must be provided');if(pid===undefined)throw new Error('pid must be provided');tr.model.ProcessBase.call(this,model);this.pid=pid;this.name=undefined;this.labels=[];this.instantEvents=[];this.memoryDumps=[];this.frames=[];this.activities=[];};Process.compare=function(x,y){var tmp=tr.model.ProcessBase.compare(x,y);if(tmp)return tmp;tmp=tr.b.comparePossiblyUndefinedValues(x.name,y.name,function(x,y){return x.localeCompare(y);});if(tmp)return tmp;tmp=tr.b.compareArrays(x.labels,y.labels,function(x,y){return x.localeCompare(y);});if(tmp)return tmp;return x.pid-y.pid;};Process.prototype={__proto__:tr.model.ProcessBase.prototype,get stableId(){return this.pid;},compareTo:function(that){return Process.compare(this,that);},childEvents:function*(){yield*ProcessBase.prototype.childEvents.call(this);yield*this.instantEvents;yield*this.frames;yield*this.memoryDumps;},addLabelIfNeeded:function(labelName){for(var i=0;i<this.labels.length;i++){if(this.labels[i]===labelName)return;}this.labels.push(labelName);},get userFriendlyName(){var res;if(this.name)res=this.name+' (pid '+this.pid+')';else res='Process '+this.pid;if(this.labels.length)res+=': '+this.labels.join(', ');return res;},get userFriendlyDetails(){if(this.name)return this.name+' (pid '+this.pid+')';return'pid: '+this.pid;},getSettingsKey:function(){if(!this.name)return undefined;if(!this.labels.length)return'processes.'+this.name;return'processes.'+this.name+'.'+this.labels.join('.');},shiftTimestampsForward:function(amount){for(var i=0;i<this.instantEvents.length;i++)this.instantEvents[i].start+=amount;for(var i=0;i<this.frames.length;i++)this.frames[i].shiftTimestampsForward(amount);for(var i=0;i<this.memoryDumps.length;i++)this.memoryDumps[i].shiftTimestampsForward(amount);for(var i=0;i<this.activities.length;i++)this.activities[i].shiftTimestampsForward(amount);tr.model.ProcessBase.prototype.shiftTimestampsForward.apply(this,arguments);},updateBounds:function(){tr.model.ProcessBase.prototype.updateBounds.apply(this);for(var i=0;i<this.frames.length;i++)this.frames[i].addBoundsToRange(this.bounds);for(var i=0;i<this.memoryDumps.length;i++)this.memoryDumps[i].addBoundsToRange(this.bounds);for(var i=0;i<this.activities.length;i++)this.activities[i].addBoundsToRange(this.bounds);},sortMemoryDumps:function(){this.memoryDumps.sort(function(x,y){return x.start-y.start;});tr.model.ProcessMemoryDump.hookUpMostRecentVmRegionsLinks(this.memoryDumps);}};return{Process:Process};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./process_base.js":150,"./process_memory_dump.js":151}],150:[function(require,module,exports){(function(global){"use strict";require("../base/guid.js");require("../base/range.js");require("./counter.js");require("./event_container.js");require("./object_collection.js");require("./thread.js");'use strict';global.tr.exportTo('tr.model',function(){var Thread=tr.model.Thread;var Counter=tr.model.Counter;function ProcessBase(model){if(!model)throw new Error('Must provide a model');tr.model.EventContainer.call(this);this.model=model;this.threads={};this.counters={};this.objects=new tr.model.ObjectCollection(this);this.sortIndex=0;};ProcessBase.compare=function(x,y){return x.sortIndex-y.sortIndex;};ProcessBase.prototype={__proto__:tr.model.EventContainer.prototype,get stableId(){throw new Error('Not implemented');},childEventContainers:function*(){yield*tr.b.dictionaryValues(this.threads);yield*tr.b.dictionaryValues(this.counters);yield this.objects;},iterateAllPersistableObjects:function(cb){cb(this);for(var tid in this.threads)this.threads[tid].iterateAllPersistableObjects(cb);},get numThreads(){var n=0;for(var p in this.threads){n++;}return n;},shiftTimestampsForward:function(amount){for(var child of this.childEventContainers())child.shiftTimestampsForward(amount);},autoCloseOpenSlices:function(){for(var tid in this.threads){var thread=this.threads[tid];thread.autoCloseOpenSlices();}},autoDeleteObjects:function(maxTimestamp){this.objects.autoDeleteObjects(maxTimestamp);},preInitializeObjects:function(){this.objects.preInitializeAllObjects();},initializeObjects:function(){this.objects.initializeAllObjects();},mergeKernelWithUserland:function(){for(var tid in this.threads){var thread=this.threads[tid];thread.mergeKernelWithUserland();}},updateBounds:function(){this.bounds.reset();for(var tid in this.threads){this.threads[tid].updateBounds();this.bounds.addRange(this.threads[tid].bounds);}for(var id in this.counters){this.counters[id].updateBounds();this.bounds.addRange(this.counters[id].bounds);}this.objects.updateBounds();this.bounds.addRange(this.objects.bounds);},addCategoriesToDict:function(categoriesDict){for(var tid in this.threads)this.threads[tid].addCategoriesToDict(categoriesDict);for(var id in this.counters)categoriesDict[this.counters[id].category]=true;this.objects.addCategoriesToDict(categoriesDict);},findAllThreadsMatching:function(predicate,opt_this){var threads=[];for(var tid in this.threads){var thread=this.threads[tid];if(predicate.call(opt_this,thread))threads.push(thread);}return threads;},findAllThreadsNamed:function(name){var threads=this.findAllThreadsMatching(function(thread){if(!thread.name)return false;return thread.name===name;});return threads;},findAtMostOneThreadNamed:function(name){var threads=this.findAllThreadsNamed(name);if(threads.length===0)return undefined;if(threads.length>1)throw new Error('Expected no more than one '+name);return threads[0];},pruneEmptyContainers:function(){var threadsToKeep={};for(var tid in this.threads){var thread=this.threads[tid];if(!thread.isEmpty)threadsToKeep[tid]=thread;}this.threads=threadsToKeep;},getThread:function(tid){return this.threads[tid];},getOrCreateThread:function(tid){if(!this.threads[tid])this.threads[tid]=new Thread(this,tid);return this.threads[tid];},getOrCreateCounter:function(cat,name){var id=cat+'.'+name;if(!this.counters[id])this.counters[id]=new Counter(this,id,cat,name);return this.counters[id];},getSettingsKey:function(){throw new Error('Not implemented');},createSubSlices:function(){for(var tid in this.threads)this.threads[tid].createSubSlices();}};return{ProcessBase:ProcessBase};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/guid.js":45,"../base/range.js":53,"./counter.js":116,"./event_container.js":123,"./object_collection.js":144,"./thread.js":162}],151:[function(require,module,exports){(function(global){"use strict";require("../base/unit.js");require("./container_memory_dump.js");require("./memory_allocator_dump.js");require("./vm_region.js");'use strict';global.tr.exportTo('tr.model',function(){var DISCOUNTED_ALLOCATOR_NAMES=['winheap','malloc'];var TRACING_OVERHEAD_PATH=['allocated_objects','tracing_overhead'];var SIZE_NUMERIC_NAME=tr.model.MemoryAllocatorDump.SIZE_NUMERIC_NAME;var RESIDENT_SIZE_NUMERIC_NAME=tr.model.MemoryAllocatorDump.RESIDENT_SIZE_NUMERIC_NAME;function getSizeNumericValue(dump,sizeNumericName){var sizeNumeric=dump.numerics[sizeNumericName];if(sizeNumeric===undefined)return 0;return sizeNumeric.value;}function ProcessMemoryDump(globalMemoryDump,process,start){tr.model.ContainerMemoryDump.call(this,start);this.process=process;this.globalMemoryDump=globalMemoryDump;this.totals=undefined;this.vmRegions=undefined;this.heapDumps=undefined;this.tracingOverheadOwnershipSetUp_=false;this.tracingOverheadDiscountedFromVmRegions_=false;}ProcessMemoryDump.prototype={__proto__:tr.model.ContainerMemoryDump.prototype,get userFriendlyName(){return'Process memory dump at '+tr.b.Unit.byName.timeStampInMs.format(this.start);},get containerName(){return this.process.userFriendlyName;},get processMemoryDumps(){var dumps={};dumps[this.process.pid]=this;return dumps;},get hasOwnVmRegions(){return this.vmRegions!==undefined;},setUpTracingOverheadOwnership:function(opt_model){if(this.tracingOverheadOwnershipSetUp_)return;this.tracingOverheadOwnershipSetUp_=true;var tracingDump=this.getMemoryAllocatorDumpByFullName('tracing');if(tracingDump===undefined||tracingDump.owns!==undefined){return;}if(tracingDump.owns!==undefined)return;var hasDiscountedFromAllocatorDumps=DISCOUNTED_ALLOCATOR_NAMES.some(function(allocatorName){var allocatorDump=this.getMemoryAllocatorDumpByFullName(allocatorName);if(allocatorDump===undefined)return false;var nextPathIndex=0;var currentDump=allocatorDump;var currentFullName=allocatorName;for(;nextPathIndex<TRACING_OVERHEAD_PATH.length;nextPathIndex++){var childFullName=currentFullName+'/'+TRACING_OVERHEAD_PATH[nextPathIndex];var childDump=this.getMemoryAllocatorDumpByFullName(childFullName);if(childDump===undefined)break;currentDump=childDump;currentFullName=childFullName;}for(;nextPathIndex<TRACING_OVERHEAD_PATH.length;nextPathIndex++){var childFullName=currentFullName+'/'+TRACING_OVERHEAD_PATH[nextPathIndex];var childDump=new tr.model.MemoryAllocatorDump(currentDump.containerMemoryDump,childFullName);childDump.parent=currentDump;currentDump.children.push(childDump);currentFullName=childFullName;currentDump=childDump;}var ownershipLink=new tr.model.MemoryAllocatorDumpLink(tracingDump,currentDump);tracingDump.owns=ownershipLink;currentDump.ownedBy.push(ownershipLink);return true;},this);if(hasDiscountedFromAllocatorDumps)this.forceRebuildingMemoryAllocatorDumpByFullNameIndex();},discountTracingOverheadFromVmRegions:function(opt_model){if(this.tracingOverheadDiscountedFromVmRegions_)return;this.tracingOverheadDiscountedFromVmRegions_=true;var tracingDump=this.getMemoryAllocatorDumpByFullName('tracing');if(tracingDump===undefined)return;var discountedSize=getSizeNumericValue(tracingDump,SIZE_NUMERIC_NAME);var discountedResidentSize=getSizeNumericValue(tracingDump,RESIDENT_SIZE_NUMERIC_NAME);if(discountedSize<=0&&discountedResidentSize<=0)return;if(this.totals!==undefined){if(this.totals.residentBytes!==undefined)this.totals.residentBytes-=discountedResidentSize;if(this.totals.peakResidentBytes!==undefined)this.totals.peakResidentBytes-=discountedResidentSize;}if(this.vmRegions!==undefined){var hasSizeInBytes=this.vmRegions.sizeInBytes!==undefined;var hasPrivateDirtyResident=this.vmRegions.byteStats.privateDirtyResident!==undefined;var hasProportionalResident=this.vmRegions.byteStats.proportionalResident!==undefined;if(hasSizeInBytes&&discountedSize>0||(hasPrivateDirtyResident||hasProportionalResident)&&discountedResidentSize>0){var byteStats={};if(hasPrivateDirtyResident)byteStats.privateDirtyResident=-discountedResidentSize;if(hasProportionalResident)byteStats.proportionalResident=-discountedResidentSize;this.vmRegions.addRegion(tr.model.VMRegion.fromDict({mappedFile:'[discounted tracing overhead]',sizeInBytes:hasSizeInBytes?-discountedSize:undefined,byteStats:byteStats}));}}}};ProcessMemoryDump.hookUpMostRecentVmRegionsLinks=function(processDumps){var mostRecentVmRegions=undefined;processDumps.forEach(function(processDump){if(processDump.vmRegions!==undefined)mostRecentVmRegions=processDump.vmRegions;processDump.mostRecentVmRegions=mostRecentVmRegions;});};tr.model.EventRegistry.register(ProcessMemoryDump,{name:'processMemoryDump',pluralName:'processMemoryDumps'});return{ProcessMemoryDump:ProcessMemoryDump};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/unit.js":63,"./container_memory_dump.js":115,"./memory_allocator_dump.js":140,"./vm_region.js":174}],152:[function(require,module,exports){(function(global){"use strict";require("./location.js");require("./annotation.js");require("../ui/annotations/rect_annotation_view.js");'use strict';global.tr.exportTo('tr.model',function(){function RectAnnotation(start,end){tr.model.Annotation.apply(this,arguments);this.startLocation_=start;this.endLocation_=end;this.fillStyle='rgba(255, 180, 0, 0.3)';}RectAnnotation.fromDict=function(dict){var args=dict.args;var startLoc=new tr.model.Location(args.start.xWorld,args.start.yComponents);var endLoc=new tr.model.Location(args.end.xWorld,args.end.yComponents);return new tr.model.RectAnnotation(startLoc,endLoc);};RectAnnotation.prototype={__proto__:tr.model.Annotation.prototype,get startLocation(){return this.startLocation_;},get endLocation(){return this.endLocation_;},toDict:function(){return{typeName:'rect',args:{start:this.startLocation.toDict(),end:this.endLocation.toDict()}};},createView_:function(viewport){return new tr.ui.annotations.RectAnnotationView(viewport,this);}};tr.model.Annotation.register(RectAnnotation,{typeName:'rect'});return{RectAnnotation:RectAnnotation};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../ui/annotations/rect_annotation_view.js":178,"./annotation.js":108,"./location.js":139}],153:[function(require,module,exports){(function(global){"use strict";require("../base/unit.js");require("./timed_event.js");'use strict';global.tr.exportTo('tr.model',function(){function Sample(cpu,thread,title,start,leafStackFrame,opt_weight,opt_args){tr.model.TimedEvent.call(this,start);this.title=title;this.cpu=cpu;this.thread=thread;this.leafStackFrame=leafStackFrame;this.weight=opt_weight;this.args=opt_args||{};}Sample.prototype={__proto__:tr.model.TimedEvent.prototype,get colorId(){return this.leafStackFrame.colorId;},get stackTrace(){return this.leafStackFrame.stackTrace;},getUserFriendlyStackTrace:function(){return this.leafStackFrame.getUserFriendlyStackTrace();},get userFriendlyName(){return'Sample at '+tr.b.Unit.byName.timeStampInMs.format(this.start);}};tr.model.EventRegistry.register(Sample,{name:'sample',pluralName:'samples'});return{Sample:Sample};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/unit.js":63,"./timed_event.js":166}],154:[function(require,module,exports){(function(global){"use strict";require("../base/base.js");require("./constants.js");'use strict';global.tr.exportTo('tr.model',function(){function ScopedId(scope,id){if(scope===undefined){throw new Error('Scope should be defined. Use \''+tr.model.OBJECT_DEFAULT_SCOPE+'\' as the default scope.');}this.scope=scope;this.id=id;}ScopedId.prototype={toString:function(){return'{scope: '+this.scope+', id: '+this.id+'}';}};return{ScopedId:ScopedId};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/base.js":34,"./constants.js":114}],155:[function(require,module,exports){(function(global){"use strict";require("./selection_state.js");'use strict';global.tr.exportTo('tr.model',function(){var SelectionState=tr.model.SelectionState;function SelectableItem(modelItem){this.modelItem_=modelItem;}SelectableItem.prototype={get modelItem(){return this.modelItem_;},get selected(){return this.selectionState===SelectionState.SELECTED;},addToSelection:function(selection){var modelItem=this.modelItem_;if(!modelItem)return;selection.push(modelItem);},addToTrackMap:function(eventToTrackMap,track){var modelItem=this.modelItem_;if(!modelItem)return;eventToTrackMap.addEvent(modelItem,track);}};return{SelectableItem:SelectableItem};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./selection_state.js":156}],156:[function(require,module,exports){(function(global){"use strict";require("../base/base.js");require("../base/color_scheme.js");'use strict';global.tr.exportTo('tr.model',function(){var ColorScheme=tr.b.ColorScheme;var SelectionState={NONE:0,SELECTED:ColorScheme.properties.brightenedOffsets[0],HIGHLIGHTED:ColorScheme.properties.brightenedOffsets[1],DIMMED:ColorScheme.properties.dimmedOffsets[0],BRIGHTENED0:ColorScheme.properties.brightenedOffsets[0],BRIGHTENED1:ColorScheme.properties.brightenedOffsets[1],BRIGHTENED2:ColorScheme.properties.brightenedOffsets[2],DIMMED0:ColorScheme.properties.dimmedOffsets[0],DIMMED1:ColorScheme.properties.dimmedOffsets[1],DIMMED2:ColorScheme.properties.dimmedOffsets[2]};var brighteningLevels=[SelectionState.NONE,SelectionState.BRIGHTENED0,SelectionState.BRIGHTENED1,SelectionState.BRIGHTENED2];SelectionState.getFromBrighteningLevel=function(level){return brighteningLevels[level];};var dimmingLevels=[SelectionState.DIMMED0,SelectionState.DIMMED1,SelectionState.DIMMED2];SelectionState.getFromDimmingLevel=function(level){return dimmingLevels[level];};return{SelectionState:SelectionState};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/base.js":34,"../base/color_scheme.js":38}],157:[function(require,module,exports){(function(global){"use strict";require("../base/unit.js");require("./timed_event.js");'use strict';global.tr.exportTo('tr.model',function(){function Slice(category,title,colorId,start,args,opt_duration,opt_cpuStart,opt_cpuDuration,opt_argsStripped,opt_bindId){if(!(this instanceof Slice)){throw new Error("Can't instantiate pure virtual class Slice");}tr.model.TimedEvent.call(this,start);this.category=category||'';this.title=title;this.colorId=colorId;this.args=args;this.startStackFrame=undefined;this.endStackFrame=undefined;this.didNotFinish=false;this.inFlowEvents=[];this.outFlowEvents=[];this.subSlices=[];this.selfTime=undefined;this.cpuSelfTime=undefined;this.important=false;this.parentContainer=undefined;this.argsStripped=false;this.bind_id_=opt_bindId;this.parentSlice=undefined;this.isTopLevel=false;if(opt_duration!==undefined)this.duration=opt_duration;if(opt_cpuStart!==undefined)this.cpuStart=opt_cpuStart;if(opt_cpuDuration!==undefined)this.cpuDuration=opt_cpuDuration;if(opt_argsStripped!==undefined)this.argsStripped=true;}Slice.prototype={__proto__:tr.model.TimedEvent.prototype,get analysisTypeName(){return this.title;},get userFriendlyName(){return'Slice '+this.title+' at '+tr.b.Unit.byName.timeStampInMs.format(this.start);},get stableId(){var parentSliceGroup=this.parentContainer.sliceGroup;return parentSliceGroup.stableId+'.'+parentSliceGroup.slices.indexOf(this);},findDescendentSlice:function(targetTitle){if(!this.subSlices)return undefined;for(var i=0;i<this.subSlices.length;i++){if(this.subSlices[i].title==targetTitle)return this.subSlices[i];var slice=this.subSlices[i].findDescendentSlice(targetTitle);if(slice)return slice;}return undefined;},get mostTopLevelSlice(){var curSlice=this;while(curSlice.parentSlice)curSlice=curSlice.parentSlice;return curSlice;},getProcess:function(){var thread=this.parentContainer;if(thread&&thread.getProcess)return thread.getProcess();return undefined;},get model(){var process=this.getProcess();if(process!==undefined)return this.getProcess().model;return undefined;},findTopmostSlicesRelativeToThisSlice:function*(eventPredicate){if(eventPredicate(this)){yield this;return;}for(var s of this.subSlices)yield*s.findTopmostSlicesRelativeToThisSlice(eventPredicate);},iterateAllSubsequentSlices:function(callback,opt_this){var parentStack=[];var started=false;var topmostSlice=this.mostTopLevelSlice;parentStack.push(topmostSlice);while(parentStack.length!==0){var curSlice=parentStack.pop();if(started)callback.call(opt_this,curSlice);else started=curSlice.guid===this.guid;for(var i=curSlice.subSlices.length-1;i>=0;i--){parentStack.push(curSlice.subSlices[i]);}}},get subsequentSlices(){var res=[];this.iterateAllSubsequentSlices(function(subseqSlice){res.push(subseqSlice);});return res;},enumerateAllAncestors:function*(){var curSlice=this;while(curSlice.parentSlice){curSlice=curSlice.parentSlice;yield curSlice;}},get ancestorSlices(){var res=[];for(var slice of this.enumerateAllAncestors())res.push(slice);return res;},iterateEntireHierarchy:function(callback,opt_this){var mostTopLevelSlice=this.mostTopLevelSlice;callback.call(opt_this,mostTopLevelSlice);mostTopLevelSlice.iterateAllSubsequentSlices(callback,opt_this);},get entireHierarchy(){var res=[];this.iterateEntireHierarchy(function(slice){res.push(slice);});return res;},get ancestorAndSubsequentSlices(){var res=[];res.push(this);for(var aSlice of this.enumerateAllAncestors())res.push(aSlice);this.iterateAllSubsequentSlices(function(sSlice){res.push(sSlice);});return res;},enumerateAllDescendents:function*(){for(var slice of this.subSlices)yield slice;for(var slice of this.subSlices)yield*slice.enumerateAllDescendents();},get descendentSlices(){var res=[];for(var slice of this.enumerateAllDescendents())res.push(slice);return res;}};return{Slice:Slice};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/unit.js":63,"./timed_event.js":166}],158:[function(require,module,exports){(function(global){"use strict";require("../base/color_scheme.js");require("../base/guid.js");require("../base/sorted_array_utils.js");require("../core/filter.js");require("./event_container.js");require("./thread_slice.js");'use strict';global.tr.exportTo('tr.model',function(){var ColorScheme=tr.b.ColorScheme;var ThreadSlice=tr.model.ThreadSlice;function getSliceLo(s){return s.start;}function getSliceHi(s){return s.end;}function SliceGroup(parentContainer,opt_sliceConstructor,opt_name){tr.model.EventContainer.call(this);this.parentContainer_=parentContainer;var sliceConstructor=opt_sliceConstructor||ThreadSlice;this.sliceConstructor=sliceConstructor;this.sliceConstructorSubTypes=this.sliceConstructor.subTypes;if(!this.sliceConstructorSubTypes)throw new Error('opt_sliceConstructor must have a subtype registry.');this.openPartialSlices_=[];this.slices=[];this.topLevelSlices=[];this.haveTopLevelSlicesBeenBuilt=false;this.name_=opt_name;if(this.model===undefined)throw new Error('SliceGroup must have model defined.');}SliceGroup.prototype={__proto__:tr.model.EventContainer.prototype,get parentContainer(){return this.parentContainer_;},get model(){return this.parentContainer_.model;},get stableId(){return this.parentContainer_.stableId+'.SliceGroup';},getSettingsKey:function(){if(!this.name_)return undefined;var parentKey=this.parentContainer_.getSettingsKey();if(!parentKey)return undefined;return parentKey+'.'+this.name;},get length(){return this.slices.length;},pushSlice:function(slice){this.haveTopLevelSlicesBeenBuilt=false;slice.parentContainer=this.parentContainer_;this.slices.push(slice);return slice;},pushSlices:function(slices){this.haveTopLevelSlicesBeenBuilt=false;slices.forEach(function(slice){slice.parentContainer=this.parentContainer_;this.slices.push(slice);},this);},beginSlice:function(category,title,ts,opt_args,opt_tts,opt_argsStripped,opt_colorId){if(this.openPartialSlices_.length){var prevSlice=this.openPartialSlices_[this.openPartialSlices_.length-1];if(ts<prevSlice.start)throw new Error('Slices must be added in increasing timestamp order');}var colorId=opt_colorId||ColorScheme.getColorIdForGeneralPurposeString(title);var sliceConstructorSubTypes=this.sliceConstructorSubTypes;var sliceType=sliceConstructorSubTypes.getConstructor(category,title);var slice=new sliceType(category,title,colorId,ts,opt_args?opt_args:{},null,opt_tts,undefined,opt_argsStripped);this.openPartialSlices_.push(slice);slice.didNotFinish=true;this.pushSlice(slice);return slice;},isTimestampValidForBeginOrEnd:function(ts){if(!this.openPartialSlices_.length)return true;var top=this.openPartialSlices_[this.openPartialSlices_.length-1];return ts>=top.start;},get openSliceCount(){return this.openPartialSlices_.length;},get mostRecentlyOpenedPartialSlice(){if(!this.openPartialSlices_.length)return undefined;return this.openPartialSlices_[this.openPartialSlices_.length-1];},endSlice:function(ts,opt_tts,opt_colorId){if(!this.openSliceCount)throw new Error('endSlice called without an open slice');var slice=this.openPartialSlices_[this.openSliceCount-1];this.openPartialSlices_.splice(this.openSliceCount-1,1);if(ts<slice.start)throw new Error('Slice '+slice.title+' end time is before its start.');slice.duration=ts-slice.start;slice.didNotFinish=false;slice.colorId=opt_colorId||slice.colorId;if(opt_tts&&slice.cpuStart!==undefined)slice.cpuDuration=opt_tts-slice.cpuStart;return slice;},pushCompleteSlice:function(category,title,ts,duration,tts,cpuDuration,opt_args,opt_argsStripped,opt_colorId,opt_bindId){var colorId=opt_colorId||ColorScheme.getColorIdForGeneralPurposeString(title);var sliceConstructorSubTypes=this.sliceConstructorSubTypes;var sliceType=sliceConstructorSubTypes.getConstructor(category,title);var slice=new sliceType(category,title,colorId,ts,opt_args?opt_args:{},duration,tts,cpuDuration,opt_argsStripped,opt_bindId);if(duration===undefined)slice.didNotFinish=true;this.pushSlice(slice);return slice;},autoCloseOpenSlices:function(){this.updateBounds();var maxTimestamp=this.bounds.max;for(var sI=0;sI<this.slices.length;sI++){var slice=this.slices[sI];if(slice.didNotFinish)slice.duration=maxTimestamp-slice.start;}this.openPartialSlices_=[];},shiftTimestampsForward:function(amount){for(var sI=0;sI<this.slices.length;sI++){var slice=this.slices[sI];slice.start=slice.start+amount;}},updateBounds:function(){this.bounds.reset();for(var i=0;i<this.slices.length;i++){this.bounds.addValue(this.slices[i].start);this.bounds.addValue(this.slices[i].end);}},copySlice:function(slice){var sliceConstructorSubTypes=this.sliceConstructorSubTypes;var sliceType=sliceConstructorSubTypes.getConstructor(slice.category,slice.title);var newSlice=new sliceType(slice.category,slice.title,slice.colorId,slice.start,slice.args,slice.duration,slice.cpuStart,slice.cpuDuration);newSlice.didNotFinish=slice.didNotFinish;return newSlice;},findTopmostSlicesInThisContainer:function*(eventPredicate,opt_this){if(!this.haveTopLevelSlicesBeenBuilt)throw new Error('Nope');for(var s of this.topLevelSlices)yield*s.findTopmostSlicesRelativeToThisSlice(eventPredicate);},childEvents:function*(){yield*this.slices;},childEventContainers:function*(){},getSlicesOfName:function(title){var slices=[];for(var i=0;i<this.slices.length;i++){if(this.slices[i].title==title){slices.push(this.slices[i]);}}return slices;},iterSlicesInTimeRange:function(callback,start,end){var ret=[];tr.b.iterateOverIntersectingIntervals(this.topLevelSlices,function(s){return s.start;},function(s){return s.duration;},start,end,function(topLevelSlice){callback(topLevelSlice);for(var slice of topLevelSlice.enumerateAllDescendents())callback(slice);});return ret;},findFirstSlice:function(){if(!this.haveTopLevelSlicesBeenBuilt)throw new Error('Nope');if(0===this.slices.length)return undefined;return this.slices[0];},findSliceAtTs:function(ts){if(!this.haveTopLevelSlicesBeenBuilt)throw new Error('Nope');var i=tr.b.findIndexInSortedClosedIntervals(this.topLevelSlices,getSliceLo,getSliceHi,ts);if(i==-1||i==this.topLevelSlices.length)return undefined;var curSlice=this.topLevelSlices[i];while(true){var i=tr.b.findIndexInSortedClosedIntervals(curSlice.subSlices,getSliceLo,getSliceHi,ts);if(i==-1||i==curSlice.subSlices.length)return curSlice;curSlice=curSlice.subSlices[i];}},findNextSliceAfter:function(ts,refGuid){var i=tr.b.findLowIndexInSortedArray(this.slices,getSliceLo,ts);if(i===this.slices.length)return undefined;for(;i<this.slices.length;i++){var slice=this.slices[i];if(slice.start>ts)return slice;if(slice.guid<=refGuid)continue;return slice;}return undefined;},createSubSlices:function(){this.haveTopLevelSlicesBeenBuilt=true;this.createSubSlicesImpl_();if(this.parentContainer.timeSlices)this.addCpuTimeToSubslices_(this.parentContainer.timeSlices);this.slices.forEach(function(slice){var selfTime=slice.duration;for(var i=0;i<slice.subSlices.length;i++)selfTime-=slice.subSlices[i].duration;slice.selfTime=selfTime;if(slice.cpuDuration===undefined)return;var cpuSelfTime=slice.cpuDuration;for(var i=0;i<slice.subSlices.length;i++){if(slice.subSlices[i].cpuDuration!==undefined)cpuSelfTime-=slice.subSlices[i].cpuDuration;}slice.cpuSelfTime=cpuSelfTime;});},createSubSlicesImpl_:function(){var precisionUnit=this.model.intrinsicTimeUnit;function addSliceIfBounds(parent,child){if(parent.bounds(child,precisionUnit)){child.parentSlice=parent;if(parent.subSlices===undefined)parent.subSlices=[];parent.subSlices.push(child);return true;}return false;}if(!this.slices.length)return;var ops=[];for(var i=0;i<this.slices.length;i++){if(this.slices[i].subSlices)this.slices[i].subSlices.splice(0,this.slices[i].subSlices.length);ops.push(i);}var originalSlices=this.slices;ops.sort(function(ix,iy){var x=originalSlices[ix];var y=originalSlices[iy];if(x.start!=y.start)return x.start-y.start;return ix-iy;});var slices=new Array(this.slices.length);for(var i=0;i<ops.length;i++){slices[i]=originalSlices[ops[i]];}var rootSlice=slices[0];this.topLevelSlices=[];this.topLevelSlices.push(rootSlice);rootSlice.isTopLevel=true;for(var i=1;i<slices.length;i++){var slice=slices[i];while(rootSlice!==undefined&&!addSliceIfBounds(rootSlice,slice)){rootSlice=rootSlice.parentSlice;}if(rootSlice===undefined){this.topLevelSlices.push(slice);slice.isTopLevel=true;}rootSlice=slice;}this.slices=slices;},addCpuTimeToSubslices_:function(timeSlices){var SCHEDULING_STATE=tr.model.SCHEDULING_STATE;var sliceIdx=0;timeSlices.forEach(function(timeSlice){if(timeSlice.schedulingState==SCHEDULING_STATE.RUNNING){while(sliceIdx<this.topLevelSlices.length){if(this.addCpuTimeToSubslice_(this.topLevelSlices[sliceIdx],timeSlice)){sliceIdx++;}else{break;}}}},this);},addCpuTimeToSubslice_:function(slice,timeSlice){if(slice.start>timeSlice.end||slice.end<timeSlice.start)return slice.end<=timeSlice.end;var duration=timeSlice.duration;if(slice.start>timeSlice.start)duration-=slice.start-timeSlice.start;if(timeSlice.end>slice.end)duration-=timeSlice.end-slice.end;if(slice.cpuDuration){slice.cpuDuration+=duration;}else{slice.cpuDuration=duration;}for(var i=0;i<slice.subSlices.length;i++){this.addCpuTimeToSubslice_(slice.subSlices[i],timeSlice);}return slice.end<=timeSlice.end;}};SliceGroup.merge=function(groupA,groupB){if(groupA.openPartialSlices_.length>0)throw new Error('groupA has open partial slices');if(groupB.openPartialSlices_.length>0)throw new Error('groupB has open partial slices');if(groupA.parentContainer!=groupB.parentContainer)throw new Error('Different parent threads. Cannot merge');if(groupA.sliceConstructor!=groupB.sliceConstructor)throw new Error('Different slice constructors. Cannot merge');var result=new SliceGroup(groupA.parentContainer,groupA.sliceConstructor,groupA.name_);var slicesA=groupA.slices;var slicesB=groupB.slices;var idxA=0;var idxB=0;var openA=[];var openB=[];var splitOpenSlices=function(when){for(var i=0;i<openB.length;i++){var oldSlice=openB[i];var oldEnd=oldSlice.end;if(when<oldSlice.start||oldEnd<when){throw new Error('slice should not be split');}var newSlice=result.copySlice(oldSlice);newSlice.start=when;newSlice.duration=oldEnd-when;if(newSlice.title.indexOf(' (cont.)')==-1)newSlice.title+=' (cont.)';oldSlice.duration=when-oldSlice.start;openB[i]=newSlice;result.pushSlice(newSlice);}};var closeOpenSlices=function(upTo){while(openA.length>0||openB.length>0){var nextA=openA[openA.length-1];var nextB=openB[openB.length-1];var endA=nextA&&nextA.end;var endB=nextB&&nextB.end;if((endA===undefined||endA>upTo)&&(endB===undefined||endB>upTo)){return;}if(endB===undefined||endA<endB){splitOpenSlices(endA);openA.pop();}else{openB.pop();}}};while(idxA<slicesA.length||idxB<slicesB.length){var sA=slicesA[idxA];var sB=slicesB[idxB];var nextSlice,isFromB;if(sA===undefined||sB!==undefined&&sA.start>sB.start){nextSlice=result.copySlice(sB);isFromB=true;idxB++;}else{nextSlice=result.copySlice(sA);isFromB=false;idxA++;}closeOpenSlices(nextSlice.start);result.pushSlice(nextSlice);if(isFromB){openB.push(nextSlice);}else{splitOpenSlices(nextSlice.start);openA.push(nextSlice);}}closeOpenSlices();return result;};return{SliceGroup:SliceGroup};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/color_scheme.js":38,"../base/guid.js":45,"../base/sorted_array_utils.js":58,"../core/filter.js":67,"./event_container.js":123,"./thread_slice.js":163}],159:[function(require,module,exports){(function(global){"use strict";require("./source_info.js");'use strict';global.tr.exportTo('tr.model.source_info',function(){function JSSourceInfo(file,line,column,isNative,scriptId,state){tr.model.source_info.SourceInfo.call(this,file,line,column);this.isNative_=isNative;this.scriptId_=scriptId;this.state_=state;}JSSourceInfo.prototype={__proto__:tr.model.source_info.SourceInfo.prototype,get state(){return this.state_;},get isNative(){return this.isNative_;},get scriptId(){return this.scriptId_;},toString:function(){var str=this.isNative_?'[native v8] ':'';return str+tr.model.source_info.SourceInfo.prototype.toString.call(this);}};return{JSSourceInfo:JSSourceInfo,JSSourceState:{COMPILED:'compiled',OPTIMIZABLE:'optimizable',OPTIMIZED:'optimized',UNKNOWN:'unknown'}};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./source_info.js":160}],160:[function(require,module,exports){(function(global){"use strict";require("../../base/base.js");'use strict';global.tr.exportTo('tr.model.source_info',function(){function SourceInfo(file,opt_line,opt_column){this.file_=file;this.line_=opt_line||-1;this.column_=opt_column||-1;}SourceInfo.prototype={get file(){return this.file_;},get line(){return this.line_;},get column(){return this.column_;},get domain(){if(!this.file_)return undefined;var domain=this.file_.match(/(.*:\/\/[^:\/]*)/i);return domain?domain[1]:undefined;},toString:function(){var str='';if(this.file_)str+=this.file_;if(this.line_>0)str+=':'+this.line_;if(this.column_>0)str+=':'+this.column_;return str;}};return{SourceInfo:SourceInfo};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../../base/base.js":34}],161:[function(require,module,exports){(function(global){"use strict";require("../base/base.js");'use strict';global.tr.exportTo('tr.model',function(){function StackFrame(parentFrame,id,title,colorId,opt_sourceInfo){if(id===undefined)throw new Error('id must be given');this.parentFrame_=parentFrame;this.id=id;this.title_=title;this.colorId=colorId;this.children=[];this.sourceInfo_=opt_sourceInfo;if(this.parentFrame_)this.parentFrame_.addChild(this);}StackFrame.prototype={get parentFrame(){return this.parentFrame_;},get title(){if(this.sourceInfo_){var src=this.sourceInfo_.toString();return this.title_+(src===''?'':' '+src);}return this.title_;},get domain(){var result='unknown';if(this.sourceInfo_&&this.sourceInfo_.domain)result=this.sourceInfo_.domain;if(result==='unknown'&&this.parentFrame)result=this.parentFrame.domain;return result;},get sourceInfo(){return this.sourceInfo_;},set parentFrame(parentFrame){if(this.parentFrame_)Polymer.dom(this.parentFrame_).removeChild(this);this.parentFrame_=parentFrame;if(this.parentFrame_)this.parentFrame_.addChild(this);},addChild:function(child){this.children.push(child);},removeChild:function(child){var i=this.children.indexOf(child.id);if(i==-1)throw new Error('omg');this.children.splice(i,1);},removeAllChildren:function(){for(var i=0;i<this.children.length;i++)this.children[i].parentFrame_=undefined;this.children.splice(0,this.children.length);},get stackTrace(){var stack=[];var cur=this;while(cur){stack.push(cur);cur=cur.parentFrame;}return stack;},getUserFriendlyStackTrace:function(){return this.stackTrace.map(function(x){return x.title;});}};return{StackFrame:StackFrame};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/base.js":34}],162:[function(require,module,exports){(function(global){"use strict";require("../base/guid.js");require("../base/range.js");require("./async_slice_group.js");require("./event_container.js");require("./slice_group.js");require("./thread_slice.js");'use strict';global.tr.exportTo('tr.model',function(){var AsyncSlice=tr.model.AsyncSlice;var AsyncSliceGroup=tr.model.AsyncSliceGroup;var SliceGroup=tr.model.SliceGroup;var ThreadSlice=tr.model.ThreadSlice;var ThreadTimeSlice=tr.model.ThreadTimeSlice;function Thread(parent,tid){if(!parent)throw new Error('Parent must be provided.');tr.model.EventContainer.call(this);this.parent=parent;this.sortIndex=0;this.tid=tid;this.name=undefined;this.samples_=undefined;var that=this;this.sliceGroup=new SliceGroup(this,ThreadSlice,'slices');this.timeSlices=undefined;this.kernelSliceGroup=new SliceGroup(this,ThreadSlice,'kernel-slices');this.asyncSliceGroup=new AsyncSliceGroup(this,'async-slices');}Thread.prototype={__proto__:tr.model.EventContainer.prototype,get model(){return this.parent.model;},get stableId(){return this.parent.stableId+'.'+this.tid;},compareTo:function(that){return Thread.compare(this,that);},childEventContainers:function*(){if(this.sliceGroup.length)yield this.sliceGroup;if(this.kernelSliceGroup.length)yield this.kernelSliceGroup;if(this.asyncSliceGroup.length)yield this.asyncSliceGroup;},childEvents:function*(){if(this.timeSlices)yield*this.timeSlices;},iterateAllPersistableObjects:function(cb){cb(this);if(this.sliceGroup.length)cb(this.sliceGroup);this.asyncSliceGroup.viewSubGroups.forEach(cb);},shiftTimestampsForward:function(amount){this.sliceGroup.shiftTimestampsForward(amount);if(this.timeSlices){for(var i=0;i<this.timeSlices.length;i++){var slice=this.timeSlices[i];slice.start+=amount;}}this.kernelSliceGroup.shiftTimestampsForward(amount);this.asyncSliceGroup.shiftTimestampsForward(amount);},get isEmpty(){if(this.sliceGroup.length)return false;if(this.sliceGroup.openSliceCount)return false;if(this.timeSlices&&this.timeSlices.length)return false;if(this.kernelSliceGroup.length)return false;if(this.asyncSliceGroup.length)return false;if(this.samples_.length)return false;return true;},updateBounds:function(){this.bounds.reset();this.sliceGroup.updateBounds();this.bounds.addRange(this.sliceGroup.bounds);this.kernelSliceGroup.updateBounds();this.bounds.addRange(this.kernelSliceGroup.bounds);this.asyncSliceGroup.updateBounds();this.bounds.addRange(this.asyncSliceGroup.bounds);if(this.timeSlices&&this.timeSlices.length){this.bounds.addValue(this.timeSlices[0].start);this.bounds.addValue(this.timeSlices[this.timeSlices.length-1].end);}if(this.samples_&&this.samples_.length){this.bounds.addValue(this.samples_[0].start);this.bounds.addValue(this.samples_[this.samples_.length-1].end);}},addCategoriesToDict:function(categoriesDict){for(var i=0;i<this.sliceGroup.length;i++)categoriesDict[this.sliceGroup.slices[i].category]=true;for(var i=0;i<this.kernelSliceGroup.length;i++)categoriesDict[this.kernelSliceGroup.slices[i].category]=true;for(var i=0;i<this.asyncSliceGroup.length;i++)categoriesDict[this.asyncSliceGroup.slices[i].category]=true;if(this.samples_){for(var i=0;i<this.samples_.length;i++)categoriesDict[this.samples_[i].category]=true;}},autoCloseOpenSlices:function(){this.sliceGroup.autoCloseOpenSlices();this.kernelSliceGroup.autoCloseOpenSlices();},mergeKernelWithUserland:function(){if(this.kernelSliceGroup.length>0){var newSlices=SliceGroup.merge(this.sliceGroup,this.kernelSliceGroup);this.sliceGroup.slices=newSlices.slices;this.kernelSliceGroup=new SliceGroup(this);this.updateBounds();}},createSubSlices:function(){this.sliceGroup.createSubSlices();this.samples_=this.parent.model.samples.filter(function(sample){return sample.thread==this;},this);},get userFriendlyName(){return this.name||this.tid;},get userFriendlyDetails(){return'tid: '+this.tid+(this.name?', name: '+this.name:'');},getSettingsKey:function(){if(!this.name)return undefined;var parentKey=this.parent.getSettingsKey();if(!parentKey)return undefined;return parentKey+'.'+this.name;},getProcess:function(){return this.parent;},indexOfTimeSlice:function(timeSlice){var i=tr.b.findLowIndexInSortedArray(this.timeSlices,function(slice){return slice.start;},timeSlice.start);if(this.timeSlices[i]!==timeSlice)return undefined;return i;},getCpuStatsForRange:function(range){var stats={};stats.total=0;if(!this.timeSlices)return stats;function addStatsForSlice(threadTimeSlice){var freqRange=tr.b.Range.fromExplicitRange(threadTimeSlice.start,threadTimeSlice.end);var intersection=freqRange.findIntersection(range);if(threadTimeSlice.schedulingState==tr.model.SCHEDULING_STATE.RUNNING){var cpu=threadTimeSlice.cpuOnWhichThreadWasRunning;if(!(cpu.cpuNumber in stats))stats[cpu.cpuNumber]=0;stats[cpu.cpuNumber]+=intersection.duration;stats.total+=intersection.duration;}}tr.b.iterateOverIntersectingIntervals(this.timeSlices,function(x){return x.start;},function(x){return x.end;},range.min,range.max,addStatsForSlice);return stats;},getSchedulingStatsForRange:function(start,end){var stats={};if(!this.timeSlices)return stats;function addStatsForSlice(threadTimeSlice){var overlapStart=Math.max(threadTimeSlice.start,start);var overlapEnd=Math.min(threadTimeSlice.end,end);var schedulingState=threadTimeSlice.schedulingState;if(!(schedulingState in stats))stats[schedulingState]=0;stats[schedulingState]+=overlapEnd-overlapStart;}tr.b.iterateOverIntersectingIntervals(this.timeSlices,function(x){return x.start;},function(x){return x.end;},start,end,addStatsForSlice);return stats;},get samples(){return this.samples_;}};Thread.compare=function(x,y){var tmp=x.parent.compareTo(y.parent);if(tmp)return tmp;tmp=x.sortIndex-y.sortIndex;if(tmp)return tmp;tmp=tr.b.comparePossiblyUndefinedValues(x.name,y.name,function(x,y){return x.localeCompare(y);});if(tmp)return tmp;return x.tid-y.tid;};return{Thread:Thread};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/guid.js":45,"../base/range.js":53,"./async_slice_group.js":110,"./event_container.js":123,"./slice_group.js":158,"./thread_slice.js":163}],163:[function(require,module,exports){(function(global){"use strict";require("./slice.js");'use strict';global.tr.exportTo('tr.model',function(){var Slice=tr.model.Slice;function ThreadSlice(cat,title,colorId,start,args,opt_duration,opt_cpuStart,opt_cpuDuration,opt_argsStripped,opt_bindId){Slice.call(this,cat,title,colorId,start,args,opt_duration,opt_cpuStart,opt_cpuDuration,opt_argsStripped,opt_bindId);this.subSlices=[];}ThreadSlice.prototype={__proto__:Slice.prototype,get overlappingSamples(){var samples=new tr.model.EventSet();if(!this.parentContainer||!this.parentContainer.samples)return samples;this.parentContainer.samples.forEach(function(sample){if(this.start<=sample.start&&sample.start<=this.end)samples.push(sample);},this);return samples;}};tr.model.EventRegistry.register(ThreadSlice,{name:'slice',pluralName:'slices'});return{ThreadSlice:ThreadSlice};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./slice.js":157}],164:[function(require,module,exports){(function(global){"use strict";require("../base/range.js");require("./slice.js");'use strict';global.tr.exportTo('tr.model',function(){var Slice=tr.model.Slice;var SCHEDULING_STATE={DEBUG:'Debug',EXIT_DEAD:'Exit Dead',RUNNABLE:'Runnable',RUNNING:'Running',SLEEPING:'Sleeping',STOPPED:'Stopped',TASK_DEAD:'Task Dead',UNINTR_SLEEP:'Uninterruptible Sleep',UNINTR_SLEEP_WAKE_KILL:'Uninterruptible Sleep | WakeKill',UNINTR_SLEEP_WAKING:'Uninterruptible Sleep | Waking',UNINTR_SLEEP_IO:'Uninterruptible Sleep - Block I/O',UNINTR_SLEEP_WAKE_KILL_IO:'Uninterruptible Sleep | WakeKill - Block I/O',UNINTR_SLEEP_WAKING_IO:'Uninterruptible Sleep | Waking - Block I/O',UNKNOWN:'UNKNOWN',WAKE_KILL:'Wakekill',WAKING:'Waking',ZOMBIE:'Zombie'};function ThreadTimeSlice(thread,schedulingState,cat,start,args,opt_duration){Slice.call(this,cat,schedulingState,this.getColorForState_(schedulingState),start,args,opt_duration);this.thread=thread;this.schedulingState=schedulingState;this.cpuOnWhichThreadWasRunning=undefined;}ThreadTimeSlice.prototype={__proto__:Slice.prototype,getColorForState_:function(state){var getColorIdForReservedName=tr.b.ColorScheme.getColorIdForReservedName;switch(state){case SCHEDULING_STATE.RUNNABLE:return getColorIdForReservedName('thread_state_runnable');case SCHEDULING_STATE.RUNNING:return getColorIdForReservedName('thread_state_running');case SCHEDULING_STATE.SLEEPING:return getColorIdForReservedName('thread_state_sleeping');case SCHEDULING_STATE.DEBUG:case SCHEDULING_STATE.EXIT_DEAD:case SCHEDULING_STATE.STOPPED:case SCHEDULING_STATE.TASK_DEAD:case SCHEDULING_STATE.UNINTR_SLEEP:case SCHEDULING_STATE.UNINTR_SLEEP_WAKE_KILL:case SCHEDULING_STATE.UNINTR_SLEEP_WAKING:case SCHEDULING_STATE.UNKNOWN:case SCHEDULING_STATE.WAKE_KILL:case SCHEDULING_STATE.WAKING:case SCHEDULING_STATE.ZOMBIE:return getColorIdForReservedName('thread_state_uninterruptible');case SCHEDULING_STATE.UNINTR_SLEEP_IO:case SCHEDULING_STATE.UNINTR_SLEEP_WAKE_KILL_IO:case SCHEDULING_STATE.UNINTR_SLEEP_WAKING_IO:return getColorIdForReservedName('thread_state_iowait');default:return getColorIdForReservedName('thread_state_unknown');}},get analysisTypeName(){return'tr.ui.analysis.ThreadTimeSlice';},getAssociatedCpuSlice:function(){if(!this.cpuOnWhichThreadWasRunning)return undefined;var cpuSlices=this.cpuOnWhichThreadWasRunning.slices;for(var i=0;i<cpuSlices.length;i++){var cpuSlice=cpuSlices[i];if(cpuSlice.start!==this.start)continue;if(cpuSlice.duration!==this.duration)continue;return cpuSlice;}return undefined;},getCpuSliceThatTookCpu:function(){if(this.cpuOnWhichThreadWasRunning)return undefined;var curIndex=this.thread.indexOfTimeSlice(this);var cpuSliceWhenLastRunning;while(curIndex>=0){var curSlice=this.thread.timeSlices[curIndex];if(!curSlice.cpuOnWhichThreadWasRunning){curIndex--;continue;}cpuSliceWhenLastRunning=curSlice.getAssociatedCpuSlice();break;}if(!cpuSliceWhenLastRunning)return undefined;var cpu=cpuSliceWhenLastRunning.cpu;var indexOfSliceOnCpuWhenLastRunning=cpu.indexOf(cpuSliceWhenLastRunning);var nextRunningSlice=cpu.slices[indexOfSliceOnCpuWhenLastRunning+1];if(!nextRunningSlice)return undefined;if(Math.abs(nextRunningSlice.start-cpuSliceWhenLastRunning.end)<0.00001)return nextRunningSlice;return undefined;}};tr.model.EventRegistry.register(ThreadTimeSlice,{name:'threadTimeSlice',pluralName:'threadTimeSlices'});return{ThreadTimeSlice:ThreadTimeSlice,SCHEDULING_STATE:SCHEDULING_STATE};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/range.js":53,"./slice.js":157}],165:[function(require,module,exports){(function(global){"use strict";require("../base/range.js");require("../base/sorted_array_utils.js");'use strict';global.tr.exportTo('tr.model',function(){function TimeToObjectInstanceMap(createObjectInstanceFunction,parent,scopedId){this.createObjectInstanceFunction_=createObjectInstanceFunction;this.parent=parent;this.scopedId=scopedId;this.instances=[];}TimeToObjectInstanceMap.prototype={idWasCreated:function(category,name,ts){if(this.instances.length==0){this.instances.push(this.createObjectInstanceFunction_(this.parent,this.scopedId,category,name,ts));this.instances[0].creationTsWasExplicit=true;return this.instances[0];}var lastInstance=this.instances[this.instances.length-1];if(ts<lastInstance.deletionTs){throw new Error('Mutation of the TimeToObjectInstanceMap must be '+'done in ascending timestamp order.');}lastInstance=this.createObjectInstanceFunction_(this.parent,this.scopedId,category,name,ts);lastInstance.creationTsWasExplicit=true;this.instances.push(lastInstance);return lastInstance;},addSnapshot:function(category,name,ts,args,opt_baseTypeName){if(this.instances.length==0){this.instances.push(this.createObjectInstanceFunction_(this.parent,this.scopedId,category,name,ts,opt_baseTypeName));}var i=tr.b.findIndexInSortedIntervals(this.instances,function(inst){return inst.creationTs;},function(inst){return inst.deletionTs-inst.creationTs;},ts);var instance;if(i<0){instance=this.instances[0];if(ts>instance.deletionTs||instance.creationTsWasExplicit){throw new Error('At the provided timestamp, no instance was still alive');}if(instance.snapshots.length!=0){throw new Error('Cannot shift creationTs forward, '+'snapshots have been added. First snap was at ts='+instance.snapshots[0].ts+' and creationTs was '+instance.creationTs);}instance.creationTs=ts;}else if(i>=this.instances.length){instance=this.instances[this.instances.length-1];if(ts>=instance.deletionTs){instance=this.createObjectInstanceFunction_(this.parent,this.scopedId,category,name,ts,opt_baseTypeName);this.instances.push(instance);}else{var lastValidIndex;for(var i=this.instances.length-1;i>=0;i--){var tmp=this.instances[i];if(ts>=tmp.deletionTs)break;if(tmp.creationTsWasExplicit==false&&tmp.snapshots.length==0)lastValidIndex=i;}if(lastValidIndex===undefined){throw new Error('Cannot add snapshot. No instance was alive that was mutable.');}instance=this.instances[lastValidIndex];instance.creationTs=ts;}}else{instance=this.instances[i];}return instance.addSnapshot(ts,args,name,opt_baseTypeName);},get lastInstance(){if(this.instances.length==0)return undefined;return this.instances[this.instances.length-1];},idWasDeleted:function(category,name,ts){if(this.instances.length==0){this.instances.push(this.createObjectInstanceFunction_(this.parent,this.scopedId,category,name,ts));}var lastInstance=this.instances[this.instances.length-1];if(ts<lastInstance.creationTs)throw new Error('Cannot delete an id before it was created');if(lastInstance.deletionTs==Number.MAX_VALUE){lastInstance.wasDeleted(ts);return lastInstance;}if(ts<lastInstance.deletionTs)throw new Error('id was already deleted earlier.');lastInstance=this.createObjectInstanceFunction_(this.parent,this.scopedId,category,name,ts);this.instances.push(lastInstance);lastInstance.wasDeleted(ts);return lastInstance;},getInstanceAt:function(ts){var i=tr.b.findIndexInSortedIntervals(this.instances,function(inst){return inst.creationTs;},function(inst){return inst.deletionTs-inst.creationTs;},ts);if(i<0){if(this.instances[0].creationTsWasExplicit)return undefined;return this.instances[0];}else if(i>=this.instances.length){return undefined;}return this.instances[i];},logToConsole:function(){for(var i=0;i<this.instances.length;i++){var instance=this.instances[i];var cEF='';var dEF='';if(instance.creationTsWasExplicit)cEF='(explicitC)';if(instance.deletionTsWasExplicit)dEF='(explicit)';console.log(instance.creationTs,cEF,instance.deletionTs,dEF,instance.category,instance.name,instance.snapshots.length+' snapshots');}}};return{TimeToObjectInstanceMap:TimeToObjectInstanceMap};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/range.js":53,"../base/sorted_array_utils.js":58}],166:[function(require,module,exports){(function(global){"use strict";require("../base/guid.js");require("../base/time_display_modes.js");require("./event.js");'use strict';global.tr.exportTo('tr.model',function(){function TimedEvent(start){tr.model.Event.call(this);this.start=start;this.duration=0;this.cpuStart=undefined;this.cpuDuration=undefined;this.contexts=Object.freeze([]);}TimedEvent.prototype={__proto__:tr.model.Event.prototype,get end(){return this.start+this.duration;},addBoundsToRange:function(range){range.addValue(this.start);range.addValue(this.end);},bounds:function(that,opt_precisionUnit){if(opt_precisionUnit===undefined)opt_precisionUnit=tr.b.TimeDisplayModes.ms;var startsBefore=opt_precisionUnit.roundedLess(that.start,this.start);var endsAfter=opt_precisionUnit.roundedLess(this.end,that.end);return!startsBefore&&!endsAfter;}};return{TimedEvent:TimedEvent};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/guid.js":45,"../base/time_display_modes.js":61,"./event.js":122}],167:[function(require,module,exports){(function(global){"use strict";require("./user_expectation.js");'use strict';global.tr.exportTo('tr.model.um',function(){function AnimationExpectation(parentModel,initiatorTitle,start,duration){tr.model.um.UserExpectation.call(this,parentModel,initiatorTitle,start,duration);this.frameEvents_=undefined;}AnimationExpectation.prototype={__proto__:tr.model.um.UserExpectation.prototype,constructor:AnimationExpectation,get frameEvents(){if(this.frameEvents_)return this.frameEvents_;this.frameEvents_=new tr.model.EventSet();this.associatedEvents.forEach(function(event){if(event.title===tr.model.helpers.IMPL_RENDERING_STATS)this.frameEvents_.push(event);},this);return this.frameEvents_;}};tr.model.um.UserExpectation.subTypes.register(AnimationExpectation,{stageTitle:'Animation',colorId:tr.b.ColorScheme.getColorIdForReservedName('rail_animation')});return{AnimationExpectation:AnimationExpectation};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./user_expectation.js":172}],168:[function(require,module,exports){(function(global){"use strict";require("./user_expectation.js");'use strict';global.tr.exportTo('tr.model.um',function(){function IdleExpectation(parentModel,start,duration){var initiatorTitle='';tr.model.um.UserExpectation.call(this,parentModel,initiatorTitle,start,duration);}IdleExpectation.prototype={__proto__:tr.model.um.UserExpectation.prototype,constructor:IdleExpectation};tr.model.um.UserExpectation.subTypes.register(IdleExpectation,{stageTitle:'Idle',colorId:tr.b.ColorScheme.getColorIdForReservedName('rail_idle')});return{IdleExpectation:IdleExpectation};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./user_expectation.js":172}],169:[function(require,module,exports){(function(global){"use strict";require("./user_expectation.js");'use strict';global.tr.exportTo('tr.model.um',function(){var LOAD_SUBTYPE_NAMES={SUCCESSFUL:'Successful',FAILED:'Failed'};var DOES_LOAD_SUBTYPE_NAME_EXIST={};for(var key in LOAD_SUBTYPE_NAMES){DOES_LOAD_SUBTYPE_NAME_EXIST[LOAD_SUBTYPE_NAMES[key]]=true;;}function LoadExpectation(parentModel,initiatorTitle,start,duration){if(!DOES_LOAD_SUBTYPE_NAME_EXIST[initiatorTitle])throw new Error(initiatorTitle+' is not in LOAD_SUBTYPE_NAMES');tr.model.um.UserExpectation.call(this,parentModel,initiatorTitle,start,duration);this.renderProcess=undefined;this.renderMainThread=undefined;this.routingId=undefined;this.parentRoutingId=undefined;this.loadFinishedEvent=undefined;}LoadExpectation.prototype={__proto__:tr.model.um.UserExpectation.prototype,constructor:LoadExpectation};tr.model.um.UserExpectation.subTypes.register(LoadExpectation,{stageTitle:'Load',colorId:tr.b.ColorScheme.getColorIdForReservedName('rail_load')});return{LOAD_SUBTYPE_NAMES:LOAD_SUBTYPE_NAMES,LoadExpectation:LoadExpectation};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./user_expectation.js":172}],170:[function(require,module,exports){(function(global){"use strict";require("./user_expectation.js");'use strict';global.tr.exportTo('tr.model.um',function(){function ResponseExpectation(parentModel,initiatorTitle,start,duration,opt_isAnimationBegin){tr.model.um.UserExpectation.call(this,parentModel,initiatorTitle,start,duration);this.isAnimationBegin=opt_isAnimationBegin||false;}ResponseExpectation.prototype={__proto__:tr.model.um.UserExpectation.prototype,constructor:ResponseExpectation};tr.model.um.UserExpectation.subTypes.register(ResponseExpectation,{stageTitle:'Response',colorId:tr.b.ColorScheme.getColorIdForReservedName('rail_response')});return{ResponseExpectation:ResponseExpectation};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./user_expectation.js":172}],171:[function(require,module,exports){(function(global){"use strict";require("./user_expectation.js");'use strict';global.tr.exportTo('tr.model.um',function(){function StartupExpectation(parentModel,start,duration){tr.model.um.UserExpectation.call(this,parentModel,'',start,duration);}StartupExpectation.prototype={__proto__:tr.model.um.UserExpectation.prototype,constructor:StartupExpectation};tr.model.um.UserExpectation.subTypes.register(StartupExpectation,{stageTitle:'Startup',colorId:tr.b.ColorScheme.getColorIdForReservedName('startup')});return{StartupExpectation:StartupExpectation};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./user_expectation.js":172}],172:[function(require,module,exports){(function(global){"use strict";require("../../base/range_utils.js");require("../../base/statistics.js");require("../../base/unit.js");require("../compound_event_selection_state.js");require("../event_set.js");require("../timed_event.js");'use strict';global.tr.exportTo('tr.model.um',function(){var CompoundEventSelectionState=tr.model.CompoundEventSelectionState;function UserExpectation(parentModel,initiatorTitle,start,duration){tr.model.TimedEvent.call(this,start);this.associatedEvents=new tr.model.EventSet();this.duration=duration;this.initiatorTitle_=initiatorTitle;this.parentModel=parentModel;this.typeInfo_=undefined;this.sourceEvents=new tr.model.EventSet();}UserExpectation.prototype={__proto__:tr.model.TimedEvent.prototype,computeCompoundEvenSelectionState:function(selection){var cess=CompoundEventSelectionState.NOT_SELECTED;if(selection.contains(this))cess|=CompoundEventSelectionState.EVENT_SELECTED;if(this.associatedEvents.intersectionIsEmpty(selection))return cess;var allContained=this.associatedEvents.every(function(event){return selection.contains(event);});if(allContained)cess|=CompoundEventSelectionState.ALL_ASSOCIATED_EVENTS_SELECTED;else cess|=CompoundEventSelectionState.SOME_ASSOCIATED_EVENTS_SELECTED;return cess;},get associatedSamples(){var samples=new tr.model.EventSet();this.associatedEvents.forEach(function(event){if(event instanceof tr.model.ThreadSlice)samples.addEventSet(event.overlappingSamples);});return samples;},get userFriendlyName(){return this.title+' User Expectation at '+tr.b.Unit.byName.timeStampInMs.format(this.start);},get stableId(){return'UserExpectation.'+this.guid;},get typeInfo(){if(!this.typeInfo_){this.typeInfo_=UserExpectation.subTypes.findTypeInfo(this.constructor);}if(!this.typeInfo_)throw new Error('Unregistered UserExpectation');return this.typeInfo_;},get colorId(){return this.typeInfo.metadata.colorId;},get stageTitle(){return this.typeInfo.metadata.stageTitle;},get initiatorTitle(){return this.initiatorTitle_;},get title(){if(!this.initiatorTitle)return this.stageTitle;return this.initiatorTitle+' '+this.stageTitle;},get totalCpuMs(){var cpuMs=0;this.associatedEvents.forEach(function(event){if(event.cpuSelfTime)cpuMs+=event.cpuSelfTime;});return cpuMs;}};var subTypes={};var options=new tr.b.ExtensionRegistryOptions(tr.b.BASIC_REGISTRY_MODE);tr.b.decorateExtensionRegistry(subTypes,options);subTypes.addEventListener('will-register',function(e){var metadata=e.typeInfo.metadata;if(metadata.stageTitle===undefined){throw new Error('Registered UserExpectations must provide '+'stageTitle');}if(metadata.colorId===undefined){throw new Error('Registered UserExpectations must provide '+'colorId');}});tr.model.EventRegistry.register(UserExpectation,{name:'userExpectation',pluralName:'userExpectations',subTypes:subTypes});return{UserExpectation:UserExpectation};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../../base/range_utils.js":54,"../../base/statistics.js":59,"../../base/unit.js":63,"../compound_event_selection_state.js":113,"../event_set.js":126,"../timed_event.js":166}],173:[function(require,module,exports){(function(global){"use strict";require("../event_container.js");'use strict';global.tr.exportTo('tr.model.um',function(){function UserModel(parentModel){tr.model.EventContainer.call(this);this.parentModel_=parentModel;this.expectations_=new tr.model.EventSet();}UserModel.prototype={__proto__:tr.model.EventContainer.prototype,get stableId(){return'UserModel';},get parentModel(){return this.parentModel_;},sortExpectations:function(){this.expectations_.sortEvents((x,y)=>x.start-y.start);},get expectations(){return this.expectations_;},shiftTimestampsForward:function(amount){},addCategoriesToDict:function(categoriesDict){},childEvents:function*(){yield*this.expectations;},childEventContainers:function*(){},updateBounds:function(){this.bounds.reset();this.expectations.forEach(function(expectation){expectation.addBoundsToRange(this.bounds);},this);}};return{UserModel:UserModel};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../event_container.js":123}],174:[function(require,module,exports){(function(global){"use strict";require("../base/base.js");'use strict';global.tr.exportTo('tr.model',function(){function VMRegion(startAddress,sizeInBytes,protectionFlags,mappedFile,byteStats){this.startAddress=startAddress;this.sizeInBytes=sizeInBytes;this.protectionFlags=protectionFlags;this.mappedFile=mappedFile||'';this.byteStats=byteStats||{};};VMRegion.PROTECTION_FLAG_READ=4;VMRegion.PROTECTION_FLAG_WRITE=2;VMRegion.PROTECTION_FLAG_EXECUTE=1;VMRegion.PROTECTION_FLAG_MAYSHARE=128;VMRegion.prototype={get uniqueIdWithinProcess(){return this.mappedFile+'#'+this.startAddress;},get protectionFlagsToString(){if(this.protectionFlags===undefined)return undefined;return(this.protectionFlags&VMRegion.PROTECTION_FLAG_READ?'r':'-')+(this.protectionFlags&VMRegion.PROTECTION_FLAG_WRITE?'w':'-')+(this.protectionFlags&VMRegion.PROTECTION_FLAG_EXECUTE?'x':'-')+(this.protectionFlags&VMRegion.PROTECTION_FLAG_MAYSHARE?'s':'p');}};VMRegion.fromDict=function(dict){return new VMRegion(dict.startAddress,dict.sizeInBytes,dict.protectionFlags,dict.mappedFile,dict.byteStats);};function VMRegionClassificationNode(opt_rule){this.rule_=opt_rule||VMRegionClassificationNode.CLASSIFICATION_RULES;this.hasRegions=false;this.sizeInBytes=undefined;this.byteStats={};this.children_=undefined;this.regions_=[];}VMRegionClassificationNode.CLASSIFICATION_RULES={name:'Total',children:[{name:'Android',file:/^\/dev\/ashmem(?!\/libc malloc)/,children:[{name:'Java runtime',file:/^\/dev\/ashmem\/dalvik-/,children:[{name:'Spaces',file:/\/dalvik-(alloc|main|large object|non moving|zygote) space/,children:[{name:'Normal',file:/\/dalvik-(alloc|main)/},{name:'Large',file:/\/dalvik-large object/},{name:'Zygote',file:/\/dalvik-zygote/},{name:'Non-moving',file:/\/dalvik-non moving/}]},{name:'Linear Alloc',file:/\/dalvik-LinearAlloc/},{name:'Indirect Reference Table',file:/\/dalvik-indirect.ref/},{name:'Cache',file:/\/dalvik-jit-code-cache/},{name:'Accounting'}]},{name:'Cursor',file:/\/CursorWindow/},{name:'Ashmem'}]},{name:'Native heap',file:/^((\[heap\])|(\[anon:)|(\/dev\/ashmem\/libc malloc)|(\[discounted tracing overhead\])|$)/},{name:'Stack',file:/^\[stack/},{name:'Files',file:/\.((((jar)|(apk)|(ttf)|(odex)|(oat)|(art))$)|(dex)|(so))/,children:[{name:'so',file:/\.so/},{name:'jar',file:/\.jar$/},{name:'apk',file:/\.apk$/},{name:'ttf',file:/\.ttf$/},{name:'dex',file:/\.((dex)|(odex$))/},{name:'oat',file:/\.oat$/},{name:'art',file:/\.art$/}]},{name:'Devices',file:/(^\/dev\/)|(anon_inode:dmabuf)/,children:[{name:'GPU',file:/\/((nv)|(mali)|(kgsl))/},{name:'DMA',file:/anon_inode:dmabuf/}]}]};VMRegionClassificationNode.OTHER_RULE={name:'Other'};VMRegionClassificationNode.fromRegions=function(regions,opt_rules){var tree=new VMRegionClassificationNode(opt_rules);tree.regions_=regions;for(var i=0;i<regions.length;i++)tree.addStatsFromRegion_(regions[i]);return tree;};VMRegionClassificationNode.prototype={get title(){return this.rule_.name;},get children(){if(this.isLeafNode)return undefined;if(this.children_===undefined)this.buildTree_();return this.children_;},get regions(){if(!this.isLeafNode){return undefined;}return this.regions_;},get allRegionsForTesting(){if(this.regions_!==undefined){if(this.children_!==undefined){throw new Error('Internal error: a VM region classification node '+'cannot have both regions and children');}return this.regions_;}var regions=[];this.children_.forEach(function(childNode){regions=regions.concat(childNode.allRegionsForTesting);});return regions;},get isLeafNode(){var children=this.rule_.children;return children===undefined||children.length===0;},addRegion:function(region){this.addRegionRecursively_(region,true);},someRegion:function(fn,opt_this){if(this.regions_!==undefined){return this.regions_.some(fn,opt_this);}return this.children_.some(function(childNode){return childNode.someRegion(fn,opt_this);});},addRegionRecursively_:function(region,addStatsToThisNode){if(addStatsToThisNode)this.addStatsFromRegion_(region);if(this.regions_!==undefined){if(this.children_!==undefined){throw new Error('Internal error: a VM region classification node '+'cannot have both regions and children');}this.regions_.push(region);return;}function regionRowMatchesChildNide(child){var fileRegExp=child.rule_.file;if(fileRegExp===undefined)return true;return fileRegExp.test(region.mappedFile);}var matchedChild=tr.b.findFirstInArray(this.children_,regionRowMatchesChildNide);if(matchedChild===undefined){if(this.children_.length!==this.rule_.children.length)throw new Error('Internal error');matchedChild=new VMRegionClassificationNode(VMRegionClassificationNode.OTHER_RULE);this.children_.push(matchedChild);}matchedChild.addRegionRecursively_(region,true);},buildTree_:function(){var cachedRegions=this.regions_;this.regions_=undefined;this.buildChildNodesRecursively_();for(var i=0;i<cachedRegions.length;i++){this.addRegionRecursively_(cachedRegions[i],false);}},buildChildNodesRecursively_:function(){if(this.children_!==undefined){throw new Error('Internal error: Classification node already has children');}if(this.regions_!==undefined&&this.regions_.length!==0){throw new Error('Internal error: Classification node should have no regions');}if(this.isLeafNode)return;this.regions_=undefined;this.children_=this.rule_.children.map(function(childRule){var child=new VMRegionClassificationNode(childRule);child.buildChildNodesRecursively_();return child;});},addStatsFromRegion_:function(region){this.hasRegions=true;var regionSizeInBytes=region.sizeInBytes;if(regionSizeInBytes!==undefined)this.sizeInBytes=(this.sizeInBytes||0)+regionSizeInBytes;var thisByteStats=this.byteStats;var regionByteStats=region.byteStats;for(var byteStatName in regionByteStats){var regionByteStatValue=regionByteStats[byteStatName];if(regionByteStatValue===undefined)continue;thisByteStats[byteStatName]=(thisByteStats[byteStatName]||0)+regionByteStatValue;}}};return{VMRegion:VMRegion,VMRegionClassificationNode:VMRegionClassificationNode};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/base.js":34}],175:[function(require,module,exports){(function(global){"use strict";require("./annotation.js");require("../ui/annotations/x_marker_annotation_view.js");'use strict';global.tr.exportTo('tr.model',function(){function XMarkerAnnotation(timestamp){tr.model.Annotation.apply(this,arguments);this.timestamp=timestamp;this.strokeStyle='rgba(0, 0, 255, 0.5)';}XMarkerAnnotation.fromDict=function(dict){return new XMarkerAnnotation(dict.args.timestamp);};XMarkerAnnotation.prototype={__proto__:tr.model.Annotation.prototype,toDict:function(){return{typeName:'xmarker',args:{timestamp:this.timestamp}};},createView_:function(viewport){return new tr.ui.annotations.XMarkerAnnotationView(viewport,this);}};tr.model.Annotation.register(XMarkerAnnotation,{typeName:'xmarker'});return{XMarkerAnnotation:XMarkerAnnotation};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../ui/annotations/x_marker_annotation_view.js":179,"./annotation.js":108}],176:[function(require,module,exports){(function(global){"use strict";require("../../base/base.js");'use strict';global.tr.exportTo('tr.ui.annotations',function(){function AnnotationView(viewport,annotation){}AnnotationView.prototype={draw:function(ctx){throw new Error('Not implemented');}};return{AnnotationView:AnnotationView};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../../base/base.js":34}],177:[function(require,module,exports){(function(global){"use strict";require("./annotation_view.js");'use strict';global.tr.exportTo('tr.ui.annotations',function(){function CommentBoxAnnotationView(viewport,annotation){this.viewport_=viewport;this.annotation_=annotation;this.textArea_=undefined;this.styleWidth=250;this.styleHeight=50;this.fontSize=10;this.rightOffset=50;this.topOffset=25;}CommentBoxAnnotationView.prototype={__proto__:tr.ui.annotations.AnnotationView.prototype,removeTextArea:function(){Polymer.dom(Polymer.dom(this.textArea_).parentNode).removeChild(this.textArea_);},draw:function(ctx){var coords=this.annotation_.location.toViewCoordinates(this.viewport_);if(coords.viewX<0){if(this.textArea_)this.textArea_.style.visibility='hidden';return;}if(!this.textArea_){this.textArea_=document.createElement('textarea');this.textArea_.style.position='absolute';this.textArea_.readOnly=true;this.textArea_.value=this.annotation_.text;this.textArea_.style.zIndex=1;Polymer.dom(Polymer.dom(ctx.canvas).parentNode).appendChild(this.textArea_);}this.textArea_.style.width=this.styleWidth+'px';this.textArea_.style.height=this.styleHeight+'px';this.textArea_.style.fontSize=this.fontSize+'px';this.textArea_.style.visibility='visible';this.textArea_.style.left=coords.viewX+ctx.canvas.getBoundingClientRect().left+this.rightOffset+'px';this.textArea_.style.top=coords.viewY-ctx.canvas.getBoundingClientRect().top-this.topOffset+'px';ctx.strokeStyle='rgb(0, 0, 0)';ctx.lineWidth=2;ctx.beginPath();tr.ui.b.drawLine(ctx,coords.viewX,coords.viewY-ctx.canvas.getBoundingClientRect().top,coords.viewX+this.rightOffset,coords.viewY-this.topOffset-ctx.canvas.getBoundingClientRect().top);ctx.stroke();}};return{CommentBoxAnnotationView:CommentBoxAnnotationView};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./annotation_view.js":176}],178:[function(require,module,exports){(function(global){"use strict";require("./annotation_view.js");'use strict';global.tr.exportTo('tr.ui.annotations',function(){function RectAnnotationView(viewport,annotation){this.viewport_=viewport;this.annotation_=annotation;}RectAnnotationView.prototype={__proto__:tr.ui.annotations.AnnotationView.prototype,draw:function(ctx){var dt=this.viewport_.currentDisplayTransform;var startCoords=this.annotation_.startLocation.toViewCoordinates(this.viewport_);var endCoords=this.annotation_.endLocation.toViewCoordinates(this.viewport_);var startY=startCoords.viewY-ctx.canvas.getBoundingClientRect().top;var sizeY=endCoords.viewY-startCoords.viewY;if(startY+sizeY<0){startY=sizeY;}else if(startY<0){startY=0;}ctx.fillStyle=this.annotation_.fillStyle;ctx.fillRect(startCoords.viewX,startY,endCoords.viewX-startCoords.viewX,sizeY);}};return{RectAnnotationView:RectAnnotationView};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./annotation_view.js":176}],179:[function(require,module,exports){(function(global){"use strict";require("./annotation_view.js");'use strict';global.tr.exportTo('tr.ui.annotations',function(){function XMarkerAnnotationView(viewport,annotation){this.viewport_=viewport;this.annotation_=annotation;}XMarkerAnnotationView.prototype={__proto__:tr.ui.annotations.AnnotationView.prototype,draw:function(ctx){var dt=this.viewport_.currentDisplayTransform;var viewX=dt.xWorldToView(this.annotation_.timestamp);ctx.beginPath();tr.ui.b.drawLine(ctx,viewX,0,viewX,ctx.canvas.height);ctx.strokeStyle=this.annotation_.strokeStyle;ctx.stroke();}};return{XMarkerAnnotationView:XMarkerAnnotationView};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./annotation_view.js":176}],180:[function(require,module,exports){(function(global){"use strict";require("../../base/event.js");require("../../base/utils.js");require("./ui.js");require("./utils.js");'use strict';global.tr.exportTo('tr.ui.b',function(){if(tr.isHeadless)return{};return;var Overlay=tr.ui.b.define('overlay');Overlay.prototype={__proto__:HTMLDivElement.prototype,decorate:function(){Polymer.dom(this).classList.add('overlay');this.parentEl_=this.ownerDocument.body;this.visible_=false;this.userCanClose_=true;this.onKeyDown_=this.onKeyDown_.bind(this);this.onClick_=this.onClick_.bind(this);this.onFocusIn_=this.onFocusIn_.bind(this);this.onDocumentClick_=this.onDocumentClick_.bind(this);this.onClose_=this.onClose_.bind(this);this.addEventListener('visible-change',tr.ui.b.Overlay.prototype.onVisibleChange_.bind(this),true);var createShadowRoot=this.createShadowRoot||this.webkitCreateShadowRoot;this.shadow_=createShadowRoot.call(this);Polymer.dom(this.shadow_).appendChild(tr.ui.b.instantiateTemplate('#overlay-template',THIS_DOC));this.closeBtn_=Polymer.dom(this.shadow_).querySelector('close-button');this.closeBtn_.addEventListener('click',this.onClose_);Polymer.dom(this.shadow_).querySelector('overlay-frame').addEventListener('click',this.onClick_);this.observer_=new WebKitMutationObserver(this.didButtonBarMutate_.bind(this));this.observer_.observe(Polymer.dom(this.shadow_).querySelector('button-bar'),{childList:true});Object.defineProperty(this,'title',{get:function(){return Polymer.dom(Polymer.dom(this.shadow_).querySelector('title')).textContent;},set:function(title){Polymer.dom(Polymer.dom(this.shadow_).querySelector('title')).textContent=title;}});},set userCanClose(userCanClose){this.userCanClose_=userCanClose;this.closeBtn_.style.display=userCanClose?'block':'none';},get buttons(){return Polymer.dom(this.shadow_).querySelector('button-bar');},get visible(){return this.visible_;},set visible(newValue){if(this.visible_===newValue)return;this.visible_=newValue;var e=new tr.b.Event('visible-change');this.dispatchEvent(e);},onVisibleChange_:function(){this.visible_?this.show_():this.hide_();},show_:function(){Polymer.dom(this.parentEl_).appendChild(this);if(this.userCanClose_){this.addEventListener('keydown',this.onKeyDown_.bind(this));this.addEventListener('click',this.onDocumentClick_.bind(this));this.closeBtn_.addEventListener('click',this.onClose_);}this.parentEl_.addEventListener('focusin',this.onFocusIn_);this.tabIndex=0;var focusEl=undefined;var elList=Polymer.dom(this).querySelectorAll('button, input, list, select, a');if(elList.length>0){if(elList[0]===this.closeBtn_){if(elList.length>1)focusEl=elList[1];}else{focusEl=elList[0];}}if(focusEl===undefined)focusEl=this;focusEl.focus();},hide_:function(){Polymer.dom(this.parentEl_).removeChild(this);this.parentEl_.removeEventListener('focusin',this.onFocusIn_);if(this.closeBtn_)this.closeBtn_.removeEventListener('click',this.onClose_);document.removeEventListener('keydown',this.onKeyDown_);document.removeEventListener('click',this.onDocumentClick_);},onClose_:function(e){this.visible=false;if(e.type!='keydown'||e.type==='keydown'&&e.keyCode===27)e.stopPropagation();e.preventDefault();tr.b.dispatchSimpleEvent(this,'closeclick');},onFocusIn_:function(e){if(e.target===this)return;window.setTimeout(function(){this.focus();},0);e.preventDefault();e.stopPropagation();},didButtonBarMutate_:function(e){var hasButtons=this.buttons.children.length>0;if(hasButtons){Polymer.dom(this.shadow_).querySelector('button-bar').style.display=undefined;}else{Polymer.dom(this.shadow_).querySelector('button-bar').style.display='none';}},onKeyDown_:function(e){if(e.keyCode===9&&e.shiftKey&&e.target===this){e.preventDefault();return;}if(e.keyCode!==27)return;this.onClose_(e);},onClick_:function(e){e.stopPropagation();},onDocumentClick_:function(e){if(!this.userCanClose_)return;this.onClose_(e);}};Overlay.showError=function(msg,opt_err){var o=new Overlay();o.title='Error';Polymer.dom(o).textContent=msg;if(opt_err){var e=tr.b.normalizeException(opt_err);var stackDiv=document.createElement('pre');Polymer.dom(stackDiv).textContent=e.stack;stackDiv.style.paddingLeft='8px';stackDiv.style.margin=0;Polymer.dom(o).appendChild(stackDiv);}var b=document.createElement('button');Polymer.dom(b).textContent='OK';b.addEventListener('click',function(){o.visible=false;});Polymer.dom(o.buttons).appendChild(b);o.visible=true;return o;};return{Overlay:Overlay};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../../base/event.js":39,"../../base/utils.js":65,"./ui.js":181,"./utils.js":182}],181:[function(require,module,exports){(function(global){"use strict";require("../../base/base.js");'use strict';global.tr.exportTo('tr.ui.b',function(){function decorate(source,constr){var elements;if(typeof source=='string')elements=Polymer.dom(tr.doc).querySelectorAll(source);else elements=[source];for(var i=0,el;el=elements[i];i++){if(!(el instanceof constr))constr.decorate(el);}}function define(className,opt_parentConstructor,opt_tagNS){if(typeof className=='function'){throw new Error('Passing functions as className is deprecated. Please '+'use (className, opt_parentConstructor) to subclass');}var className=className.toLowerCase();if(opt_parentConstructor&&!opt_parentConstructor.tagName)throw new Error('opt_parentConstructor was not '+'created by tr.ui.b.define');var tagName=className;var tagNS=undefined;if(opt_parentConstructor){if(opt_tagNS)throw new Error('Must not specify tagNS if parentConstructor is given');var parent=opt_parentConstructor;while(parent&&parent.tagName){tagName=parent.tagName;tagNS=parent.tagNS;parent=parent.parentConstructor;}}else{tagNS=opt_tagNS;}function f(){if(opt_parentConstructor&&f.prototype.__proto__!=opt_parentConstructor.prototype){throw new Error(className+' prototye\'s __proto__ field is messed up. '+'It MUST be the prototype of '+opt_parentConstructor.tagName);}var el;if(tagNS===undefined)el=tr.doc.createElement(tagName);else el=tr.doc.createElementNS(tagNS,tagName);f.decorate.call(this,el,arguments);return el;}f.decorate=function(el){el.__proto__=f.prototype;el.decorate.apply(el,arguments[1]);el.constructor=f;};f.className=className;f.tagName=tagName;f.tagNS=tagNS;f.parentConstructor=opt_parentConstructor?opt_parentConstructor:undefined;f.toString=function(){if(!f.parentConstructor)return f.tagName;return f.parentConstructor.toString()+'::'+f.className;};return f;}function elementIsChildOf(el,potentialParent){if(el==potentialParent)return false;var cur=el;while(Polymer.dom(cur).parentNode){if(cur==potentialParent)return true;cur=Polymer.dom(cur).parentNode;}return false;};return{decorate:decorate,define:define,elementIsChildOf:elementIsChildOf};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../../base/base.js":34}],182:[function(require,module,exports){(function(global){"use strict";require("../../base/base.js");require("../../base/rect.js");'use strict';global.tr.exportTo('tr.ui.b',function(){function instantiateTemplate(selector,doc){doc=doc||document;var el=Polymer.dom(doc).querySelector(selector);if(!el)throw new Error('Element not found');return doc.importNode(el.content,true);}function windowRectForElement(element){var position=[element.offsetLeft,element.offsetTop];var size=[element.offsetWidth,element.offsetHeight];var node=element.offsetParent;while(node){position[0]+=node.offsetLeft;position[1]+=node.offsetTop;node=node.offsetParent;}return tr.b.Rect.fromXYWH(position[0],position[1],size[0],size[1]);}function scrollIntoViewIfNeeded(el){var pr=el.parentElement.getBoundingClientRect();var cr=el.getBoundingClientRect();if(cr.top<pr.top){el.scrollIntoView(true);}else if(cr.bottom>pr.bottom){el.scrollIntoView(false);}}function extractUrlString(url){var extracted=url.replace(/url\((.*)\)/,'$1');extracted=extracted.replace(/\"(.*)\"/,'$1');return extracted;}function toThreeDigitLocaleString(value){return value.toLocaleString(undefined,{minimumFractionDigits:3,maximumFractionDigits:3});}function isUnknownElementName(name){return document.createElement(name)instanceof HTMLUnknownElement;}return{isUnknownElementName:isUnknownElementName,toThreeDigitLocaleString:toThreeDigitLocaleString,instantiateTemplate:instantiateTemplate,windowRectForElement:windowRectForElement,scrollIntoViewIfNeeded:scrollIntoViewIfNeeded,extractUrlString:extractUrlString};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../../base/base.js":34,"../../base/rect.js":55}],183:[function(require,module,exports){(function(global){"use strict";var _slicedToArray=function(){function sliceIterator(arr,i){var _arr=[];var _n=true;var _d=false;var _e=undefined;try{for(var _i=arr[Symbol.iterator](),_s;!(_n=(_s=_i.next()).done);_n=true){_arr.push(_s.value);if(i&&_arr.length===i)break;}}catch(err){_d=true;_e=err;}finally{try{if(!_n&&_i["return"])_i["return"]();}finally{if(_d)throw _e;}}return _arr;}return function(arr,i){if(Array.isArray(arr)){return arr;}else if(Symbol.iterator in Object(arr)){return sliceIterator(arr,i);}else{throw new TypeError("Invalid attempt to destructure non-iterable instance");}};}();require("./related_value_map.js");'use strict';global.tr.exportTo('tr.v.d',function(){class Breakdown extends tr.v.d.Diagnostic{constructor(){super();this.values_=new Map();this.colorScheme=undefined;}set(name,value){if(typeof name!=='string'||typeof value!=='number'){throw new Error('Breakdown maps from strings to numbers');}this.values_.set(name,value);}get(name){return this.values_.get(name)||0;}*[Symbol.iterator](){for(var pair of this.values_)yield pair;}asDictInto_(d){d.values={};for(var _ref of this){var _ref2=_slicedToArray(_ref,2);var name=_ref2[0];var value=_ref2[1];d.values[name]=value;}if(this.colorScheme)d.colorScheme=this.colorScheme;}static fromDict(d){var breakdown=new Breakdown();tr.b.iterItems(d.values,(name,value)=>breakdown.set(name,value));if(d.colorScheme)breakdown.colorScheme=d.colorScheme;return breakdown;}}tr.v.d.Diagnostic.register(Breakdown,{elementName:'tr-v-ui-breakdown-span'});return{Breakdown:Breakdown};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./related_value_map.js":191}],184:[function(require,module,exports){(function(global){"use strict";require("../../base/extension_registry.js");'use strict';global.tr.exportTo('tr.v.d',function(){class Diagnostic{asDict(){var result={type:this.constructor.name};this.asDictInto_(result);return result;}asDictInto_(d){throw new Error('Abstract virtual method');}static fromDict(d){var typeInfo=Diagnostic.findTypeInfoWithName(d.type);if(!typeInfo)throw new Error('Unrecognized diagnostic type: '+d.type);return typeInfo.constructor.fromDict(d);}}var options=new tr.b.ExtensionRegistryOptions(tr.b.BASIC_REGISTRY_MODE);options.defaultMetadata={};options.mandatoryBaseClass=Diagnostic;tr.b.decorateExtensionRegistry(Diagnostic,options);Diagnostic.addEventListener('will-register',function(e){var constructor=e.typeInfo.constructor;if(!(constructor.fromDict instanceof Function)||constructor.fromDict===Diagnostic.fromDict||constructor.fromDict.length!==1){throw new Error('Diagnostics must define fromDict(d)');}});return{Diagnostic:Diagnostic};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../../base/extension_registry.js":41}],185:[function(require,module,exports){(function(global){"use strict";var _slicedToArray=function(){function sliceIterator(arr,i){var _arr=[];var _n=true;var _d=false;var _e=undefined;try{for(var _i=arr[Symbol.iterator](),_s;!(_n=(_s=_i.next()).done);_n=true){_arr.push(_s.value);if(i&&_arr.length===i)break;}}catch(err){_d=true;_e=err;}finally{try{if(!_n&&_i["return"])_i["return"]();}finally{if(_d)throw _e;}}return _arr;}return function(arr,i){if(Array.isArray(arr)){return arr;}else if(Symbol.iterator in Object(arr)){return sliceIterator(arr,i);}else{throw new TypeError("Invalid attempt to destructure non-iterable instance");}};}();require("./breakdown.js");require("./generic.js");require("./iteration_info.js");require("./related_event_set.js");require("./related_histogram_breakdown.js");require("./related_value_map.js");require("./related_value_set.js");require("./scalar.js");'use strict';global.tr.exportTo('tr.v.d',function(){class DiagnosticMap extends Map{set(name,diagnostic){if(typeof name!=='string')throw new Error('name must be string, not '+name);if(!(diagnostic instanceof tr.v.d.Diagnostic))throw new Error('Must be instanceof Diagnostic: '+diagnostic);Map.prototype.set.call(this,name,diagnostic);}addDicts(dict){tr.b.iterItems(dict,function(name,diagnosticDict){this.set(name,tr.v.d.Diagnostic.fromDict(diagnosticDict));},this);}asDict(){var dict={};for(var _ref of this){var _ref2=_slicedToArray(_ref,2);var name=_ref2[0];var diagnostic=_ref2[1];dict[name]=diagnostic.asDict();}return dict;}static fromDict(d){var diagnostics=new DiagnosticMap();diagnostics.addDicts(d);return diagnostics;}static fromObject(obj){var diagnostics=new DiagnosticMap();tr.b.iterItems(obj,function(name,diagnostic){diagnostics.set(name,diagnostic);});return diagnostics;}}return{DiagnosticMap:DiagnosticMap};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./breakdown.js":183,"./generic.js":187,"./iteration_info.js":188,"./related_event_set.js":189,"./related_histogram_breakdown.js":190,"./related_value_map.js":191,"./related_value_set.js":192,"./scalar.js":193}],186:[function(require,module,exports){(function(global){"use strict";require("../../base/guid.js");'use strict';global.tr.exportTo('tr.v.d',function(){class EventRef{constructor(event){this.stableId=event.stableId;this.title=event.title;this.start=event.start;this.duration=event.duration;this.end=this.start+this.duration;this.guid=tr.b.GUID.allocateSimple();}}return{EventRef:EventRef};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../../base/guid.js":45}],187:[function(require,module,exports){(function(global){"use strict";require("./diagnostic.js");'use strict';global.tr.exportTo('tr.v.d',function(){class Generic extends tr.v.d.Diagnostic{constructor(value){super();this.value=value;}asDictInto_(d){d.value=this.value;}static fromDict(d){return new Generic(d.value);}}tr.v.d.Diagnostic.register(Generic,{elementName:'tr-v-ui-generic-diagnostic-span'});return{Generic:Generic};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./diagnostic.js":184}],188:[function(require,module,exports){(function(global){"use strict";require("../../base/utils.js");require("./diagnostic.js");'use strict';global.tr.exportTo('tr.v.d',function(){class IterationInfo extends tr.v.d.Diagnostic{constructor(opt_info){super();this.benchmarkName_='';this.benchmarkStart_=undefined;this.label_='';this.osVersion_='';this.productVersion_='';this.storyDisplayName_='';this.storyGroupingKeys_={};this.storyRepeatCounter_=undefined;this.storyUrl_='';this.storysetRepeatCounter_=undefined;if(opt_info)this.addInfo(opt_info);}addInfo(info){if(info.benchmarkName)this.benchmarkName_=info.benchmarkName;if(info.benchmarkStartMs)this.benchmarkStart_=new Date(info.benchmarkStartMs);if(info.label)this.label_=info.label;if(info.storyDisplayName)this.storyDisplayName_=info.storyDisplayName;if(info.storyGroupingKeys)this.storyGroupingKeys_=info.storyGroupingKeys;if(info.storyRepeatCounter!==undefined)this.storyRepeatCounter_=info.storyRepeatCounter;if(info.storyUrl)this.storyUrl_=info.storyUrl;if(info.storysetRepeatCounter!==undefined)this.storysetRepeatCounter_=info.storysetRepeatCounter;if(info['os-version'])this.osVersion_=info['os-version'];if(info['product-version'])this.productVersion_=info['product-version'];}addToValue(value){value.diagnostics.set(IterationInfo.NAME,this);}static getFromValue(value){return value.diagnostics.get(IterationInfo.NAME);}asDictInto_(d){d.benchmarkName=this.benchmarkName;if(this.benchmarkStart)d.benchmarkStartMs=this.benchmarkStart.getTime();d.label=this.label;d.storyDisplayName=this.storyDisplayName;d.storyGroupingKeys=this.storyGroupingKeys;d.storyRepeatCounter=this.storyRepeatCounter;d.storyUrl=this.storyUrl;d.storysetRepeatCounter=this.storysetRepeatCounter;d['os-version']=this.osVersion;d['product-version']=this.productVersion;}static fromDict(d){var info=new IterationInfo();info.addInfo(d);return info;}get displayLabel(){if(this.label)return this.label;return this.benchmarkName+' '+this.benchmarkStartString;}get osVersion(){return this.osVersion_;}get productVersion(){return this.productVersion_;}get benchmarkName(){return this.benchmarkName_;}get label(){return this.label_;}get storyGroupingKeys(){return this.storyGroupingKeys_;}get storyDisplayName(){return this.storyDisplayName_;}get storyUrl(){return this.storyUrl_;}get storyRepeatCounter(){return this.storyRepeatCounter_;}get storyRepeatCounterLabel(){return'story repeat '+this.storyRepeatCounter;}get storysetRepeatCounter(){return this.storysetRepeatCounter_;}get storysetRepeatCounterLabel(){return'storyset repeat '+this.storysetRepeatCounter;}get benchmarkStart(){return this.benchmarkStart_;}get benchmarkStartString(){if(this.benchmarkStart_===undefined)return'';return tr.b.formatDate(this.benchmarkStart);}static getField(value,fieldName,defaultValue){var iteration=tr.v.d.IterationInfo.getFromValue(value);if(!(iteration instanceof tr.v.d.IterationInfo)||!iteration[fieldName]){return defaultValue;}return iteration[fieldName];}static getStoryGroupingKeyLabel(value,storyGroupingKey){var iteration=tr.v.d.IterationInfo.getFromValue(value);if(!(iteration instanceof tr.v.d.IterationInfo))return storyGroupingKey+': undefined';return storyGroupingKey+': '+iteration.storyGroupingKeys[storyGroupingKey];}}IterationInfo.NAME='iteration';tr.v.d.Diagnostic.register(IterationInfo,{elementName:'tr-v-ui-iteration-info-span'});return{IterationInfo:IterationInfo};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../../base/utils.js":65,"./diagnostic.js":184}],189:[function(require,module,exports){(function(global){"use strict";var _slicedToArray=function(){function sliceIterator(arr,i){var _arr=[];var _n=true;var _d=false;var _e=undefined;try{for(var _i=arr[Symbol.iterator](),_s;!(_n=(_s=_i.next()).done);_n=true){_arr.push(_s.value);if(i&&_arr.length===i)break;}}catch(err){_d=true;_e=err;}finally{try{if(!_n&&_i["return"])_i["return"]();}finally{if(_d)throw _e;}}return _arr;}return function(arr,i){if(Array.isArray(arr)){return arr;}else if(Symbol.iterator in Object(arr)){return sliceIterator(arr,i);}else{throw new TypeError("Invalid attempt to destructure non-iterable instance");}};}();require("../../model/event_set.js");require("./diagnostic.js");require("./event_ref.js");'use strict';global.tr.exportTo('tr.v.d',function(){class RelatedEventSet extends tr.v.d.Diagnostic{constructor(opt_events){super();this.eventsByStableId_=new Map();if(opt_events){if(opt_events instanceof tr.model.EventSet||opt_events instanceof Array){for(var event of opt_events)this.add(event);}else{this.add(opt_events);}}}add(event){this.eventsByStableId_.set(event.stableId,event);}has(event){return this.eventsByStableId_.has(event.stableId);}get length(){return this.eventsByStableId_.size;}*[Symbol.iterator](){for(var _ref of this.eventsByStableId_){var _ref2=_slicedToArray(_ref,2);var stableId=_ref2[0];var event=_ref2[1];yield event;}}resolve(model,opt_required){for(var _ref3 of this.eventsByStableId_){var _ref4=_slicedToArray(_ref3,2);var stableId=_ref4[0];var event=_ref4[1];if(!(event instanceof tr.v.d.EventRef))continue;event=model.getEventByStableId(stableId);if(event instanceof tr.model.Event)this.eventsByStableId_.set(stableId,event);else if(opt_required)throw new Error('Unable to find Event '+stableId);}}asDictInto_(d){d.events=[];for(var event of this){d.events.push({stableId:event.stableId,title:event.title,start:event.start,duration:event.duration});}}static fromDict(d){return new RelatedEventSet(d.events.map(event=>new tr.v.d.EventRef(event)));}}tr.v.d.Diagnostic.register(RelatedEventSet,{elementName:'tr-v-ui-related-event-set-span'});return{RelatedEventSet:RelatedEventSet};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../../model/event_set.js":126,"./diagnostic.js":184,"./event_ref.js":186}],190:[function(require,module,exports){(function(global){"use strict";require("./related_value_map.js");'use strict';global.tr.exportTo('tr.v.d',function(){var COLOR_SCHEME_CHROME_USER_FRIENDLY_CATEGORY_DRIVER='ChromeUserFriendlyCategory';class RelatedHistogramBreakdown extends tr.v.d.RelatedValueMap{constructor(){super();this.colorScheme=undefined;}set(name,value){if(!(value instanceof tr.v.d.ValueRef)){if(!(value instanceof tr.v.Histogram)){throw new Error('RelatedHistogramBreakdown can only contain Histograms');}if(value.name.indexOf(name)!==value.name.length-name.length){throw new Error('RelatedHistogramBreakdown name must be a suffix of value.name');}if(this.length>0&&value.unit!==tr.b.getFirstElement(this)[1].unit){throw new Error('Units mismatch',tr.b.getFirstElement(this)[1].unit,value.unit);}}tr.v.d.RelatedValueMap.prototype.set.call(this,name,value);}asDictInto_(d){tr.v.d.RelatedValueMap.prototype.asDictInto_.call(this,d);if(this.colorScheme)d.colorScheme=this.colorScheme;}static fromDict(d){var diagnostic=new RelatedHistogramBreakdown();tr.b.iterItems(d.values,function(name,guid){diagnostic.set(name,new tr.v.d.ValueRef(guid));});if(d.colorScheme)diagnostic.colorScheme=d.colorScheme;return diagnostic;}static buildFromEvents(values,namePrefix,events,categoryForEvent,unit,opt_sampleForEvent,opt_binBoundaries,opt_this){var sampleForEvent=opt_sampleForEvent||(event=>event.cpuSelfTime);var diagnostic=new RelatedHistogramBreakdown();for(var event of events){var sample=sampleForEvent.call(opt_this,event);if(sample===undefined)continue;var eventCategory=categoryForEvent.call(opt_this,event);var value=diagnostic.get(eventCategory);if(value===undefined){value=new tr.v.Histogram(namePrefix+eventCategory,unit,opt_binBoundaries);values.addHistogram(value);diagnostic.set(eventCategory,value);}value.addSample(sample,{relatedEvents:new tr.v.d.RelatedEventSet([event])});}return diagnostic;}}tr.v.d.Diagnostic.register(RelatedHistogramBreakdown,{elementName:'tr-v-ui-breakdown-span'});return{COLOR_SCHEME_CHROME_USER_FRIENDLY_CATEGORY_DRIVER:COLOR_SCHEME_CHROME_USER_FRIENDLY_CATEGORY_DRIVER,RelatedHistogramBreakdown:RelatedHistogramBreakdown};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./related_value_map.js":191}],191:[function(require,module,exports){(function(global){"use strict";var _slicedToArray=function(){function sliceIterator(arr,i){var _arr=[];var _n=true;var _d=false;var _e=undefined;try{for(var _i=arr[Symbol.iterator](),_s;!(_n=(_s=_i.next()).done);_n=true){_arr.push(_s.value);if(i&&_arr.length===i)break;}}catch(err){_d=true;_e=err;}finally{try{if(!_n&&_i["return"])_i["return"]();}finally{if(_d)throw _e;}}return _arr;}return function(arr,i){if(Array.isArray(arr)){return arr;}else if(Symbol.iterator in Object(arr)){return sliceIterator(arr,i);}else{throw new TypeError("Invalid attempt to destructure non-iterable instance");}};}();require("../../base/iteration_helpers.js");require("./diagnostic.js");require("./value_ref.js");'use strict';global.tr.exportTo('tr.v.d',function(){class RelatedValueMap extends tr.v.d.Diagnostic{constructor(){super();this.valuesByName_=new Map();}get(name){return this.valuesByName_.get(name);}set(name,value){if(!(value instanceof tr.v.Histogram)&&!(value instanceof tr.v.d.ValueRef))throw new Error('Must be instanceof Histogram or ValueRef: '+value);this.valuesByName_.set(name,value);}add(value){this.set(value.name,value);}get length(){return this.valuesByName_.size;}*[Symbol.iterator](){for(var pair of this.valuesByName_)yield pair;}resolve(valueSet,opt_required){for(var _ref of this){var _ref2=_slicedToArray(_ref,2);var name=_ref2[0];var value=_ref2[1];if(!(value instanceof tr.v.d.ValueRef))continue;var guid=value.guid;value=valueSet.lookup(guid);if(value instanceof tr.v.Histogram)this.valuesByName_.set(name,value);else if(opt_required)throw new Error('Unable to find Histogram '+guid);}}asDictInto_(d){d.values={};for(var _ref3 of this){var _ref4=_slicedToArray(_ref3,2);var name=_ref4[0];var value=_ref4[1];d.values[name]=value.guid;}}static fromDict(d){var map=new RelatedValueMap();tr.b.iterItems(d.values,function(name,guid){map.set(name,new tr.v.d.ValueRef(guid));});return map;}}tr.v.d.Diagnostic.register(RelatedValueMap,{elementName:'tr-v-ui-related-value-map-span'});return{RelatedValueMap:RelatedValueMap};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../../base/iteration_helpers.js":47,"./diagnostic.js":184,"./value_ref.js":194}],192:[function(require,module,exports){(function(global){"use strict";var _slicedToArray=function(){function sliceIterator(arr,i){var _arr=[];var _n=true;var _d=false;var _e=undefined;try{for(var _i=arr[Symbol.iterator](),_s;!(_n=(_s=_i.next()).done);_n=true){_arr.push(_s.value);if(i&&_arr.length===i)break;}}catch(err){_d=true;_e=err;}finally{try{if(!_n&&_i["return"])_i["return"]();}finally{if(_d)throw _e;}}return _arr;}return function(arr,i){if(Array.isArray(arr)){return arr;}else if(Symbol.iterator in Object(arr)){return sliceIterator(arr,i);}else{throw new TypeError("Invalid attempt to destructure non-iterable instance");}};}();require("../../base/iteration_helpers.js");require("./diagnostic.js");require("./value_ref.js");'use strict';global.tr.exportTo('tr.v.d',function(){class RelatedValueSet extends tr.v.d.Diagnostic{constructor(opt_values){super();this.valuesByGuid_=new Map();if(opt_values)for(var value of opt_values)this.add(value);}add(value){if(!(value instanceof tr.v.Histogram)&&!(value instanceof tr.v.d.ValueRef))throw new Error('Must be instanceof Histogram or ValueRef: '+value);if(this.valuesByGuid_.get(value.guid))throw new Error('Tried to add same value twice');this.valuesByGuid_.set(value.guid,value);}has(value){return this.valuesByGuid_.has(value.guid);}get length(){return this.valuesByGuid_.size;}*[Symbol.iterator](){for(var _ref of this.valuesByGuid_){var _ref2=_slicedToArray(_ref,2);var guid=_ref2[0];var value=_ref2[1];yield value;}}resolve(valueSet,opt_required){for(var _ref3 of this.valuesByGuid_){var _ref4=_slicedToArray(_ref3,2);var guid=_ref4[0];var value=_ref4[1];if(!(value instanceof tr.v.d.ValueRef))continue;value=valueSet.lookup(guid);if(value instanceof tr.v.Histogram)this.valuesByGuid_.set(guid,value);else if(opt_required)throw new Error('Unable to find Histogram '+guid);}}asDictInto_(d){d.guids=[];for(var value of this)d.guids.push(value.guid);}static fromDict(d){return new RelatedValueSet(d.guids.map(guid=>new tr.v.d.ValueRef(guid)));}}tr.v.d.Diagnostic.register(RelatedValueSet,{elementName:'tr-v-ui-related-value-set-span'});return{RelatedValueSet:RelatedValueSet};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../../base/iteration_helpers.js":47,"./diagnostic.js":184,"./value_ref.js":194}],193:[function(require,module,exports){(function(global){"use strict";require("./diagnostic.js");require("../numeric.js");'use strict';global.tr.exportTo('tr.v.d',function(){class Scalar extends tr.v.d.Diagnostic{constructor(value){super();if(!(value instanceof tr.v.ScalarNumeric))throw new Error("expected ScalarNumeric");this.value=value;}asDictInto_(d){d.value=this.value.asDict();}static fromDict(d){return new Scalar(tr.v.ScalarNumeric.fromDict(d.value));}}tr.v.d.Diagnostic.register(Scalar,{elementName:'tr-v-ui-scalar-diagnostic-span'});return{Scalar:Scalar};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../numeric.js":196,"./diagnostic.js":184}],194:[function(require,module,exports){(function(global){"use strict";require("../../base/base.js");'use strict';global.tr.exportTo('tr.v.d',function(){function ValueRef(guid){this.guid=guid;}return{ValueRef:ValueRef};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../../base/base.js":34}],195:[function(require,module,exports){(function(global){"use strict";var _slicedToArray=function(){function sliceIterator(arr,i){var _arr=[];var _n=true;var _d=false;var _e=undefined;try{for(var _i=arr[Symbol.iterator](),_s;!(_n=(_s=_i.next()).done);_n=true){_arr.push(_s.value);if(i&&_arr.length===i)break;}}catch(err){_d=true;_e=err;}finally{try{if(!_n&&_i["return"])_i["return"]();}finally{if(_d)throw _e;}}return _arr;}return function(arr,i){if(Array.isArray(arr)){return arr;}else if(Symbol.iterator in Object(arr)){return sliceIterator(arr,i);}else{throw new TypeError("Invalid attempt to destructure non-iterable instance");}};}();require("../base/iteration_helpers.js");require("../base/range.js");require("../base/running_statistics.js");require("../base/sorted_array_utils.js");require("../base/statistics.js");require("../base/unit.js");require("./diagnostics/diagnostic_map.js");require("./numeric.js");'use strict';global.tr.exportTo('tr.v',function(){var MAX_DIAGNOSTIC_MAPS=16;var DEFAULT_BOUNDARIES_FOR_UNIT=new Map();class HistogramBin{constructor(range){this.range=range;this.count=0;this.diagnosticMaps=[];}addSample(value){this.count+=1;}addDiagnosticMap(diagnostics){tr.b.Statistics.uniformlySampleStream(this.diagnosticMaps,this.count,diagnostics,MAX_DIAGNOSTIC_MAPS);}addBin(other){if(!this.range.equals(other.range))throw new Error('Merging incompatible Histogram bins.');tr.b.Statistics.mergeSampledStreams(this.diagnosticMaps,this.count,other.diagnosticMaps,other.count,MAX_DIAGNOSTIC_MAPS);this.count+=other.count;}fromDict(dict){this.count=dict[0];if(dict.length>1){for(var map of dict[1]){this.diagnosticMaps.push(tr.v.d.DiagnosticMap.fromDict(map));}}}asDict(){if(!this.diagnosticMaps.length){return[this.count];}return[this.count,this.diagnosticMaps.map(d=>d.asDict())];}}var DEFAULT_SUMMARY_OPTIONS=new Map([['avg',true],['geometricMean',false],['std',true],['count',true],['sum',true],['min',true],['max',true],['nans',false]]);class Histogram{constructor(name,unit,opt_binBoundaries){var binBoundaries=opt_binBoundaries;if(!binBoundaries){var baseUnit=unit.baseUnit?unit.baseUnit:unit;binBoundaries=DEFAULT_BOUNDARIES_FOR_UNIT.get(baseUnit.unitName);}this.guid_=undefined;this.binBoundariesDict_=binBoundaries.asDict();this.centralBins=[];this.description='';this.diagnostics=new tr.v.d.DiagnosticMap();this.maxCount_=0;this.name_=name;this.nanDiagnosticMaps=[];this.numNans=0;this.running=new tr.b.RunningStatistics();this.sampleValues_=[];this.shortName=undefined;this.summaryOptions=new Map(DEFAULT_SUMMARY_OPTIONS);this.summaryOptions.set('percentile',[]);this.unit=unit;this.underflowBin=new HistogramBin(tr.b.Range.fromExplicitRange(-Number.MAX_VALUE,binBoundaries.range.min));this.overflowBin=new HistogramBin(tr.b.Range.fromExplicitRange(binBoundaries.range.max,Number.MAX_VALUE));for(var range of binBoundaries.binRanges()){this.centralBins.push(new HistogramBin(range));}this.allBins=[this.underflowBin];for(var bin of this.centralBins)this.allBins.push(bin);this.allBins.push(this.overflowBin);this.maxNumSampleValues_=this.defaultMaxNumSampleValues_;}get maxNumSampleValues(){return this.maxNumSampleValues_;}set maxNumSampleValues(n){this.maxNumSampleValues_=n;tr.b.Statistics.uniformlySampleArray(this.sampleValues_,this.maxNumSampleValues_);}get name(){return this.name_;}get guid(){if(this.guid_===undefined)this.guid_=tr.b.GUID.allocateUUID4();return this.guid_;}set guid(guid){if(this.guid_!==undefined)throw new Error('Cannot reset guid');this.guid_=guid;}static fromDict(dict){var hist=new Histogram(dict.name,tr.b.Unit.fromJSON(dict.unit),HistogramBinBoundaries.fromDict(dict.binBoundaries));hist.guid=dict.guid;if(dict.shortName){hist.shortName=dict.shortName;}if(dict.description){hist.description=dict.description;}if(dict.diagnostics){hist.diagnostics.addDicts(dict.diagnostics);}if(dict.underflowBin){hist.underflowBin.fromDict(dict.underflowBin);}if(dict.overflowBin){hist.overflowBin.fromDict(dict.overflowBin);}if(dict.centralBins){if(dict.centralBins.length!==undefined){for(var i=0;i<dict.centralBins.length;++i){hist.centralBins[i].fromDict(dict.centralBins[i]);}}else{tr.b.iterItems(dict.centralBins,(i,binDict)=>{hist.centralBins[i].fromDict(binDict);});}}for(var bin of hist.allBins){hist.maxCount_=Math.max(hist.maxCount_,bin.count);}if(dict.running){hist.running=tr.b.RunningStatistics.fromDict(dict.running);}if(dict.summaryOptions){hist.customizeSummaryOptions(dict.summaryOptions);}if(dict.maxNumSampleValues!==undefined){hist.maxNumSampleValues=dict.maxNumSampleValues;}if(dict.sampleValues){hist.sampleValues_=dict.sampleValues;}if(dict.numNans){hist.numNans=dict.numNans;}if(dict.nanDiagnostics){for(var map of dict.nanDiagnostics){hist.nanDiagnosticMaps.push(tr.v.d.DiagnosticMap.fromDict(map));}}return hist;}static buildFromSamples(unit,samples){var boundaries=HistogramBinBoundaries.createFromSamples(samples);var result=new Histogram(unit,boundaries);result.maxNumSampleValues=1000;for(var sample of samples)result.addSample(sample);return result;}get numValues(){return tr.b.Statistics.sum(this.allBins,function(e){return e.count;});}get average(){return this.running.mean;}get standardDeviation(){return this.running.stddev;}get geometricMean(){return this.running.geometricMean;}get sum(){return this.running.sum;}get maxCount(){return this.maxCount_;}getDifferenceSignificance(other,opt_alpha){if(this.unit!==other.unit)throw new Error('Cannot compare Numerics with different units');if(this.unit.improvementDirection===tr.b.ImprovementDirection.DONT_CARE){return tr.b.Statistics.Significance.DONT_CARE;}if(!(other instanceof Histogram))throw new Error('Unable to compute a p-value');var testResult=tr.b.Statistics.mwu(this.sampleValues,other.sampleValues,opt_alpha);return testResult.significance;}getApproximatePercentile(percent){if(!(percent>=0&&percent<=1))throw new Error('percent must be [0,1]');if(this.numValues==0)return 0;var valuesToSkip=Math.floor((this.numValues-1)*percent);for(var i=0;i<this.allBins.length;i++){var bin=this.allBins[i];valuesToSkip-=bin.count;if(valuesToSkip<0){if(bin===this.underflowBin)return bin.range.max;else if(bin===this.overflowBin)return bin.range.min;else return bin.range.center;}}throw new Error('Unreachable');}getBinForValue(value){var binIndex=tr.b.findHighIndexInSortedArray(this.allBins,b=>value<b.range.max?-1:1);return this.allBins[binIndex]||this.overflowBin;}addSample(value,opt_diagnostics){if(opt_diagnostics&&!(opt_diagnostics instanceof tr.v.d.DiagnosticMap))opt_diagnostics=tr.v.d.DiagnosticMap.fromObject(opt_diagnostics);if(typeof value!=='number'||isNaN(value)){this.numNans++;if(opt_diagnostics){tr.b.Statistics.uniformlySampleStream(this.nanDiagnosticMaps,this.numNans,opt_diagnostics,MAX_DIAGNOSTIC_MAPS);}}else{this.running.add(value);var bin=this.getBinForValue(value);bin.addSample(value);if(opt_diagnostics)bin.addDiagnosticMap(opt_diagnostics);if(bin.count>this.maxCount_)this.maxCount_=bin.count;}tr.b.Statistics.uniformlySampleStream(this.sampleValues_,this.numValues+this.numNans,value,this.maxNumSampleValues);}sampleValuesInto(samples){for(var sampleValue of this.sampleValues)samples.push(sampleValue);}canAddHistogram(other){if(this.unit!==other.unit)return false;if(this.allBins.length!==other.allBins.length)return false;for(var i=0;i<this.allBins.length;++i)if(!this.allBins[i].range.equals(other.allBins[i].range))return false;return true;}addHistogram(other){if(!this.canAddHistogram(other)){throw new Error('Merging incompatible Histograms');}tr.b.Statistics.mergeSampledStreams(this.nanDiagnosticMaps,this.numNans,other.nanDiagnosticMaps,other.numNans,MAX_DIAGNOSTIC_MAPS);tr.b.Statistics.mergeSampledStreams(this.sampleValues,this.numValues,other.sampleValues,other.numValues,tr.b.Statistics.mean([this.maxNumSampleValues,other.maxNumSampleValues]));this.numNans+=other.numNans;this.running=this.running.merge(other.running);for(var i=0;i<this.allBins.length;++i){this.allBins[i].addBin(other.allBins[i]);}}customizeSummaryOptions(summaryOptions){tr.b.iterItems(summaryOptions,(key,value)=>this.summaryOptions.set(key,value));}get statisticsScalars(){function statNameToKey(stat){switch(stat){case'std':return'stddev';case'avg':return'mean';}return stat;}function percentToString(percent){if(percent<0||percent>1)throw new Error('Percent must be between 0.0 and 1.0');switch(percent){case 0:return'000';case 1:return'100';}var str=percent.toString();if(str[1]!=='.')throw new Error('Unexpected percent');str=str+'0'.repeat(Math.max(4-str.length,0));if(str.length>4)str=str.slice(0,4)+'_'+str.slice(4);return'0'+str.slice(2);}var results=new Map();for(var _ref of this.summaryOptions){var _ref2=_slicedToArray(_ref,2);var stat=_ref2[0];var option=_ref2[1];if(!option){continue;}if(stat==='percentile'){for(var percent of option){var percentile=this.getApproximatePercentile(percent);results.set('pct_'+percentToString(percent),new tr.v.ScalarNumeric(this.unit,percentile));}}else if(stat==='nans'){results.set('nans',new tr.v.ScalarNumeric(tr.b.Unit.byName.count_smallerIsBetter,this.numNans));}else{var statUnit=stat==='count'?tr.b.Unit.byName.count_smallerIsBetter:this.unit;var key=statNameToKey(stat);var statValue=this.running[key];if(typeof statValue==='number'){results.set(stat,new tr.v.ScalarNumeric(statUnit,statValue));}}}return results;}get sampleValues(){return this.sampleValues_;}clone(){return Histogram.fromDict(this.asDict());}cloneEmpty(){var binBoundaries=HistogramBinBoundaries.fromDict(this.binBoundariesDict_);return new Histogram(this.name,this.unit,binBoundaries);}asDict(){var dict={};dict.binBoundaries=this.binBoundariesDict_;dict.name=this.name;dict.unit=this.unit.asJSON();dict.guid=this.guid;if(this.shortName){dict.shortName=this.shortName;}if(this.description){dict.description=this.description;}if(this.diagnostics.size){dict.diagnostics=this.diagnostics.asDict();}if(this.maxNumSampleValues!==this.defaultMaxNumSampleValues_){dict.maxNumSampleValues=this.maxNumSampleValues;}if(this.numNans){dict.numNans=this.numNans;}if(this.nanDiagnosticMaps.length){dict.nanDiagnostics=this.nanDiagnosticMaps.map(dm=>dm.asDict());}if(this.underflowBin.count){dict.underflowBin=this.underflowBin.asDict();}if(this.overflowBin.count){dict.overflowBin=this.overflowBin.asDict();}if(this.numValues){dict.sampleValues=this.sampleValues.slice();dict.running=this.running.asDict();dict.centralBins=this.centralBinsAsDict_();}var summaryOptions={};var anyOverriddenSummaryOptions=false;for(var _ref3 of this.summaryOptions){var _ref4=_slicedToArray(_ref3,2);var name=_ref4[0];var option=_ref4[1];if(name==='percentile'){if(option.length===0){continue;}option=option.slice();}else if(option===DEFAULT_SUMMARY_OPTIONS.get(name)){continue;}summaryOptions[name]=option;anyOverriddenSummaryOptions=true;}if(anyOverriddenSummaryOptions){dict.summaryOptions=summaryOptions;}return dict;}centralBinsAsDict_(){var numCentralBins=this.centralBins.length;var emptyBins=0;for(var i=0;i<numCentralBins;++i){if(this.centralBins[i].count===0){++emptyBins;}}if(emptyBins===numCentralBins){return undefined;}if(emptyBins>numCentralBins/2){var centralBinsDict={};for(var i=0;i<numCentralBins;++i){var bin=this.centralBins[i];if(bin.count>0){centralBinsDict[i]=bin.asDict();}}return centralBinsDict;}var centralBinsArray=[];for(var i=0;i<numCentralBins;++i){centralBinsArray.push(this.centralBins[i].asDict());}return centralBinsArray;}get defaultMaxNumSampleValues_(){return this.allBins.length*10;}}var HISTOGRAM_BIN_BOUNDARIES_CACHE=new Map();class HistogramBinBoundaries{static createLinear(min,max,numBins){return new HistogramBinBoundaries(min).addLinearBins(max,numBins);}static createExponential(min,max,numBins){return new HistogramBinBoundaries(min).addExponentialBins(max,numBins);}static createWithBoundaries(binBoundaries){var builder=new HistogramBinBoundaries(binBoundaries[0]);for(var boundary of binBoundaries.slice(1))builder.addBinBoundary(boundary);return builder;}static createFromSamples(samples){var range=new tr.b.Range();for(var sample of samples)if(!isNaN(Math.max(sample)))range.addValue(sample);if(range.isEmpty)range.addValue(1);if(range.min===range.max)range.addValue(range.min-1);var numBins=Math.ceil(Math.sqrt(samples.length));var builder=new HistogramBinBoundaries(range.min);builder.addLinearBins(range.max,numBins);return builder;}constructor(minBinBoundary){this.boundaries_=undefined;this.builder_=[minBinBoundary];this.range_=new tr.b.Range();this.range_.addValue(minBinBoundary);}get range(){return this.range_;}asDict(){return this.builder_.slice();}static fromDict(dict){var cacheKey=JSON.stringify(dict);if(HISTOGRAM_BIN_BOUNDARIES_CACHE.has(cacheKey)){return HISTOGRAM_BIN_BOUNDARIES_CACHE.get(cacheKey);}var binBoundaries=new HistogramBinBoundaries(dict[0]);for(var slice of dict.slice(1)){if(!(slice instanceof Array)){binBoundaries.addBinBoundary(slice);continue;}switch(slice[0]){case HistogramBinBoundaries.SLICE_TYPE.LINEAR:binBoundaries.addLinearBins(slice[1],slice[2]);break;case HistogramBinBoundaries.SLICE_TYPE.EXPONENTIAL:binBoundaries.addExponentialBins(slice[1],slice[2]);break;default:throw new Error('Unrecognized HistogramBinBoundaries slice type');}}HISTOGRAM_BIN_BOUNDARIES_CACHE.set(cacheKey,binBoundaries);return binBoundaries;}*binRanges(){if(this.boundaries_===undefined){this.build_();}for(var i=0;i<this.boundaries_.length-1;++i){yield tr.b.Range.fromExplicitRange(this.boundaries_[i],this.boundaries_[i+1]);}}build_(){if(typeof this.builder_[0]!=='number'){throw new Error('Invalid start of builder_');}this.boundaries_=[this.builder_[0]];for(var slice of this.builder_.slice(1)){if(!(slice instanceof Array)){this.boundaries_.push(slice);continue;}var nextMaxBinBoundary=slice[1];var binCount=slice[2];var curMaxBinBoundary=this.boundaries_[this.boundaries_.length-1];switch(slice[0]){case HistogramBinBoundaries.SLICE_TYPE.LINEAR:var binWidth=(nextMaxBinBoundary-curMaxBinBoundary)/binCount;for(var i=1;i<binCount;i++){var boundary=curMaxBinBoundary+i*binWidth;this.boundaries_.push(boundary);}break;case HistogramBinBoundaries.SLICE_TYPE.EXPONENTIAL:var binExponentWidth=Math.log(nextMaxBinBoundary/curMaxBinBoundary)/binCount;for(var i=1;i<binCount;i++){var boundary=curMaxBinBoundary*Math.exp(i*binExponentWidth);this.boundaries_.push(boundary);}break;default:throw new Error('Unrecognized HistogramBinBoundaries slice type');}this.boundaries_.push(nextMaxBinBoundary);}}addBinBoundary(nextMaxBinBoundary){if(nextMaxBinBoundary<=this.range.max){throw new Error('The added max bin boundary must be larger than '+'the current max boundary');}this.boundaries_=undefined;this.builder_.push(nextMaxBinBoundary);this.range.addValue(nextMaxBinBoundary);return this;}addLinearBins(nextMaxBinBoundary,binCount){if(binCount<=0)throw new Error('Bin count must be positive');if(nextMaxBinBoundary<=this.range.max){throw new Error('The new max bin boundary must be greater than '+'the previous max bin boundary');}this.boundaries_=undefined;this.builder_.push([HistogramBinBoundaries.SLICE_TYPE.LINEAR,nextMaxBinBoundary,binCount]);this.range.addValue(nextMaxBinBoundary);return this;}addExponentialBins(nextMaxBinBoundary,binCount){if(binCount<=0){throw new Error('Bin count must be positive');}if(this.range.max<=0){throw new Error('Current max bin boundary must be positive');}if(this.range.max>=nextMaxBinBoundary){throw new Error('The last added max boundary must be greater than '+'the current max boundary boundary');}this.boundaries_=undefined;this.builder_.push([HistogramBinBoundaries.SLICE_TYPE.EXPONENTIAL,nextMaxBinBoundary,binCount]);this.range.addValue(nextMaxBinBoundary);return this;}}HistogramBinBoundaries.SLICE_TYPE={LINEAR:0,EXPONENTIAL:1};DEFAULT_BOUNDARIES_FOR_UNIT.set(tr.b.Unit.byName.timeDurationInMs.unitName,HistogramBinBoundaries.createExponential(1e-3,1e6,1e2));DEFAULT_BOUNDARIES_FOR_UNIT.set(tr.b.Unit.byName.timeStampInMs.unitName,HistogramBinBoundaries.createLinear(0,1e10,1e3));DEFAULT_BOUNDARIES_FOR_UNIT.set(tr.b.Unit.byName.normalizedPercentage.unitName,HistogramBinBoundaries.createLinear(0,1.0,20));DEFAULT_BOUNDARIES_FOR_UNIT.set(tr.b.Unit.byName.sizeInBytes.unitName,HistogramBinBoundaries.createExponential(1,1e12,1e2));DEFAULT_BOUNDARIES_FOR_UNIT.set(tr.b.Unit.byName.energyInJoules.unitName,HistogramBinBoundaries.createExponential(1e-3,1e3,50));DEFAULT_BOUNDARIES_FOR_UNIT.set(tr.b.Unit.byName.powerInWatts.unitName,HistogramBinBoundaries.createExponential(1e-3,1,50));DEFAULT_BOUNDARIES_FOR_UNIT.set(tr.b.Unit.byName.unitlessNumber.unitName,HistogramBinBoundaries.createExponential(1e-3,1e3,50));DEFAULT_BOUNDARIES_FOR_UNIT.set(tr.b.Unit.byName.count.unitName,HistogramBinBoundaries.createExponential(1,1e3,20));return{Histogram:Histogram,HistogramBinBoundaries:HistogramBinBoundaries};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/iteration_helpers.js":47,"../base/range.js":53,"../base/running_statistics.js":56,"../base/sorted_array_utils.js":58,"../base/statistics.js":59,"../base/unit.js":63,"./diagnostics/diagnostic_map.js":185,"./numeric.js":196}],196:[function(require,module,exports){(function(global){"use strict";require("../base/iteration_helpers.js");require("../base/unit.js");'use strict';global.tr.exportTo('tr.v',function(){class NumericBase{constructor(unit){if(!(unit instanceof tr.b.Unit))throw new Error('Expected provided unit to be instance of Unit');this.unit=unit;}asDict(){var d={unit:this.unit.asJSON()};this.asDictInto_(d);return d;}static fromDict(d){if(d.type==='scalar')return ScalarNumeric.fromDict(d);throw new Error('Not implemented');}}class ScalarNumeric extends NumericBase{constructor(unit,value){if(!(unit instanceof tr.b.Unit))throw new Error('Expected Unit');if(!(typeof value=='number'))throw new Error('Expected value to be number');super(unit);this.value=value;}asDictInto_(d){d.type='scalar';if(this.value===Infinity)d.value='Infinity';else if(this.value===-Infinity)d.value='-Infinity';else if(isNaN(this.value))d.value='NaN';else d.value=this.value;}toString(){return this.unit.format(this.value);}static fromDict(d){if(typeof d.value==='string'){if(d.value==='-Infinity'){d.value=-Infinity;}else if(d.value==='Infinity'){d.value=Infinity;}else if(d.value==='NaN'){d.value=NaN;}}return new ScalarNumeric(tr.b.Unit.fromJSON(d.unit),d.value);}}return{NumericBase:NumericBase,ScalarNumeric:ScalarNumeric};});}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../base/iteration_helpers.js":47,"../base/unit.js":63}],197:[function(require,module,exports){'use strict';const ExtensionProtocol=require('../../../lighthouse-core/gather/connections/extension');const RawProtocol=require('../../../lighthouse-core/gather/connections/raw');const Runner=require('../../../lighthouse-core/runner');const Config=require('../../../lighthouse-core/config/config');const defaultConfig=require('../../../lighthouse-core/config/default.json');const log=require('../../../lighthouse-core/lib/log');const ReportGenerator=require('../../../lighthouse-core/report/report-generator');const STORAGE_KEY='lighthouse_v2';const isExtension=window.chrome&&chrome.runtime;const _flatten=arr=>[].concat(...arr);const _uniq=arr=>Array.from(new Set(arr));let lighthouseIsRunning=false;let latestStatusLog=[];function updateBadgeUI(optUrl){if(isExtension){const manifest=chrome.runtime.getManifest();let title=manifest.browser_action.default_title;let path=manifest.browser_action.default_icon['38'];if(lighthouseIsRunning){title=`Testing ${optUrl}`;path='images/lh_logo_icon_light.png';}
chrome.browserAction.setTitle({title});chrome.browserAction.setIcon({path});}}
function filterOutArtifacts(result){result.artifacts=undefined;}
window.runLighthouseForConnection=function(connection,url,options,aggregationTags){const runConfig=JSON.parse(JSON.stringify(defaultConfig));const chosenTags=aggregationTags.filter(tag=>tag.value).map(tag=>tag.id);Config.rebuildConfigFromTags(runConfig,chosenTags);const config=new Config(runConfig);const runOptions=Object.assign({},options,{url,config});lighthouseIsRunning=true;updateBadgeUI(url);return Runner.run(connection,runOptions).then(result=>{lighthouseIsRunning=false;updateBadgeUI();filterOutArtifacts(result);return result;}).catch(err=>{lighthouseIsRunning=false;updateBadgeUI();throw err;});};window.runLighthouseInExtension=function(options,aggregationTags){log.setLevel('info');const connection=new ExtensionProtocol();return connection.getCurrentTabURL().then(url=>window.runLighthouseForConnection(connection,url,options,aggregationTags)).then(results=>{const blobURL=window.createReportPageAsBlob(results,'extension');chrome.tabs.create({url:blobURL});});};window.runLighthouseInWorker=function(port,url,options,aggregationTags){log.setLevel('info');const connection=new RawProtocol(port);return window.runLighthouseForConnection(connection,url,options,aggregationTags);};window.createReportPageAsBlob=function(results,reportContext){performance.mark('report-start');const reportGenerator=new ReportGenerator();let html;try{html=reportGenerator.generateHTML(results,reportContext);}catch(err){html=reportGenerator.renderException(err,results);}
const blob=new Blob([html],{type:'text/html'});const blobURL=window.URL.createObjectURL(blob);performance.mark('report-end');performance.measure('generate report','report-start','report-end');return blobURL;};const tagMap={'pwa':'Progressive Web App audits','perf':'Performance metrics & diagnostics','best_practices':'Developer best practices'};window.getDefaultAggregationTags=function(){return _uniq(_flatten(getDefaultAggregations().map(agg=>agg.tags))).map(tag=>{return{id:tag,value:true,name:tagMap[tag]};});};window.getDefaultAggregations=function(){return _flatten(defaultConfig.aggregations.map(aggregation=>{if(aggregation.items.length===1){return{name:aggregation.name,id:aggregation.id,tags:aggregation.tags,description:aggregation.description,audits:aggregation.items[0].audits,};}
return aggregation.items;})).map(aggregation=>{return{name:aggregation.name,id:aggregation.id,tags:aggregation.tags,description:aggregation.description,audits:Object.keys(aggregation.audits)};});};window.saveSelectedTags=function(selectedTags){const storage={[STORAGE_KEY]:selectedTags};chrome.storage.local.set(storage);};window.loadSavedTags=function(){return new Promise(resolve=>{chrome.storage.local.get(STORAGE_KEY,result=>{const tags=result&&result[STORAGE_KEY];resolve(Array.isArray(tags)?tags:[]);});});};window.resolveTags=function(){return loadSavedTags().then(selectedTags=>{const tags=[].concat(window.getDefaultAggregationTags());if(Array.isArray(selectedTags)){selectedTags.forEach(selectedTag=>{const setting=tags.find(t=>t.id==selectedTag.id);if(setting){setting.value=selectedTag.value;}});}
return tags;});};window.listenForStatus=function(callback){log.events.addListener('status',function(log){latestStatusLog=log;callback(log);});if(lighthouseIsRunning&&latestStatusLog){callback(latestStatusLog);}};window.isRunning=function(){return lighthouseIsRunning;};if(window.chrome&&chrome.runtime){chrome.runtime.onInstalled.addListener(details=>{if(details.previousVersion){console.log('previousVersion',details.previousVersion);}});}
window.getManifest=function(){return isExtension&&chrome.runtime.getManifest();};},{"../../../lighthouse-core/config/config":4,"../../../lighthouse-core/config/default.json":5,"../../../lighthouse-core/gather/connections/extension":14,"../../../lighthouse-core/gather/connections/raw":15,"../../../lighthouse-core/lib/log":24,"../../../lighthouse-core/report/report-generator":32,"../../../lighthouse-core/runner":33}],198:[function(require,module,exports){'use strict'
exports.byteLength=byteLength
exports.toByteArray=toByteArray
exports.fromByteArray=fromByteArray
var lookup=[]
var revLookup=[]
var Arr=typeof Uint8Array!=='undefined'?Uint8Array:Array
var code='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
for(var i=0,len=code.length;i<len;++i){lookup[i]=code[i]
revLookup[code.charCodeAt(i)]=i}
revLookup['-'.charCodeAt(0)]=62
revLookup['_'.charCodeAt(0)]=63
function placeHoldersCount(b64){var len=b64.length
if(len%4>0){throw new Error('Invalid string. Length must be a multiple of 4')}
return b64[len-2]==='='?2:b64[len-1]==='='?1:0}
function byteLength(b64){return b64.length*3/4-placeHoldersCount(b64)}
function toByteArray(b64){var i,j,l,tmp,placeHolders,arr
var len=b64.length
placeHolders=placeHoldersCount(b64)
arr=new Arr(len*3/4-placeHolders)
l=placeHolders>0?len-4:len
var L=0
for(i=0,j=0;i<l;i+=4,j+=3){tmp=(revLookup[b64.charCodeAt(i)]<<18)|(revLookup[b64.charCodeAt(i+1)]<<12)|(revLookup[b64.charCodeAt(i+2)]<<6)|revLookup[b64.charCodeAt(i+3)]
arr[L++]=(tmp>>16)&0xFF
arr[L++]=(tmp>>8)&0xFF
arr[L++]=tmp&0xFF}
if(placeHolders===2){tmp=(revLookup[b64.charCodeAt(i)]<<2)|(revLookup[b64.charCodeAt(i+1)]>>4)
arr[L++]=tmp&0xFF}else if(placeHolders===1){tmp=(revLookup[b64.charCodeAt(i)]<<10)|(revLookup[b64.charCodeAt(i+1)]<<4)|(revLookup[b64.charCodeAt(i+2)]>>2)
arr[L++]=(tmp>>8)&0xFF
arr[L++]=tmp&0xFF}
return arr}
function tripletToBase64(num){return lookup[num>>18&0x3F]+lookup[num>>12&0x3F]+lookup[num>>6&0x3F]+lookup[num&0x3F]}
function encodeChunk(uint8,start,end){var tmp
var output=[]
for(var i=start;i<end;i+=3){tmp=(uint8[i]<<16)+(uint8[i+1]<<8)+(uint8[i+2])
output.push(tripletToBase64(tmp))}
return output.join('')}
function fromByteArray(uint8){var tmp
var len=uint8.length
var extraBytes=len%3
var output=''
var parts=[]
var maxChunkLength=16383
for(var i=0,len2=len-extraBytes;i<len2;i+=maxChunkLength){parts.push(encodeChunk(uint8,i,(i+maxChunkLength)>len2?len2:(i+maxChunkLength)))}
if(extraBytes===1){tmp=uint8[len-1]
output+=lookup[tmp>>2]
output+=lookup[(tmp<<4)&0x3F]
output+='=='}else if(extraBytes===2){tmp=(uint8[len-2]<<8)+(uint8[len-1])
output+=lookup[tmp>>10]
output+=lookup[(tmp>>4)&0x3F]
output+=lookup[(tmp<<2)&0x3F]
output+='='}
parts.push(output)
return parts.join('')}},{}],199:[function(require,module,exports){},{}],200:[function(require,module,exports){(function(global){'use strict'
var base64=require('base64-js')
var ieee754=require('ieee754')
var isArray=require('isarray')
exports.Buffer=Buffer
exports.SlowBuffer=SlowBuffer
exports.INSPECT_MAX_BYTES=50
Buffer.TYPED_ARRAY_SUPPORT=global.TYPED_ARRAY_SUPPORT!==undefined?global.TYPED_ARRAY_SUPPORT:typedArraySupport()
exports.kMaxLength=kMaxLength()
function typedArraySupport(){try{var arr=new Uint8Array(1)
arr.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}}
return arr.foo()===42&&typeof arr.subarray==='function'&&arr.subarray(1,1).byteLength===0}catch(e){return false}}
function kMaxLength(){return Buffer.TYPED_ARRAY_SUPPORT?0x7fffffff:0x3fffffff}
function createBuffer(that,length){if(kMaxLength()<length){throw new RangeError('Invalid typed array length')}
if(Buffer.TYPED_ARRAY_SUPPORT){that=new Uint8Array(length)
that.__proto__=Buffer.prototype}else{if(that===null){that=new Buffer(length)}
that.length=length}
return that}
function Buffer(arg,encodingOrOffset,length){if(!Buffer.TYPED_ARRAY_SUPPORT&&!(this instanceof Buffer)){return new Buffer(arg,encodingOrOffset,length)}
if(typeof arg==='number'){if(typeof encodingOrOffset==='string'){throw new Error('If encoding is specified then the first argument must be a string')}
return allocUnsafe(this,arg)}
return from(this,arg,encodingOrOffset,length)}
Buffer.poolSize=8192
Buffer._augment=function(arr){arr.__proto__=Buffer.prototype
return arr}
function from(that,value,encodingOrOffset,length){if(typeof value==='number'){throw new TypeError('"value" argument must not be a number')}
if(typeof ArrayBuffer!=='undefined'&&value instanceof ArrayBuffer){return fromArrayBuffer(that,value,encodingOrOffset,length)}
if(typeof value==='string'){return fromString(that,value,encodingOrOffset)}
return fromObject(that,value)}
Buffer.from=function(value,encodingOrOffset,length){return from(null,value,encodingOrOffset,length)}
if(Buffer.TYPED_ARRAY_SUPPORT){Buffer.prototype.__proto__=Uint8Array.prototype
Buffer.__proto__=Uint8Array
if(typeof Symbol!=='undefined'&&Symbol.species&&Buffer[Symbol.species]===Buffer){Object.defineProperty(Buffer,Symbol.species,{value:null,configurable:true})}}
function assertSize(size){if(typeof size!=='number'){throw new TypeError('"size" argument must be a number')}else if(size<0){throw new RangeError('"size" argument must not be negative')}}
function alloc(that,size,fill,encoding){assertSize(size)
if(size<=0){return createBuffer(that,size)}
if(fill!==undefined){return typeof encoding==='string'?createBuffer(that,size).fill(fill,encoding):createBuffer(that,size).fill(fill)}
return createBuffer(that,size)}
Buffer.alloc=function(size,fill,encoding){return alloc(null,size,fill,encoding)}
function allocUnsafe(that,size){assertSize(size)
that=createBuffer(that,size<0?0:checked(size)|0)
if(!Buffer.TYPED_ARRAY_SUPPORT){for(var i=0;i<size;++i){that[i]=0}}
return that}
Buffer.allocUnsafe=function(size){return allocUnsafe(null,size)}
Buffer.allocUnsafeSlow=function(size){return allocUnsafe(null,size)}
function fromString(that,string,encoding){if(typeof encoding!=='string'||encoding===''){encoding='utf8'}
if(!Buffer.isEncoding(encoding)){throw new TypeError('"encoding" must be a valid string encoding')}
var length=byteLength(string,encoding)|0
that=createBuffer(that,length)
var actual=that.write(string,encoding)
if(actual!==length){that=that.slice(0,actual)}
return that}
function fromArrayLike(that,array){var length=array.length<0?0:checked(array.length)|0
that=createBuffer(that,length)
for(var i=0;i<length;i+=1){that[i]=array[i]&255}
return that}
function fromArrayBuffer(that,array,byteOffset,length){array.byteLength
if(byteOffset<0||array.byteLength<byteOffset){throw new RangeError('\'offset\' is out of bounds')}
if(array.byteLength<byteOffset+(length||0)){throw new RangeError('\'length\' is out of bounds')}
if(byteOffset===undefined&&length===undefined){array=new Uint8Array(array)}else if(length===undefined){array=new Uint8Array(array,byteOffset)}else{array=new Uint8Array(array,byteOffset,length)}
if(Buffer.TYPED_ARRAY_SUPPORT){that=array
that.__proto__=Buffer.prototype}else{that=fromArrayLike(that,array)}
return that}
function fromObject(that,obj){if(Buffer.isBuffer(obj)){var len=checked(obj.length)|0
that=createBuffer(that,len)
if(that.length===0){return that}
obj.copy(that,0,0,len)
return that}
if(obj){if((typeof ArrayBuffer!=='undefined'&&obj.buffer instanceof ArrayBuffer)||'length'in obj){if(typeof obj.length!=='number'||isnan(obj.length)){return createBuffer(that,0)}
return fromArrayLike(that,obj)}
if(obj.type==='Buffer'&&isArray(obj.data)){return fromArrayLike(that,obj.data)}}
throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')}
function checked(length){if(length>=kMaxLength()){throw new RangeError('Attempt to allocate Buffer larger than maximum '+'size: 0x'+kMaxLength().toString(16)+' bytes')}
return length|0}
function SlowBuffer(length){if(+length!=length){length=0}
return Buffer.alloc(+length)}
Buffer.isBuffer=function isBuffer(b){return!!(b!=null&&b._isBuffer)}
Buffer.compare=function compare(a,b){if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b)){throw new TypeError('Arguments must be Buffers')}
if(a===b)return 0
var x=a.length
var y=b.length
for(var i=0,len=Math.min(x,y);i<len;++i){if(a[i]!==b[i]){x=a[i]
y=b[i]
break}}
if(x<y)return-1
if(y<x)return 1
return 0}
Buffer.isEncoding=function isEncoding(encoding){switch(String(encoding).toLowerCase()){case'hex':case'utf8':case'utf-8':case'ascii':case'latin1':case'binary':case'base64':case'ucs2':case'ucs-2':case'utf16le':case'utf-16le':return true
default:return false}}
Buffer.concat=function concat(list,length){if(!isArray(list)){throw new TypeError('"list" argument must be an Array of Buffers')}
if(list.length===0){return Buffer.alloc(0)}
var i
if(length===undefined){length=0
for(i=0;i<list.length;++i){length+=list[i].length}}
var buffer=Buffer.allocUnsafe(length)
var pos=0
for(i=0;i<list.length;++i){var buf=list[i]
if(!Buffer.isBuffer(buf)){throw new TypeError('"list" argument must be an Array of Buffers')}
buf.copy(buffer,pos)
pos+=buf.length}
return buffer}
function byteLength(string,encoding){if(Buffer.isBuffer(string)){return string.length}
if(typeof ArrayBuffer!=='undefined'&&typeof ArrayBuffer.isView==='function'&&(ArrayBuffer.isView(string)||string instanceof ArrayBuffer)){return string.byteLength}
if(typeof string!=='string'){string=''+string}
var len=string.length
if(len===0)return 0
var loweredCase=false
for(;;){switch(encoding){case'ascii':case'latin1':case'binary':return len
case'utf8':case'utf-8':case undefined:return utf8ToBytes(string).length
case'ucs2':case'ucs-2':case'utf16le':case'utf-16le':return len*2
case'hex':return len>>>1
case'base64':return base64ToBytes(string).length
default:if(loweredCase)return utf8ToBytes(string).length
encoding=(''+encoding).toLowerCase()
loweredCase=true}}}
Buffer.byteLength=byteLength
function slowToString(encoding,start,end){var loweredCase=false
if(start===undefined||start<0){start=0}
if(start>this.length){return''}
if(end===undefined||end>this.length){end=this.length}
if(end<=0){return''}
end>>>=0
start>>>=0
if(end<=start){return''}
if(!encoding)encoding='utf8'
while(true){switch(encoding){case'hex':return hexSlice(this,start,end)
case'utf8':case'utf-8':return utf8Slice(this,start,end)
case'ascii':return asciiSlice(this,start,end)
case'latin1':case'binary':return latin1Slice(this,start,end)
case'base64':return base64Slice(this,start,end)
case'ucs2':case'ucs-2':case'utf16le':case'utf-16le':return utf16leSlice(this,start,end)
default:if(loweredCase)throw new TypeError('Unknown encoding: '+encoding)
encoding=(encoding+'').toLowerCase()
loweredCase=true}}}
Buffer.prototype._isBuffer=true
function swap(b,n,m){var i=b[n]
b[n]=b[m]
b[m]=i}
Buffer.prototype.swap16=function swap16(){var len=this.length
if(len%2!==0){throw new RangeError('Buffer size must be a multiple of 16-bits')}
for(var i=0;i<len;i+=2){swap(this,i,i+1)}
return this}
Buffer.prototype.swap32=function swap32(){var len=this.length
if(len%4!==0){throw new RangeError('Buffer size must be a multiple of 32-bits')}
for(var i=0;i<len;i+=4){swap(this,i,i+3)
swap(this,i+1,i+2)}
return this}
Buffer.prototype.swap64=function swap64(){var len=this.length
if(len%8!==0){throw new RangeError('Buffer size must be a multiple of 64-bits')}
for(var i=0;i<len;i+=8){swap(this,i,i+7)
swap(this,i+1,i+6)
swap(this,i+2,i+5)
swap(this,i+3,i+4)}
return this}
Buffer.prototype.toString=function toString(){var length=this.length|0
if(length===0)return''
if(arguments.length===0)return utf8Slice(this,0,length)
return slowToString.apply(this,arguments)}
Buffer.prototype.equals=function equals(b){if(!Buffer.isBuffer(b))throw new TypeError('Argument must be a Buffer')
if(this===b)return true
return Buffer.compare(this,b)===0}
Buffer.prototype.inspect=function inspect(){var str=''
var max=exports.INSPECT_MAX_BYTES
if(this.length>0){str=this.toString('hex',0,max).match(/.{2}/g).join(' ')
if(this.length>max)str+=' ... '}
return'<Buffer '+str+'>'}
Buffer.prototype.compare=function compare(target,start,end,thisStart,thisEnd){if(!Buffer.isBuffer(target)){throw new TypeError('Argument must be a Buffer')}
if(start===undefined){start=0}
if(end===undefined){end=target?target.length:0}
if(thisStart===undefined){thisStart=0}
if(thisEnd===undefined){thisEnd=this.length}
if(start<0||end>target.length||thisStart<0||thisEnd>this.length){throw new RangeError('out of range index')}
if(thisStart>=thisEnd&&start>=end){return 0}
if(thisStart>=thisEnd){return-1}
if(start>=end){return 1}
start>>>=0
end>>>=0
thisStart>>>=0
thisEnd>>>=0
if(this===target)return 0
var x=thisEnd-thisStart
var y=end-start
var len=Math.min(x,y)
var thisCopy=this.slice(thisStart,thisEnd)
var targetCopy=target.slice(start,end)
for(var i=0;i<len;++i){if(thisCopy[i]!==targetCopy[i]){x=thisCopy[i]
y=targetCopy[i]
break}}
if(x<y)return-1
if(y<x)return 1
return 0}
function bidirectionalIndexOf(buffer,val,byteOffset,encoding,dir){if(buffer.length===0)return-1
if(typeof byteOffset==='string'){encoding=byteOffset
byteOffset=0}else if(byteOffset>0x7fffffff){byteOffset=0x7fffffff}else if(byteOffset<-0x80000000){byteOffset=-0x80000000}
byteOffset=+byteOffset
if(isNaN(byteOffset)){byteOffset=dir?0:(buffer.length-1)}
if(byteOffset<0)byteOffset=buffer.length+byteOffset
if(byteOffset>=buffer.length){if(dir)return-1
else byteOffset=buffer.length-1}else if(byteOffset<0){if(dir)byteOffset=0
else return-1}
if(typeof val==='string'){val=Buffer.from(val,encoding)}
if(Buffer.isBuffer(val)){if(val.length===0){return-1}
return arrayIndexOf(buffer,val,byteOffset,encoding,dir)}else if(typeof val==='number'){val=val&0xFF
if(Buffer.TYPED_ARRAY_SUPPORT&&typeof Uint8Array.prototype.indexOf==='function'){if(dir){return Uint8Array.prototype.indexOf.call(buffer,val,byteOffset)}else{return Uint8Array.prototype.lastIndexOf.call(buffer,val,byteOffset)}}
return arrayIndexOf(buffer,[val],byteOffset,encoding,dir)}
throw new TypeError('val must be string, number or Buffer')}
function arrayIndexOf(arr,val,byteOffset,encoding,dir){var indexSize=1
var arrLength=arr.length
var valLength=val.length
if(encoding!==undefined){encoding=String(encoding).toLowerCase()
if(encoding==='ucs2'||encoding==='ucs-2'||encoding==='utf16le'||encoding==='utf-16le'){if(arr.length<2||val.length<2){return-1}
indexSize=2
arrLength/=2
valLength/=2
byteOffset/=2}}
function read(buf,i){if(indexSize===1){return buf[i]}else{return buf.readUInt16BE(i*indexSize)}}
var i
if(dir){var foundIndex=-1
for(i=byteOffset;i<arrLength;i++){if(read(arr,i)===read(val,foundIndex===-1?0:i-foundIndex)){if(foundIndex===-1)foundIndex=i
if(i-foundIndex+1===valLength)return foundIndex*indexSize}else{if(foundIndex!==-1)i-=i-foundIndex
foundIndex=-1}}}else{if(byteOffset+valLength>arrLength)byteOffset=arrLength-valLength
for(i=byteOffset;i>=0;i--){var found=true
for(var j=0;j<valLength;j++){if(read(arr,i+j)!==read(val,j)){found=false
break}}
if(found)return i}}
return-1}
Buffer.prototype.includes=function includes(val,byteOffset,encoding){return this.indexOf(val,byteOffset,encoding)!==-1}
Buffer.prototype.indexOf=function indexOf(val,byteOffset,encoding){return bidirectionalIndexOf(this,val,byteOffset,encoding,true)}
Buffer.prototype.lastIndexOf=function lastIndexOf(val,byteOffset,encoding){return bidirectionalIndexOf(this,val,byteOffset,encoding,false)}
function hexWrite(buf,string,offset,length){offset=Number(offset)||0
var remaining=buf.length-offset
if(!length){length=remaining}else{length=Number(length)
if(length>remaining){length=remaining}}
var strLen=string.length
if(strLen%2!==0)throw new TypeError('Invalid hex string')
if(length>strLen/2){length=strLen/2}
for(var i=0;i<length;++i){var parsed=parseInt(string.substr(i*2,2),16)
if(isNaN(parsed))return i
buf[offset+i]=parsed}
return i}
function utf8Write(buf,string,offset,length){return blitBuffer(utf8ToBytes(string,buf.length-offset),buf,offset,length)}
function asciiWrite(buf,string,offset,length){return blitBuffer(asciiToBytes(string),buf,offset,length)}
function latin1Write(buf,string,offset,length){return asciiWrite(buf,string,offset,length)}
function base64Write(buf,string,offset,length){return blitBuffer(base64ToBytes(string),buf,offset,length)}
function ucs2Write(buf,string,offset,length){return blitBuffer(utf16leToBytes(string,buf.length-offset),buf,offset,length)}
Buffer.prototype.write=function write(string,offset,length,encoding){if(offset===undefined){encoding='utf8'
length=this.length
offset=0}else if(length===undefined&&typeof offset==='string'){encoding=offset
length=this.length
offset=0}else if(isFinite(offset)){offset=offset|0
if(isFinite(length)){length=length|0
if(encoding===undefined)encoding='utf8'}else{encoding=length
length=undefined}}else{throw new Error('Buffer.write(string, encoding, offset[, length]) is no longer supported')}
var remaining=this.length-offset
if(length===undefined||length>remaining)length=remaining
if((string.length>0&&(length<0||offset<0))||offset>this.length){throw new RangeError('Attempt to write outside buffer bounds')}
if(!encoding)encoding='utf8'
var loweredCase=false
for(;;){switch(encoding){case'hex':return hexWrite(this,string,offset,length)
case'utf8':case'utf-8':return utf8Write(this,string,offset,length)
case'ascii':return asciiWrite(this,string,offset,length)
case'latin1':case'binary':return latin1Write(this,string,offset,length)
case'base64':return base64Write(this,string,offset,length)
case'ucs2':case'ucs-2':case'utf16le':case'utf-16le':return ucs2Write(this,string,offset,length)
default:if(loweredCase)throw new TypeError('Unknown encoding: '+encoding)
encoding=(''+encoding).toLowerCase()
loweredCase=true}}}
Buffer.prototype.toJSON=function toJSON(){return{type:'Buffer',data:Array.prototype.slice.call(this._arr||this,0)}}
function base64Slice(buf,start,end){if(start===0&&end===buf.length){return base64.fromByteArray(buf)}else{return base64.fromByteArray(buf.slice(start,end))}}
function utf8Slice(buf,start,end){end=Math.min(buf.length,end)
var res=[]
var i=start
while(i<end){var firstByte=buf[i]
var codePoint=null
var bytesPerSequence=(firstByte>0xEF)?4:(firstByte>0xDF)?3:(firstByte>0xBF)?2:1
if(i+bytesPerSequence<=end){var secondByte,thirdByte,fourthByte,tempCodePoint
switch(bytesPerSequence){case 1:if(firstByte<0x80){codePoint=firstByte}
break
case 2:secondByte=buf[i+1]
if((secondByte&0xC0)===0x80){tempCodePoint=(firstByte&0x1F)<<0x6|(secondByte&0x3F)
if(tempCodePoint>0x7F){codePoint=tempCodePoint}}
break
case 3:secondByte=buf[i+1]
thirdByte=buf[i+2]
if((secondByte&0xC0)===0x80&&(thirdByte&0xC0)===0x80){tempCodePoint=(firstByte&0xF)<<0xC|(secondByte&0x3F)<<0x6|(thirdByte&0x3F)
if(tempCodePoint>0x7FF&&(tempCodePoint<0xD800||tempCodePoint>0xDFFF)){codePoint=tempCodePoint}}
break
case 4:secondByte=buf[i+1]
thirdByte=buf[i+2]
fourthByte=buf[i+3]
if((secondByte&0xC0)===0x80&&(thirdByte&0xC0)===0x80&&(fourthByte&0xC0)===0x80){tempCodePoint=(firstByte&0xF)<<0x12|(secondByte&0x3F)<<0xC|(thirdByte&0x3F)<<0x6|(fourthByte&0x3F)
if(tempCodePoint>0xFFFF&&tempCodePoint<0x110000){codePoint=tempCodePoint}}}}
if(codePoint===null){codePoint=0xFFFD
bytesPerSequence=1}else if(codePoint>0xFFFF){codePoint-=0x10000
res.push(codePoint>>>10&0x3FF|0xD800)
codePoint=0xDC00|codePoint&0x3FF}
res.push(codePoint)
i+=bytesPerSequence}
return decodeCodePointsArray(res)}
var MAX_ARGUMENTS_LENGTH=0x1000
function decodeCodePointsArray(codePoints){var len=codePoints.length
if(len<=MAX_ARGUMENTS_LENGTH){return String.fromCharCode.apply(String,codePoints)}
var res=''
var i=0
while(i<len){res+=String.fromCharCode.apply(String,codePoints.slice(i,i+=MAX_ARGUMENTS_LENGTH))}
return res}
function asciiSlice(buf,start,end){var ret=''
end=Math.min(buf.length,end)
for(var i=start;i<end;++i){ret+=String.fromCharCode(buf[i]&0x7F)}
return ret}
function latin1Slice(buf,start,end){var ret=''
end=Math.min(buf.length,end)
for(var i=start;i<end;++i){ret+=String.fromCharCode(buf[i])}
return ret}
function hexSlice(buf,start,end){var len=buf.length
if(!start||start<0)start=0
if(!end||end<0||end>len)end=len
var out=''
for(var i=start;i<end;++i){out+=toHex(buf[i])}
return out}
function utf16leSlice(buf,start,end){var bytes=buf.slice(start,end)
var res=''
for(var i=0;i<bytes.length;i+=2){res+=String.fromCharCode(bytes[i]+bytes[i+1]*256)}
return res}
Buffer.prototype.slice=function slice(start,end){var len=this.length
start=~~start
end=end===undefined?len:~~end
if(start<0){start+=len
if(start<0)start=0}else if(start>len){start=len}
if(end<0){end+=len
if(end<0)end=0}else if(end>len){end=len}
if(end<start)end=start
var newBuf
if(Buffer.TYPED_ARRAY_SUPPORT){newBuf=this.subarray(start,end)
newBuf.__proto__=Buffer.prototype}else{var sliceLen=end-start
newBuf=new Buffer(sliceLen,undefined)
for(var i=0;i<sliceLen;++i){newBuf[i]=this[i+start]}}
return newBuf}
function checkOffset(offset,ext,length){if((offset%1)!==0||offset<0)throw new RangeError('offset is not uint')
if(offset+ext>length)throw new RangeError('Trying to access beyond buffer length')}
Buffer.prototype.readUIntLE=function readUIntLE(offset,byteLength,noAssert){offset=offset|0
byteLength=byteLength|0
if(!noAssert)checkOffset(offset,byteLength,this.length)
var val=this[offset]
var mul=1
var i=0
while(++i<byteLength&&(mul*=0x100)){val+=this[offset+i]*mul}
return val}
Buffer.prototype.readUIntBE=function readUIntBE(offset,byteLength,noAssert){offset=offset|0
byteLength=byteLength|0
if(!noAssert){checkOffset(offset,byteLength,this.length)}
var val=this[offset+--byteLength]
var mul=1
while(byteLength>0&&(mul*=0x100)){val+=this[offset+--byteLength]*mul}
return val}
Buffer.prototype.readUInt8=function readUInt8(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length)
return this[offset]}
Buffer.prototype.readUInt16LE=function readUInt16LE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length)
return this[offset]|(this[offset+1]<<8)}
Buffer.prototype.readUInt16BE=function readUInt16BE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length)
return(this[offset]<<8)|this[offset+1]}
Buffer.prototype.readUInt32LE=function readUInt32LE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length)
return((this[offset])|(this[offset+1]<<8)|(this[offset+2]<<16))+
(this[offset+3]*0x1000000)}
Buffer.prototype.readUInt32BE=function readUInt32BE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length)
return(this[offset]*0x1000000)+
((this[offset+1]<<16)|(this[offset+2]<<8)|this[offset+3])}
Buffer.prototype.readIntLE=function readIntLE(offset,byteLength,noAssert){offset=offset|0
byteLength=byteLength|0
if(!noAssert)checkOffset(offset,byteLength,this.length)
var val=this[offset]
var mul=1
var i=0
while(++i<byteLength&&(mul*=0x100)){val+=this[offset+i]*mul}
mul*=0x80
if(val>=mul)val-=Math.pow(2,8*byteLength)
return val}
Buffer.prototype.readIntBE=function readIntBE(offset,byteLength,noAssert){offset=offset|0
byteLength=byteLength|0
if(!noAssert)checkOffset(offset,byteLength,this.length)
var i=byteLength
var mul=1
var val=this[offset+--i]
while(i>0&&(mul*=0x100)){val+=this[offset+--i]*mul}
mul*=0x80
if(val>=mul)val-=Math.pow(2,8*byteLength)
return val}
Buffer.prototype.readInt8=function readInt8(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length)
if(!(this[offset]&0x80))return(this[offset])
return((0xff-this[offset]+1)*-1)}
Buffer.prototype.readInt16LE=function readInt16LE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length)
var val=this[offset]|(this[offset+1]<<8)
return(val&0x8000)?val|0xFFFF0000:val}
Buffer.prototype.readInt16BE=function readInt16BE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length)
var val=this[offset+1]|(this[offset]<<8)
return(val&0x8000)?val|0xFFFF0000:val}
Buffer.prototype.readInt32LE=function readInt32LE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length)
return(this[offset])|(this[offset+1]<<8)|(this[offset+2]<<16)|(this[offset+3]<<24)}
Buffer.prototype.readInt32BE=function readInt32BE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length)
return(this[offset]<<24)|(this[offset+1]<<16)|(this[offset+2]<<8)|(this[offset+3])}
Buffer.prototype.readFloatLE=function readFloatLE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length)
return ieee754.read(this,offset,true,23,4)}
Buffer.prototype.readFloatBE=function readFloatBE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length)
return ieee754.read(this,offset,false,23,4)}
Buffer.prototype.readDoubleLE=function readDoubleLE(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length)
return ieee754.read(this,offset,true,52,8)}
Buffer.prototype.readDoubleBE=function readDoubleBE(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length)
return ieee754.read(this,offset,false,52,8)}
function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError('"buffer" argument must be a Buffer instance')
if(value>max||value<min)throw new RangeError('"value" argument is out of bounds')
if(offset+ext>buf.length)throw new RangeError('Index out of range')}
Buffer.prototype.writeUIntLE=function writeUIntLE(value,offset,byteLength,noAssert){value=+value
offset=offset|0
byteLength=byteLength|0
if(!noAssert){var maxBytes=Math.pow(2,8*byteLength)-1
checkInt(this,value,offset,byteLength,maxBytes,0)}
var mul=1
var i=0
this[offset]=value&0xFF
while(++i<byteLength&&(mul*=0x100)){this[offset+i]=(value/mul)&0xFF}
return offset+byteLength}
Buffer.prototype.writeUIntBE=function writeUIntBE(value,offset,byteLength,noAssert){value=+value
offset=offset|0
byteLength=byteLength|0
if(!noAssert){var maxBytes=Math.pow(2,8*byteLength)-1
checkInt(this,value,offset,byteLength,maxBytes,0)}
var i=byteLength-1
var mul=1
this[offset+i]=value&0xFF
while(--i>=0&&(mul*=0x100)){this[offset+i]=(value/mul)&0xFF}
return offset+byteLength}
Buffer.prototype.writeUInt8=function writeUInt8(value,offset,noAssert){value=+value
offset=offset|0
if(!noAssert)checkInt(this,value,offset,1,0xff,0)
if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value)
this[offset]=(value&0xff)
return offset+1}
function objectWriteUInt16(buf,value,offset,littleEndian){if(value<0)value=0xffff+value+1
for(var i=0,j=Math.min(buf.length-offset,2);i<j;++i){buf[offset+i]=(value&(0xff<<(8*(littleEndian?i:1-i))))>>>(littleEndian?i:1-i)*8}}
Buffer.prototype.writeUInt16LE=function writeUInt16LE(value,offset,noAssert){value=+value
offset=offset|0
if(!noAssert)checkInt(this,value,offset,2,0xffff,0)
if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=(value&0xff)
this[offset+1]=(value>>>8)}else{objectWriteUInt16(this,value,offset,true)}
return offset+2}
Buffer.prototype.writeUInt16BE=function writeUInt16BE(value,offset,noAssert){value=+value
offset=offset|0
if(!noAssert)checkInt(this,value,offset,2,0xffff,0)
if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=(value>>>8)
this[offset+1]=(value&0xff)}else{objectWriteUInt16(this,value,offset,false)}
return offset+2}
function objectWriteUInt32(buf,value,offset,littleEndian){if(value<0)value=0xffffffff+value+1
for(var i=0,j=Math.min(buf.length-offset,4);i<j;++i){buf[offset+i]=(value>>>(littleEndian?i:3-i)*8)&0xff}}
Buffer.prototype.writeUInt32LE=function writeUInt32LE(value,offset,noAssert){value=+value
offset=offset|0
if(!noAssert)checkInt(this,value,offset,4,0xffffffff,0)
if(Buffer.TYPED_ARRAY_SUPPORT){this[offset+3]=(value>>>24)
this[offset+2]=(value>>>16)
this[offset+1]=(value>>>8)
this[offset]=(value&0xff)}else{objectWriteUInt32(this,value,offset,true)}
return offset+4}
Buffer.prototype.writeUInt32BE=function writeUInt32BE(value,offset,noAssert){value=+value
offset=offset|0
if(!noAssert)checkInt(this,value,offset,4,0xffffffff,0)
if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=(value>>>24)
this[offset+1]=(value>>>16)
this[offset+2]=(value>>>8)
this[offset+3]=(value&0xff)}else{objectWriteUInt32(this,value,offset,false)}
return offset+4}
Buffer.prototype.writeIntLE=function writeIntLE(value,offset,byteLength,noAssert){value=+value
offset=offset|0
if(!noAssert){var limit=Math.pow(2,8*byteLength-1)
checkInt(this,value,offset,byteLength,limit-1,-limit)}
var i=0
var mul=1
var sub=0
this[offset]=value&0xFF
while(++i<byteLength&&(mul*=0x100)){if(value<0&&sub===0&&this[offset+i-1]!==0){sub=1}
this[offset+i]=((value/mul)>>0)-sub&0xFF}
return offset+byteLength}
Buffer.prototype.writeIntBE=function writeIntBE(value,offset,byteLength,noAssert){value=+value
offset=offset|0
if(!noAssert){var limit=Math.pow(2,8*byteLength-1)
checkInt(this,value,offset,byteLength,limit-1,-limit)}
var i=byteLength-1
var mul=1
var sub=0
this[offset+i]=value&0xFF
while(--i>=0&&(mul*=0x100)){if(value<0&&sub===0&&this[offset+i+1]!==0){sub=1}
this[offset+i]=((value/mul)>>0)-sub&0xFF}
return offset+byteLength}
Buffer.prototype.writeInt8=function writeInt8(value,offset,noAssert){value=+value
offset=offset|0
if(!noAssert)checkInt(this,value,offset,1,0x7f,-0x80)
if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value)
if(value<0)value=0xff+value+1
this[offset]=(value&0xff)
return offset+1}
Buffer.prototype.writeInt16LE=function writeInt16LE(value,offset,noAssert){value=+value
offset=offset|0
if(!noAssert)checkInt(this,value,offset,2,0x7fff,-0x8000)
if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=(value&0xff)
this[offset+1]=(value>>>8)}else{objectWriteUInt16(this,value,offset,true)}
return offset+2}
Buffer.prototype.writeInt16BE=function writeInt16BE(value,offset,noAssert){value=+value
offset=offset|0
if(!noAssert)checkInt(this,value,offset,2,0x7fff,-0x8000)
if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=(value>>>8)
this[offset+1]=(value&0xff)}else{objectWriteUInt16(this,value,offset,false)}
return offset+2}
Buffer.prototype.writeInt32LE=function writeInt32LE(value,offset,noAssert){value=+value
offset=offset|0
if(!noAssert)checkInt(this,value,offset,4,0x7fffffff,-0x80000000)
if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=(value&0xff)
this[offset+1]=(value>>>8)
this[offset+2]=(value>>>16)
this[offset+3]=(value>>>24)}else{objectWriteUInt32(this,value,offset,true)}
return offset+4}
Buffer.prototype.writeInt32BE=function writeInt32BE(value,offset,noAssert){value=+value
offset=offset|0
if(!noAssert)checkInt(this,value,offset,4,0x7fffffff,-0x80000000)
if(value<0)value=0xffffffff+value+1
if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=(value>>>24)
this[offset+1]=(value>>>16)
this[offset+2]=(value>>>8)
this[offset+3]=(value&0xff)}else{objectWriteUInt32(this,value,offset,false)}
return offset+4}
function checkIEEE754(buf,value,offset,ext,max,min){if(offset+ext>buf.length)throw new RangeError('Index out of range')
if(offset<0)throw new RangeError('Index out of range')}
function writeFloat(buf,value,offset,littleEndian,noAssert){if(!noAssert){checkIEEE754(buf,value,offset,4,3.4028234663852886e+38,-3.4028234663852886e+38)}
ieee754.write(buf,value,offset,littleEndian,23,4)
return offset+4}
Buffer.prototype.writeFloatLE=function writeFloatLE(value,offset,noAssert){return writeFloat(this,value,offset,true,noAssert)}
Buffer.prototype.writeFloatBE=function writeFloatBE(value,offset,noAssert){return writeFloat(this,value,offset,false,noAssert)}
function writeDouble(buf,value,offset,littleEndian,noAssert){if(!noAssert){checkIEEE754(buf,value,offset,8,1.7976931348623157E+308,-1.7976931348623157E+308)}
ieee754.write(buf,value,offset,littleEndian,52,8)
return offset+8}
Buffer.prototype.writeDoubleLE=function writeDoubleLE(value,offset,noAssert){return writeDouble(this,value,offset,true,noAssert)}
Buffer.prototype.writeDoubleBE=function writeDoubleBE(value,offset,noAssert){return writeDouble(this,value,offset,false,noAssert)}
Buffer.prototype.copy=function copy(target,targetStart,start,end){if(!start)start=0
if(!end&&end!==0)end=this.length
if(targetStart>=target.length)targetStart=target.length
if(!targetStart)targetStart=0
if(end>0&&end<start)end=start
if(end===start)return 0
if(target.length===0||this.length===0)return 0
if(targetStart<0){throw new RangeError('targetStart out of bounds')}
if(start<0||start>=this.length)throw new RangeError('sourceStart out of bounds')
if(end<0)throw new RangeError('sourceEnd out of bounds')
if(end>this.length)end=this.length
if(target.length-targetStart<end-start){end=target.length-targetStart+start}
var len=end-start
var i
if(this===target&&start<targetStart&&targetStart<end){for(i=len-1;i>=0;--i){target[i+targetStart]=this[i+start]}}else if(len<1000||!Buffer.TYPED_ARRAY_SUPPORT){for(i=0;i<len;++i){target[i+targetStart]=this[i+start]}}else{Uint8Array.prototype.set.call(target,this.subarray(start,start+len),targetStart)}
return len}
Buffer.prototype.fill=function fill(val,start,end,encoding){if(typeof val==='string'){if(typeof start==='string'){encoding=start
start=0
end=this.length}else if(typeof end==='string'){encoding=end
end=this.length}
if(val.length===1){var code=val.charCodeAt(0)
if(code<256){val=code}}
if(encoding!==undefined&&typeof encoding!=='string'){throw new TypeError('encoding must be a string')}
if(typeof encoding==='string'&&!Buffer.isEncoding(encoding)){throw new TypeError('Unknown encoding: '+encoding)}}else if(typeof val==='number'){val=val&255}
if(start<0||this.length<start||this.length<end){throw new RangeError('Out of range index')}
if(end<=start){return this}
start=start>>>0
end=end===undefined?this.length:end>>>0
if(!val)val=0
var i
if(typeof val==='number'){for(i=start;i<end;++i){this[i]=val}}else{var bytes=Buffer.isBuffer(val)?val:utf8ToBytes(new Buffer(val,encoding).toString())
var len=bytes.length
for(i=0;i<end-start;++i){this[i+start]=bytes[i%len]}}
return this}
var INVALID_BASE64_RE=/[^+\/0-9A-Za-z-_]/g
function base64clean(str){str=stringtrim(str).replace(INVALID_BASE64_RE,'')
if(str.length<2)return''
while(str.length%4!==0){str=str+'='}
return str}
function stringtrim(str){if(str.trim)return str.trim()
return str.replace(/^\s+|\s+$/g,'')}
function toHex(n){if(n<16)return'0'+n.toString(16)
return n.toString(16)}
function utf8ToBytes(string,units){units=units||Infinity
var codePoint
var length=string.length
var leadSurrogate=null
var bytes=[]
for(var i=0;i<length;++i){codePoint=string.charCodeAt(i)
if(codePoint>0xD7FF&&codePoint<0xE000){if(!leadSurrogate){if(codePoint>0xDBFF){if((units-=3)>-1)bytes.push(0xEF,0xBF,0xBD)
continue}else if(i+1===length){if((units-=3)>-1)bytes.push(0xEF,0xBF,0xBD)
continue}
leadSurrogate=codePoint
continue}
if(codePoint<0xDC00){if((units-=3)>-1)bytes.push(0xEF,0xBF,0xBD)
leadSurrogate=codePoint
continue}
codePoint=(leadSurrogate-0xD800<<10|codePoint-0xDC00)+0x10000}else if(leadSurrogate){if((units-=3)>-1)bytes.push(0xEF,0xBF,0xBD)}
leadSurrogate=null
if(codePoint<0x80){if((units-=1)<0)break
bytes.push(codePoint)}else if(codePoint<0x800){if((units-=2)<0)break
bytes.push(codePoint>>0x6|0xC0,codePoint&0x3F|0x80)}else if(codePoint<0x10000){if((units-=3)<0)break
bytes.push(codePoint>>0xC|0xE0,codePoint>>0x6&0x3F|0x80,codePoint&0x3F|0x80)}else if(codePoint<0x110000){if((units-=4)<0)break
bytes.push(codePoint>>0x12|0xF0,codePoint>>0xC&0x3F|0x80,codePoint>>0x6&0x3F|0x80,codePoint&0x3F|0x80)}else{throw new Error('Invalid code point')}}
return bytes}
function asciiToBytes(str){var byteArray=[]
for(var i=0;i<str.length;++i){byteArray.push(str.charCodeAt(i)&0xFF)}
return byteArray}
function utf16leToBytes(str,units){var c,hi,lo
var byteArray=[]
for(var i=0;i<str.length;++i){if((units-=2)<0)break
c=str.charCodeAt(i)
hi=c>>8
lo=c%256
byteArray.push(lo)
byteArray.push(hi)}
return byteArray}
function base64ToBytes(str){return base64.toByteArray(base64clean(str))}
function blitBuffer(src,dst,offset,length){for(var i=0;i<length;++i){if((i+offset>=dst.length)||(i>=src.length))break
dst[i+offset]=src[i]}
return i}
function isnan(val){return val!==val}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"base64-js":198,"ieee754":202,"isarray":203}],201:[function(require,module,exports){function EventEmitter(){this._events=this._events||{};this._maxListeners=this._maxListeners||undefined;}
module.exports=EventEmitter;EventEmitter.EventEmitter=EventEmitter;EventEmitter.prototype._events=undefined;EventEmitter.prototype._maxListeners=undefined;EventEmitter.defaultMaxListeners=10;EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||n<0||isNaN(n))
throw TypeError('n must be a positive number');this._maxListeners=n;return this;};EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(!this._events)
this._events={};if(type==='error'){if(!this._events.error||(isObject(this._events.error)&&!this._events.error.length)){er=arguments[1];if(er instanceof Error){throw er;}else{var err=new Error('Uncaught, unspecified "error" event. ('+er+')');err.context=er;throw err;}}}
handler=this._events[type];if(isUndefined(handler))
return false;if(isFunction(handler)){switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:args=Array.prototype.slice.call(arguments,1);handler.apply(this,args);}}else if(isObject(handler)){args=Array.prototype.slice.call(arguments,1);listeners=handler.slice();len=listeners.length;for(i=0;i<len;i++)
listeners[i].apply(this,args);}
return true;};EventEmitter.prototype.addListener=function(type,listener){var m;if(!isFunction(listener))
throw TypeError('listener must be a function');if(!this._events)
this._events={};if(this._events.newListener)
this.emit('newListener',type,isFunction(listener.listener)?listener.listener:listener);if(!this._events[type])
this._events[type]=listener;else if(isObject(this._events[type]))
this._events[type].push(listener);else
this._events[type]=[this._events[type],listener];if(isObject(this._events[type])&&!this._events[type].warned){if(!isUndefined(this._maxListeners)){m=this._maxListeners;}else{m=EventEmitter.defaultMaxListeners;}
if(m&&m>0&&this._events[type].length>m){this._events[type].warned=true;console.error('(node) warning: possible EventEmitter memory '+'leak detected. %d listeners added. '+'Use emitter.setMaxListeners() to increase limit.',this._events[type].length);if(typeof console.trace==='function'){console.trace();}}}
return this;};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.once=function(type,listener){if(!isFunction(listener))
throw TypeError('listener must be a function');var fired=false;function g(){this.removeListener(type,g);if(!fired){fired=true;listener.apply(this,arguments);}}
g.listener=listener;this.on(type,g);return this;};EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))
throw TypeError('listener must be a function');if(!this._events||!this._events[type])
return this;list=this._events[type];length=list.length;position=-1;if(list===listener||(isFunction(list.listener)&&list.listener===listener)){delete this._events[type];if(this._events.removeListener)
this.emit('removeListener',type,listener);}else if(isObject(list)){for(i=length;i-->0;){if(list[i]===listener||(list[i].listener&&list[i].listener===listener)){position=i;break;}}
if(position<0)
return this;if(list.length===1){list.length=0;delete this._events[type];}else{list.splice(position,1);}
if(this._events.removeListener)
this.emit('removeListener',type,listener);}
return this;};EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)
return this;if(!this._events.removeListener){if(arguments.length===0)
this._events={};else if(this._events[type])
delete this._events[type];return this;}
if(arguments.length===0){for(key in this._events){if(key==='removeListener')continue;this.removeAllListeners(key);}
this.removeAllListeners('removeListener');this._events={};return this;}
listeners=this._events[type];if(isFunction(listeners)){this.removeListener(type,listeners);}else if(listeners){while(listeners.length)
this.removeListener(type,listeners[listeners.length-1]);}
delete this._events[type];return this;};EventEmitter.prototype.listeners=function(type){var ret;if(!this._events||!this._events[type])
ret=[];else if(isFunction(this._events[type]))
ret=[this._events[type]];else
ret=this._events[type].slice();return ret;};EventEmitter.prototype.listenerCount=function(type){if(this._events){var evlistener=this._events[type];if(isFunction(evlistener))
return 1;else if(evlistener)
return evlistener.length;}
return 0;};EventEmitter.listenerCount=function(emitter,type){return emitter.listenerCount(type);};function isFunction(arg){return typeof arg==='function';}
function isNumber(arg){return typeof arg==='number';}
function isObject(arg){return typeof arg==='object'&&arg!==null;}
function isUndefined(arg){return arg===void 0;}},{}],202:[function(require,module,exports){exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m
var eLen=nBytes*8-mLen-1
var eMax=(1<<eLen)-1
var eBias=eMax>>1
var nBits=-7
var i=isLE?(nBytes-1):0
var d=isLE?-1:1
var s=buffer[offset+i]
i+=d
e=s&((1<<(-nBits))-1)
s>>=(-nBits)
nBits+=eLen
for(;nBits>0;e=e*256+buffer[offset+i],i+=d,nBits-=8){}
m=e&((1<<(-nBits))-1)
e>>=(-nBits)
nBits+=mLen
for(;nBits>0;m=m*256+buffer[offset+i],i+=d,nBits-=8){}
if(e===0){e=1-eBias}else if(e===eMax){return m?NaN:((s?-1:1)*Infinity)}else{m=m+Math.pow(2,mLen)
e=e-eBias}
return(s?-1:1)*m*Math.pow(2,e-mLen)}
exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c
var eLen=nBytes*8-mLen-1
var eMax=(1<<eLen)-1
var eBias=eMax>>1
var rt=(mLen===23?Math.pow(2,-24)-Math.pow(2,-77):0)
var i=isLE?0:(nBytes-1)
var d=isLE?1:-1
var s=value<0||(value===0&&1/value<0)?1:0
value=Math.abs(value)
if(isNaN(value)||value===Infinity){m=isNaN(value)?1:0
e=eMax}else{e=Math.floor(Math.log(value)/Math.LN2)
if(value*(c=Math.pow(2,-e))<1){e--
c*=2}
if(e+eBias>=1){value+=rt/c}else{value+=rt*Math.pow(2,1-eBias)}
if(value*c>=2){e++
c/=2}
if(e+eBias>=eMax){m=0
e=eMax}else if(e+eBias>=1){m=(value*c-1)*Math.pow(2,mLen)
e=e+eBias}else{m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen)
e=0}}
for(;mLen>=8;buffer[offset+i]=m&0xff,i+=d,m/=256,mLen-=8){}
e=(e<<mLen)|m
eLen+=mLen
for(;eLen>0;buffer[offset+i]=e&0xff,i+=d,e/=256,eLen-=8){}
buffer[offset+i-d]|=s*128}},{}],203:[function(require,module,exports){var toString={}.toString;module.exports=Array.isArray||function(arr){return toString.call(arr)=='[object Array]';};},{}],204:[function(require,module,exports){(function(process){function normalizeArray(parts,allowAboveRoot){var up=0;for(var i=parts.length-1;i>=0;i--){var last=parts[i];if(last==='.'){parts.splice(i,1);}else if(last==='..'){parts.splice(i,1);up++;}else if(up){parts.splice(i,1);up--;}}
if(allowAboveRoot){for(;up--;up){parts.unshift('..');}}
return parts;}
var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;var splitPath=function(filename){return splitPathRe.exec(filename).slice(1);};exports.resolve=function(){var resolvedPath='',resolvedAbsolute=false;for(var i=arguments.length-1;i>=-1&&!resolvedAbsolute;i--){var path=(i>=0)?arguments[i]:process.cwd();if(typeof path!=='string'){throw new TypeError('Arguments to path.resolve must be strings');}else if(!path){continue;}
resolvedPath=path+'/'+resolvedPath;resolvedAbsolute=path.charAt(0)==='/';}
resolvedPath=normalizeArray(filter(resolvedPath.split('/'),function(p){return!!p;}),!resolvedAbsolute).join('/');return((resolvedAbsolute?'/':'')+resolvedPath)||'.';};exports.normalize=function(path){var isAbsolute=exports.isAbsolute(path),trailingSlash=substr(path,-1)==='/';path=normalizeArray(filter(path.split('/'),function(p){return!!p;}),!isAbsolute).join('/');if(!path&&!isAbsolute){path='.';}
if(path&&trailingSlash){path+='/';}
return(isAbsolute?'/':'')+path;};exports.isAbsolute=function(path){return path.charAt(0)==='/';};exports.join=function(){var paths=Array.prototype.slice.call(arguments,0);return exports.normalize(filter(paths,function(p,index){if(typeof p!=='string'){throw new TypeError('Arguments to path.join must be strings');}
return p;}).join('/'));};exports.relative=function(from,to){from=exports.resolve(from).substr(1);to=exports.resolve(to).substr(1);function trim(arr){var start=0;for(;start<arr.length;start++){if(arr[start]!=='')break;}
var end=arr.length-1;for(;end>=0;end--){if(arr[end]!=='')break;}
if(start>end)return[];return arr.slice(start,end-start+1);}
var fromParts=trim(from.split('/'));var toParts=trim(to.split('/'));var length=Math.min(fromParts.length,toParts.length);var samePartsLength=length;for(var i=0;i<length;i++){if(fromParts[i]!==toParts[i]){samePartsLength=i;break;}}
var outputParts=[];for(var i=samePartsLength;i<fromParts.length;i++){outputParts.push('..');}
outputParts=outputParts.concat(toParts.slice(samePartsLength));return outputParts.join('/');};exports.sep='/';exports.delimiter=':';exports.dirname=function(path){var result=splitPath(path),root=result[0],dir=result[1];if(!root&&!dir){return'.';}
if(dir){dir=dir.substr(0,dir.length-1);}
return root+dir;};exports.basename=function(path,ext){var f=splitPath(path)[2];if(ext&&f.substr(-1*ext.length)===ext){f=f.substr(0,f.length-ext.length);}
return f;};exports.extname=function(path){return splitPath(path)[3];};function filter(xs,f){if(xs.filter)return xs.filter(f);var res=[];for(var i=0;i<xs.length;i++){if(f(xs[i],i,xs))res.push(xs[i]);}
return res;}
var substr='ab'.substr(-1)==='b'?function(str,start,len){return str.substr(start,len)}:function(str,start,len){if(start<0)start=str.length+start;return str.substr(start,len);};}).call(this,require('_process'))},{"_process":205}],205:[function(require,module,exports){var process=module.exports={};var cachedSetTimeout;var cachedClearTimeout;function defaultSetTimout(){throw new Error('setTimeout has not been defined');}
function defaultClearTimeout(){throw new Error('clearTimeout has not been defined');}
(function(){try{if(typeof setTimeout==='function'){cachedSetTimeout=setTimeout;}else{cachedSetTimeout=defaultSetTimout;}}catch(e){cachedSetTimeout=defaultSetTimout;}
try{if(typeof clearTimeout==='function'){cachedClearTimeout=clearTimeout;}else{cachedClearTimeout=defaultClearTimeout;}}catch(e){cachedClearTimeout=defaultClearTimeout;}}())
function runTimeout(fun){if(cachedSetTimeout===setTimeout){return setTimeout(fun,0);}
if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout){cachedSetTimeout=setTimeout;return setTimeout(fun,0);}
try{return cachedSetTimeout(fun,0);}catch(e){try{return cachedSetTimeout.call(null,fun,0);}catch(e){return cachedSetTimeout.call(this,fun,0);}}}
function runClearTimeout(marker){if(cachedClearTimeout===clearTimeout){return clearTimeout(marker);}
if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout){cachedClearTimeout=clearTimeout;return clearTimeout(marker);}
try{return cachedClearTimeout(marker);}catch(e){try{return cachedClearTimeout.call(null,marker);}catch(e){return cachedClearTimeout.call(this,marker);}}}
var queue=[];var draining=false;var currentQueue;var queueIndex=-1;function cleanUpNextTick(){if(!draining||!currentQueue){return;}
draining=false;if(currentQueue.length){queue=currentQueue.concat(queue);}else{queueIndex=-1;}
if(queue.length){drainQueue();}}
function drainQueue(){if(draining){return;}
var timeout=runTimeout(cleanUpNextTick);draining=true;var len=queue.length;while(len){currentQueue=queue;queue=[];while(++queueIndex<len){if(currentQueue){currentQueue[queueIndex].run();}}
queueIndex=-1;len=queue.length;}
currentQueue=null;draining=false;runClearTimeout(timeout);}
process.nextTick=function(fun){var args=new Array(arguments.length-1);if(arguments.length>1){for(var i=1;i<arguments.length;i++){args[i-1]=arguments[i];}}
queue.push(new Item(fun,args));if(queue.length===1&&!draining){runTimeout(drainQueue);}};function Item(fun,array){this.fun=fun;this.array=array;}
Item.prototype.run=function(){this.fun.apply(null,this.array);};process.title='browser';process.browser=true;process.env={};process.argv=[];process.version='';process.versions={};function noop(){}
process.on=noop;process.addListener=noop;process.once=noop;process.off=noop;process.removeListener=noop;process.removeAllListeners=noop;process.emit=noop;process.binding=function(name){throw new Error('process.binding is not supported');};process.cwd=function(){return'/'};process.chdir=function(dir){throw new Error('process.chdir is not supported');};process.umask=function(){return 0;};},{}],206:[function(require,module,exports){window.requestFileSystem=window.requestFileSystem||window.webkitRequestFileSystem;WebInspector.TempFile=function()
{this._fileEntry=null;this._writer=null;}
WebInspector.TempFile.create=function(dirPath,name)
{var file=new WebInspector.TempFile();function requestTempFileSystem()
{return new Promise(window.requestFileSystem.bind(window,window.TEMPORARY,10));}
function getDirectoryEntry(fs)
{return new Promise(fs.root.getDirectory.bind(fs.root,dirPath,{create:true}));}
function getFileEntry(dir)
{return new Promise(dir.getFile.bind(dir,name,{create:true}));}
function createFileWriter(fileEntry)
{file._fileEntry=fileEntry;return new Promise(fileEntry.createWriter.bind(fileEntry));}
function truncateFile(writer)
{if(!writer.length){file._writer=writer;return Promise.resolve(file);}
function truncate(fulfill,reject)
{writer.onwriteend=fulfill;writer.onerror=reject;writer.truncate(0);}
function didTruncate()
{file._writer=writer;writer.onwriteend=null;writer.onerror=null;return Promise.resolve(file);}
function onTruncateError(e)
{writer.onwriteend=null;writer.onerror=null;throw e;}
return new Promise(truncate).then(didTruncate,onTruncateError);}
return WebInspector.TempFile.ensureTempStorageCleared().then(requestTempFileSystem).then(getDirectoryEntry).then(getFileEntry).then(createFileWriter).then(truncateFile);}
WebInspector.TempFile.prototype={write:function(strings,callback)
{var blob=new Blob(strings,{type:"text/plain"});this._writer.onerror=function(e)
{WebInspector.console.error("Failed to write into a temp file: "+e.target.error.message);callback(-1);}
this._writer.onwriteend=function(e)
{callback(e.target.length);}
this._writer.write(blob);},finishWriting:function()
{this._writer=null;},read:function(callback)
{this.readRange(undefined,undefined,callback);},readRange:function(startOffset,endOffset,callback)
{function didGetFile(file)
{var reader=new FileReader();if(typeof startOffset==="number"||typeof endOffset==="number")
file=file.slice((startOffset),(endOffset));reader.onloadend=function(e)
{callback((this.result));};reader.onerror=function(error)
{WebInspector.console.error("Failed to read from temp file: "+error.message);};reader.readAsText(file);}
function didFailToGetFile(error)
{WebInspector.console.error("Failed to load temp file: "+error.message);callback(null);}
this._fileEntry.file(didGetFile,didFailToGetFile);},copyToOutputStream:function(outputStream,delegate)
{function didGetFile(file)
{var reader=new WebInspector.ChunkedFileReader(file,10*1000*1000,delegate);reader.start(outputStream);}
function didFailToGetFile(error)
{WebInspector.console.error("Failed to load temp file: "+error.message);outputStream.close();}
this._fileEntry.file(didGetFile,didFailToGetFile);},remove:function()
{if(this._fileEntry)
this._fileEntry.remove(function(){});}}
WebInspector.DeferredTempFile=function(dirPath,name)
{this._chunks=[];this._tempFile=null;this._isWriting=false;this._finishCallback=null;this._finishedWriting=false;this._callsPendingOpen=[];this._pendingReads=[];WebInspector.TempFile.create(dirPath,name).then(this._didCreateTempFile.bind(this),this._failedToCreateTempFile.bind(this));}
WebInspector.DeferredTempFile.prototype={write:function(strings,callback)
{if(this._finishCallback)
throw new Error("No writes are allowed after close.");this._chunks.push({strings:strings,callback:callback||null});if(this._tempFile&&!this._isWriting)
this._writeNextChunk();},finishWriting:function(callback)
{this._finishCallback=callback;if(this._finishedWriting)
callback(this._tempFile);else if(!this._isWriting&&!this._chunks.length)
this._notifyFinished();},_failedToCreateTempFile:function(e)
{WebInspector.console.error("Failed to create temp file "+e.code+" : "+e.message);this._notifyFinished();},_didCreateTempFile:function(tempFile)
{this._tempFile=tempFile;var callsPendingOpen=this._callsPendingOpen;this._callsPendingOpen=null;for(var i=0;i<callsPendingOpen.length;++i)
callsPendingOpen[i]();if(this._chunks.length)
this._writeNextChunk();},_writeNextChunk:function()
{if(!this._tempFile)
return;var chunk=this._chunks.shift();this._isWriting=true;this._tempFile.write((chunk.strings),this._didWriteChunk.bind(this,chunk.callback));},_didWriteChunk:function(callback,size)
{this._isWriting=false;if(size===-1){this._tempFile=null;this._notifyFinished();return;}
if(callback)
callback(size);if(this._chunks.length)
this._writeNextChunk();else if(this._finishCallback)
this._notifyFinished();},_notifyFinished:function()
{this._finishedWriting=true;if(this._tempFile)
this._tempFile.finishWriting();var chunks=this._chunks;this._chunks=[];for(var i=0;i<chunks.length;++i){if(chunks[i].callback)
chunks[i].callback(-1);}
if(this._finishCallback)
this._finishCallback(this._tempFile);var pendingReads=this._pendingReads;this._pendingReads=[];for(var i=0;i<pendingReads.length;++i)
pendingReads[i]();},readRange:function(startOffset,endOffset,callback)
{if(!this._finishedWriting){this._pendingReads.push(this.readRange.bind(this,startOffset,endOffset,callback));return;}
if(!this._tempFile){callback(null);return;}
this._tempFile.readRange(startOffset,endOffset,callback);},copyToOutputStream:function(outputStream,delegate)
{if(!this._finishedWriting){this._pendingReads.push(this.copyToOutputStream.bind(this,outputStream,delegate));return;}
if(this._tempFile)
this._tempFile.copyToOutputStream(outputStream,delegate);},remove:function()
{if(this._callsPendingOpen){this._callsPendingOpen.push(this.remove.bind(this));return;}
if(this._tempFile)
this._tempFile.remove();this._tempFile=null;}}
WebInspector.TempFile._clearTempStorage=function(fulfill,reject)
{function handleError(event)
{WebInspector.console.error(WebInspector.UIString("Failed to clear temp storage: %s",event.data));reject(event.data);}
function handleMessage(event)
{if(event.data.type==="tempStorageCleared"){if(event.data.error)
WebInspector.console.error(event.data.error);else
fulfill(undefined);return;}
reject(event.data);}
try{var worker=new WebInspector.Worker("temp_storage_shared_worker","TempStorageCleaner");worker.onerror=handleError;worker.onmessage=handleMessage;}catch(e){if(e.name==="URLMismatchError")
console.log("Shared worker wasn't started due to url difference. "+e);else
throw e;}}
WebInspector.TempFile.ensureTempStorageCleared=function()
{if(!WebInspector.TempFile._storageCleanerPromise)
WebInspector.TempFile._storageCleanerPromise=new Promise(WebInspector.TempFile._clearTempStorage);return WebInspector.TempFile._storageCleanerPromise;}
WebInspector.TempFileBackingStorage=function(dirName)
{this._dirName=dirName;this.reset();}
WebInspector.TempFileBackingStorage.Chunk;WebInspector.TempFileBackingStorage.prototype={appendString:function(string)
{this._strings.push(string);this._stringsLength+=string.length;var flushStringLength=10*1024*1024;if(this._stringsLength>flushStringLength)
this._flush(false);},appendAccessibleString:function(string)
{this._flush(false);this._strings.push(string);var chunk=(this._flush(true));function readString(chunk,file)
{if(chunk.string)
return(Promise.resolve(chunk.string));console.assert(chunk.endOffset);if(!chunk.endOffset)
return Promise.reject("Nor string nor offset to the string in the file were found.");function readRange(fulfill,reject)
{file.readRange(chunk.startOffset,chunk.endOffset,fulfill);}
return new Promise(readRange);}
return readString.bind(null,chunk,this._file);},_flush:function(createChunk)
{if(!this._strings.length)
return null;var chunk=null;if(createChunk){console.assert(this._strings.length===1);chunk={string:this._strings[0],startOffset:0,endOffset:0};}
function didWrite(chunk,fileSize)
{if(fileSize===-1)
return;if(chunk){chunk.startOffset=this._fileSize;chunk.endOffset=fileSize;chunk.string=null;}
this._fileSize=fileSize;}
this._file.write(this._strings,didWrite.bind(this,chunk));this._strings=[];this._stringsLength=0;return chunk;},finishWriting:function()
{this._flush(false);this._file.finishWriting(function(){});},reset:function()
{if(this._file)
this._file.remove();this._file=new WebInspector.DeferredTempFile(this._dirName,String(Date.now()));this._strings=[];this._stringsLength=0;this._fileSize=0;},writeToStream:function(outputStream,delegate)
{this._file.copyToOutputStream(outputStream,delegate);}}},{}],207:[function(require,module,exports){WebInspector.Color=function(rgba,format,originalText)
{this._rgba=rgba;this._originalText=originalText||null;this._originalTextIsValid=!!this._originalText;this._format=format;if(typeof this._rgba[3]==="undefined")
this._rgba[3]=1;for(var i=0;i<4;++i){if(this._rgba[i]<0){this._rgba[i]=0;this._originalTextIsValid=false;}
if(this._rgba[i]>1){this._rgba[i]=1;this._originalTextIsValid=false;}}}
WebInspector.Color.Regex=/((?:rgb|hsl)a?\([^)]+\)|#[0-9a-fA-F]{6}|#[0-9a-fA-F]{3}|\b[a-zA-Z]+\b(?!-))/g;WebInspector.Color.Format={Original:"original",Nickname:"nickname",HEX:"hex",ShortHEX:"shorthex",RGB:"rgb",RGBA:"rgba",HSL:"hsl",HSLA:"hsla"}
WebInspector.Color.parse=function(text)
{var value=text.toLowerCase().replace(/\s+/g,"");var simple=/^(?:#([0-9a-f]{3}|[0-9a-f]{6})|rgb\(((?:-?\d+%?,){2}-?\d+%?)\)|(\w+)|hsl\((-?\d+\.?\d*(?:,-?\d+\.?\d*%){2})\))$/i;var match=value.match(simple);if(match){if(match[1]){var hex=match[1].toLowerCase();var format;if(hex.length===3){format=WebInspector.Color.Format.ShortHEX;hex=hex.charAt(0)+hex.charAt(0)+hex.charAt(1)+hex.charAt(1)+hex.charAt(2)+hex.charAt(2);}else
format=WebInspector.Color.Format.HEX;var r=parseInt(hex.substring(0,2),16);var g=parseInt(hex.substring(2,4),16);var b=parseInt(hex.substring(4,6),16);return new WebInspector.Color([r/255,g/255,b/255,1],format,text);}
if(match[2]){var rgbString=match[2].split(/\s*,\s*/);var rgba=[WebInspector.Color._parseRgbNumeric(rgbString[0]),WebInspector.Color._parseRgbNumeric(rgbString[1]),WebInspector.Color._parseRgbNumeric(rgbString[2]),1];return new WebInspector.Color(rgba,WebInspector.Color.Format.RGB,text);}
if(match[3]){var nickname=match[3].toLowerCase();if(nickname in WebInspector.Color.Nicknames){var rgba=WebInspector.Color.Nicknames[nickname];var color=WebInspector.Color.fromRGBA(rgba);color._format=WebInspector.Color.Format.Nickname;color._originalText=text;return color;}
return null;}
if(match[4]){var hslString=match[4].replace(/%/g,"").split(/\s*,\s*/);var hsla=[WebInspector.Color._parseHueNumeric(hslString[0]),WebInspector.Color._parseSatLightNumeric(hslString[1]),WebInspector.Color._parseSatLightNumeric(hslString[2]),1];var rgba=[];WebInspector.Color.hsl2rgb(hsla,rgba);return new WebInspector.Color(rgba,WebInspector.Color.Format.HSL,text);}
return null;}
var advanced=/^(?:rgba\(((?:-?\d+%?,){3}-?(?:\d+|\d*\.\d+))\)|hsla\((-?(?:\d+|\d*\.\d+)(?:,-?(?:\d+|\d*\.\d+)*%){2},-?(?:\d+|\d*\.\d+))\))$/;match=value.match(advanced);if(match){if(match[1]){var rgbaString=match[1].split(/\s*,\s*/);var rgba=[WebInspector.Color._parseRgbNumeric(rgbaString[0]),WebInspector.Color._parseRgbNumeric(rgbaString[1]),WebInspector.Color._parseRgbNumeric(rgbaString[2]),WebInspector.Color._parseAlphaNumeric(rgbaString[3])];return new WebInspector.Color(rgba,WebInspector.Color.Format.RGBA,text);}
if(match[2]){var hslaString=match[2].replace(/%/g,"").split(/\s*,\s*/);var hsla=[WebInspector.Color._parseHueNumeric(hslaString[0]),WebInspector.Color._parseSatLightNumeric(hslaString[1]),WebInspector.Color._parseSatLightNumeric(hslaString[2]),WebInspector.Color._parseAlphaNumeric(hslaString[3])];var rgba=[];WebInspector.Color.hsl2rgb(hsla,rgba);return new WebInspector.Color(rgba,WebInspector.Color.Format.HSLA,text);}}
return null;}
WebInspector.Color.fromRGBA=function(rgba)
{return new WebInspector.Color([rgba[0]/255,rgba[1]/255,rgba[2]/255,rgba[3]],WebInspector.Color.Format.RGBA);}
WebInspector.Color.fromHSVA=function(hsva)
{var rgba=[];WebInspector.Color.hsva2rgba(hsva,rgba);return new WebInspector.Color(rgba,WebInspector.Color.Format.HSLA);}
WebInspector.Color.prototype={format:function()
{return this._format;},hsla:function()
{if(this._hsla)
return this._hsla;var r=this._rgba[0];var g=this._rgba[1];var b=this._rgba[2];var max=Math.max(r,g,b);var min=Math.min(r,g,b);var diff=max-min;var add=max+min;if(min===max)
var h=0;else if(r===max)
var h=((1/6*(g-b)/diff)+1)%1;else if(g===max)
var h=(1/6*(b-r)/diff)+1/3;else
var h=(1/6*(r-g)/diff)+2/3;var l=0.5*add;if(l===0)
var s=0;else if(l===1)
var s=0;else if(l<=0.5)
var s=diff/add;else
var s=diff/(2-add);this._hsla=[h,s,l,this._rgba[3]];return this._hsla;},canonicalHSLA:function()
{var hsla=this.hsla();return[Math.round(hsla[0]*360),Math.round(hsla[1]*100),Math.round(hsla[2]*100),hsla[3]];},hsva:function()
{var hsla=this.hsla();var h=hsla[0];var s=hsla[1];var l=hsla[2];s*=l<0.5?l:1-l;return[h,s!==0?2*s/(l+s):0,(l+s),hsla[3]];},hasAlpha:function()
{return this._rgba[3]!==1;},canBeShortHex:function()
{if(this.hasAlpha())
return false;for(var i=0;i<3;++i){var c=Math.round(this._rgba[i]*255);if(c%17)
return false;}
return true;},asString:function(format)
{if(format===this._format&&this._originalTextIsValid)
return this._originalText;if(!format)
format=this._format;function toRgbValue(value)
{return Math.round(value*255);}
function toHexValue(value)
{var hex=Math.round(value*255).toString(16);return hex.length===1?"0"+hex:hex;}
function toShortHexValue(value)
{return(Math.round(value*255)/17).toString(16);}
switch(format){case WebInspector.Color.Format.Original:return this._originalText;case WebInspector.Color.Format.RGB:if(this.hasAlpha())
return null;return String.sprintf("rgb(%d, %d, %d)",toRgbValue(this._rgba[0]),toRgbValue(this._rgba[1]),toRgbValue(this._rgba[2]));case WebInspector.Color.Format.RGBA:return String.sprintf("rgba(%d, %d, %d, %f)",toRgbValue(this._rgba[0]),toRgbValue(this._rgba[1]),toRgbValue(this._rgba[2]),this._rgba[3]);case WebInspector.Color.Format.HSL:if(this.hasAlpha())
return null;var hsl=this.hsla();return String.sprintf("hsl(%d, %d%, %d%)",Math.round(hsl[0]*360),Math.round(hsl[1]*100),Math.round(hsl[2]*100));case WebInspector.Color.Format.HSLA:var hsla=this.hsla();return String.sprintf("hsla(%d, %d%, %d%, %f)",Math.round(hsla[0]*360),Math.round(hsla[1]*100),Math.round(hsla[2]*100),hsla[3]);case WebInspector.Color.Format.HEX:if(this.hasAlpha())
return null;return String.sprintf("#%s%s%s",toHexValue(this._rgba[0]),toHexValue(this._rgba[1]),toHexValue(this._rgba[2])).toLowerCase();case WebInspector.Color.Format.ShortHEX:if(!this.canBeShortHex())
return null;return String.sprintf("#%s%s%s",toShortHexValue(this._rgba[0]),toShortHexValue(this._rgba[1]),toShortHexValue(this._rgba[2])).toLowerCase();case WebInspector.Color.Format.Nickname:return this.nickname();}
return this._originalText;},rgba:function()
{return this._rgba.slice();},canonicalRGBA:function()
{var rgba=new Array(4);for(var i=0;i<3;++i)
rgba[i]=Math.round(this._rgba[i]*255);rgba[3]=this._rgba[3];return rgba;},nickname:function()
{if(!WebInspector.Color._rgbaToNickname){WebInspector.Color._rgbaToNickname={};for(var nickname in WebInspector.Color.Nicknames){var rgba=WebInspector.Color.Nicknames[nickname];if(rgba.length!==4)
rgba=rgba.concat(1);WebInspector.Color._rgbaToNickname[rgba]=nickname;}}
return WebInspector.Color._rgbaToNickname[this.canonicalRGBA()]||null;},toProtocolRGBA:function()
{var rgba=this.canonicalRGBA();var result={r:rgba[0],g:rgba[1],b:rgba[2]};if(rgba[3]!==1)
result.a=rgba[3];return result;},invert:function()
{var rgba=[];rgba[0]=1-this._rgba[0];rgba[1]=1-this._rgba[1];rgba[2]=1-this._rgba[2];rgba[3]=this._rgba[3];return new WebInspector.Color(rgba,WebInspector.Color.Format.RGBA);},setAlpha:function(alpha)
{var rgba=this._rgba.slice();rgba[3]=alpha;return new WebInspector.Color(rgba,WebInspector.Color.Format.RGBA);}}
WebInspector.Color._parseRgbNumeric=function(value)
{var parsed=parseInt(value,10);if(value.indexOf("%")!==-1)
parsed/=100;else
parsed/=255;return parsed;}
WebInspector.Color._parseHueNumeric=function(value)
{return isNaN(value)?0:(parseFloat(value)/360)%1;}
WebInspector.Color._parseSatLightNumeric=function(value)
{return Math.min(1,parseFloat(value)/100);}
WebInspector.Color._parseAlphaNumeric=function(value)
{return isNaN(value)?0:parseFloat(value);}
WebInspector.Color._hsva2hsla=function(hsva,out_hsla)
{var h=hsva[0];var s=hsva[1];var v=hsva[2];var t=(2-s)*v;if(v===0||s===0)
s=0;else
s*=v/(t<1?t:2-t);out_hsla[0]=h;out_hsla[1]=s;out_hsla[2]=t/2;out_hsla[3]=hsva[3];}
WebInspector.Color.hsl2rgb=function(hsl,out_rgb)
{var h=hsl[0];var s=hsl[1];var l=hsl[2];function hue2rgb(p,q,h)
{if(h<0)
h+=1;else if(h>1)
h-=1;if((h*6)<1)
return p+(q-p)*h*6;else if((h*2)<1)
return q;else if((h*3)<2)
return p+(q-p)*((2/3)-h)*6;else
return p;}
if(s<0)
s=0;if(l<=0.5)
var q=l*(1+s);else
var q=l+s-(l*s);var p=2*l-q;var tr=h+(1/3);var tg=h;var tb=h-(1/3);out_rgb[0]=hue2rgb(p,q,tr);out_rgb[1]=hue2rgb(p,q,tg);out_rgb[2]=hue2rgb(p,q,tb);out_rgb[3]=hsl[3];}
WebInspector.Color.hsva2rgba=function(hsva,out_rgba)
{WebInspector.Color._hsva2hsla(hsva,WebInspector.Color.hsva2rgba._tmpHSLA);WebInspector.Color.hsl2rgb(WebInspector.Color.hsva2rgba._tmpHSLA,out_rgba);for(var i=0;i<WebInspector.Color.hsva2rgba._tmpHSLA.length;i++)
WebInspector.Color.hsva2rgba._tmpHSLA[i]=0;};WebInspector.Color.hsva2rgba._tmpHSLA=[0,0,0,0];WebInspector.Color.luminance=function(rgba)
{var rSRGB=rgba[0];var gSRGB=rgba[1];var bSRGB=rgba[2];var r=rSRGB<=0.03928?rSRGB/12.92:Math.pow(((rSRGB+0.055)/1.055),2.4);var g=gSRGB<=0.03928?gSRGB/12.92:Math.pow(((gSRGB+0.055)/1.055),2.4);var b=bSRGB<=0.03928?bSRGB/12.92:Math.pow(((bSRGB+0.055)/1.055),2.4);return 0.2126*r+0.7152*g+0.0722*b;}
WebInspector.Color.blendColors=function(fgRGBA,bgRGBA,out_blended)
{var alpha=fgRGBA[3];out_blended[0]=((1-alpha)*bgRGBA[0])+(alpha*fgRGBA[0]);out_blended[1]=((1-alpha)*bgRGBA[1])+(alpha*fgRGBA[1]);out_blended[2]=((1-alpha)*bgRGBA[2])+(alpha*fgRGBA[2]);out_blended[3]=alpha+(bgRGBA[3]*(1-alpha));}
WebInspector.Color.calculateContrastRatio=function(fgRGBA,bgRGBA)
{WebInspector.Color.blendColors(fgRGBA,bgRGBA,WebInspector.Color.calculateContrastRatio._blendedFg);var fgLuminance=WebInspector.Color.luminance(WebInspector.Color.calculateContrastRatio._blendedFg);var bgLuminance=WebInspector.Color.luminance(bgRGBA);var contrastRatio=(Math.max(fgLuminance,bgLuminance)+0.05)/(Math.min(fgLuminance,bgLuminance)+0.05);for(var i=0;i<WebInspector.Color.calculateContrastRatio._blendedFg.length;i++)
WebInspector.Color.calculateContrastRatio._blendedFg[i]=0;return contrastRatio;}
WebInspector.Color.calculateContrastRatio._blendedFg=[0,0,0,0];WebInspector.Color.desiredLuminance=function(luminance,contrast,lighter)
{function computeLuminance()
{if(lighter)
return(luminance+0.05)*contrast-0.05;else
return(luminance+0.05)/contrast-0.05;}
var desiredLuminance=computeLuminance();if(desiredLuminance<0||desiredLuminance>1){lighter=!lighter;desiredLuminance=computeLuminance();}
return desiredLuminance;};WebInspector.Color.Nicknames={"aliceblue":[240,248,255],"antiquewhite":[250,235,215],"aqua":[0,255,255],"aquamarine":[127,255,212],"azure":[240,255,255],"beige":[245,245,220],"bisque":[255,228,196],"black":[0,0,0],"blanchedalmond":[255,235,205],"blue":[0,0,255],"blueviolet":[138,43,226],"brown":[165,42,42],"burlywood":[222,184,135],"cadetblue":[95,158,160],"chartreuse":[127,255,0],"chocolate":[210,105,30],"coral":[255,127,80],"cornflowerblue":[100,149,237],"cornsilk":[255,248,220],"crimson":[237,20,61],"cyan":[0,255,255],"darkblue":[0,0,139],"darkcyan":[0,139,139],"darkgoldenrod":[184,134,11],"darkgray":[169,169,169],"darkgrey":[169,169,169],"darkgreen":[0,100,0],"darkkhaki":[189,183,107],"darkmagenta":[139,0,139],"darkolivegreen":[85,107,47],"darkorange":[255,140,0],"darkorchid":[153,50,204],"darkred":[139,0,0],"darksalmon":[233,150,122],"darkseagreen":[143,188,143],"darkslateblue":[72,61,139],"darkslategray":[47,79,79],"darkslategrey":[47,79,79],"darkturquoise":[0,206,209],"darkviolet":[148,0,211],"deeppink":[255,20,147],"deepskyblue":[0,191,255],"dimgray":[105,105,105],"dimgrey":[105,105,105],"dodgerblue":[30,144,255],"firebrick":[178,34,34],"floralwhite":[255,250,240],"forestgreen":[34,139,34],"fuchsia":[255,0,255],"gainsboro":[220,220,220],"ghostwhite":[248,248,255],"gold":[255,215,0],"goldenrod":[218,165,32],"gray":[128,128,128],"grey":[128,128,128],"green":[0,128,0],"greenyellow":[173,255,47],"honeydew":[240,255,240],"hotpink":[255,105,180],"indianred":[205,92,92],"indigo":[75,0,130],"ivory":[255,255,240],"khaki":[240,230,140],"lavender":[230,230,250],"lavenderblush":[255,240,245],"lawngreen":[124,252,0],"lemonchiffon":[255,250,205],"lightblue":[173,216,230],"lightcoral":[240,128,128],"lightcyan":[224,255,255],"lightgoldenrodyellow":[250,250,210],"lightgreen":[144,238,144],"lightgray":[211,211,211],"lightgrey":[211,211,211],"lightpink":[255,182,193],"lightsalmon":[255,160,122],"lightseagreen":[32,178,170],"lightskyblue":[135,206,250],"lightslategray":[119,136,153],"lightslategrey":[119,136,153],"lightsteelblue":[176,196,222],"lightyellow":[255,255,224],"lime":[0,255,0],"limegreen":[50,205,50],"linen":[250,240,230],"magenta":[255,0,255],"maroon":[128,0,0],"mediumaquamarine":[102,205,170],"mediumblue":[0,0,205],"mediumorchid":[186,85,211],"mediumpurple":[147,112,219],"mediumseagreen":[60,179,113],"mediumslateblue":[123,104,238],"mediumspringgreen":[0,250,154],"mediumturquoise":[72,209,204],"mediumvioletred":[199,21,133],"midnightblue":[25,25,112],"mintcream":[245,255,250],"mistyrose":[255,228,225],"moccasin":[255,228,181],"navajowhite":[255,222,173],"navy":[0,0,128],"oldlace":[253,245,230],"olive":[128,128,0],"olivedrab":[107,142,35],"orange":[255,165,0],"orangered":[255,69,0],"orchid":[218,112,214],"palegoldenrod":[238,232,170],"palegreen":[152,251,152],"paleturquoise":[175,238,238],"palevioletred":[219,112,147],"papayawhip":[255,239,213],"peachpuff":[255,218,185],"peru":[205,133,63],"pink":[255,192,203],"plum":[221,160,221],"powderblue":[176,224,230],"purple":[128,0,128],"rebeccapurple":[102,51,153],"red":[255,0,0],"rosybrown":[188,143,143],"royalblue":[65,105,225],"saddlebrown":[139,69,19],"salmon":[250,128,114],"sandybrown":[244,164,96],"seagreen":[46,139,87],"seashell":[255,245,238],"sienna":[160,82,45],"silver":[192,192,192],"skyblue":[135,206,235],"slateblue":[106,90,205],"slategray":[112,128,144],"slategrey":[112,128,144],"snow":[255,250,250],"springgreen":[0,255,127],"steelblue":[70,130,180],"tan":[210,180,140],"teal":[0,128,128],"thistle":[216,191,216],"tomato":[255,99,71],"turquoise":[64,224,208],"violet":[238,130,238],"wheat":[245,222,179],"white":[255,255,255],"whitesmoke":[245,245,245],"yellow":[255,255,0],"yellowgreen":[154,205,50],"transparent":[0,0,0,0],};WebInspector.Color.PageHighlight={Content:WebInspector.Color.fromRGBA([111,168,220,.66]),ContentLight:WebInspector.Color.fromRGBA([111,168,220,.5]),ContentOutline:WebInspector.Color.fromRGBA([9,83,148]),Padding:WebInspector.Color.fromRGBA([147,196,125,.55]),PaddingLight:WebInspector.Color.fromRGBA([147,196,125,.4]),Border:WebInspector.Color.fromRGBA([255,229,153,.66]),BorderLight:WebInspector.Color.fromRGBA([255,229,153,.5]),Margin:WebInspector.Color.fromRGBA([246,178,107,.66]),MarginLight:WebInspector.Color.fromRGBA([246,178,107,.5]),EventTarget:WebInspector.Color.fromRGBA([255,196,196,.66]),Shape:WebInspector.Color.fromRGBA([96,82,177,0.8]),ShapeMargin:WebInspector.Color.fromRGBA([96,82,127,.6])}
WebInspector.Color.detectColorFormat=function(color)
{const cf=WebInspector.Color.Format;var format;var formatSetting=WebInspector.moduleSetting("colorFormat").get();if(formatSetting===cf.Original)
format=cf.Original;else if(formatSetting===cf.RGB)
format=(color.hasAlpha()?cf.RGBA:cf.RGB);else if(formatSetting===cf.HSL)
format=(color.hasAlpha()?cf.HSLA:cf.HSL);else if(!color.hasAlpha())
format=(color.canBeShortHex()?cf.ShortHEX:cf.HEX);else
format=cf.RGBA;return format;}},{}],208:[function(require,module,exports){WebInspector.Object=function(){}
WebInspector.Object.prototype={addEventListener:function(eventType,listener,thisObject)
{if(!listener)
console.assert(false);if(!this._listeners)
this._listeners=new Map();if(!this._listeners.has(eventType))
this._listeners.set(eventType,[]);this._listeners.get(eventType).push({thisObject:thisObject,listener:listener});return new WebInspector.EventTarget.EventDescriptor(this,eventType,thisObject,listener);},removeEventListener:function(eventType,listener,thisObject)
{console.assert(listener);if(!this._listeners||!this._listeners.has(eventType))
return;var listeners=this._listeners.get(eventType);for(var i=0;i<listeners.length;++i){if(listeners[i].listener===listener&&listeners[i].thisObject===thisObject)
listeners.splice(i--,1);}
if(!listeners.length)
this._listeners.delete(eventType);},removeAllListeners:function()
{delete this._listeners;},hasEventListeners:function(eventType)
{return this._listeners&&this._listeners.has(eventType);},dispatchEventToListeners:function(eventType,eventData)
{if(!this._listeners||!this._listeners.has(eventType))
return false;var event=new WebInspector.Event(this,eventType,eventData);var listeners=this._listeners.get(eventType).slice(0);for(var i=0;i<listeners.length;++i){listeners[i].listener.call(listeners[i].thisObject,event);if(event._stoppedPropagation)
break;}
return event.defaultPrevented;}}
WebInspector.Event=function(target,type,data)
{this.target=target;this.type=type;this.data=data;this.defaultPrevented=false;this._stoppedPropagation=false;}
WebInspector.Event.prototype={stopPropagation:function()
{this._stoppedPropagation=true;},preventDefault:function()
{this.defaultPrevented=true;},consume:function(preventDefault)
{this.stopPropagation();if(preventDefault)
this.preventDefault();}}
WebInspector.EventTarget=function()
{}
WebInspector.EventTarget.removeEventListeners=function(eventList)
{for(var i=0;i<eventList.length;++i){var eventInfo=eventList[i];eventInfo.eventTarget.removeEventListener(eventInfo.eventType,eventInfo.method,eventInfo.receiver);}
eventList.splice(0,eventList.length);}
WebInspector.EventTarget.prototype={addEventListener:function(eventType,listener,thisObject){},removeEventListener:function(eventType,listener,thisObject){},removeAllListeners:function(){},hasEventListeners:function(eventType){},dispatchEventToListeners:function(eventType,eventData){},}
WebInspector.EventTarget.EventDescriptor=function(eventTarget,eventType,receiver,method)
{this.eventTarget=eventTarget;this.eventType=eventType;this.receiver=receiver;this.method=method;}},{}],209:[function(require,module,exports){WebInspector.ParsedURL=function(url)
{this.isValid=false;this.url=url;this.scheme="";this.host="";this.port="";this.path="";this.queryParams="";this.fragment="";this.folderPathComponents="";this.lastPathComponent="";var match=url.match(/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^\s\/:]*)(?::([\d]+))?(?:(\/[^#]*)(?:#(.*))?)?$/i);if(match){this.isValid=true;this.scheme=match[1].toLowerCase();this.host=match[2];this.port=match[3];this.path=match[4]||"/";this.fragment=match[5];}else{if(this.url.startsWith("data:")){this.scheme="data";return;}
if(this.url==="about:blank"){this.scheme="about";return;}
this.path=this.url;}
var path=this.path;var indexOfQuery=path.indexOf("?");if(indexOfQuery!==-1){this.queryParams=path.substring(indexOfQuery+1);path=path.substring(0,indexOfQuery);}
var lastSlashIndex=path.lastIndexOf("/");if(lastSlashIndex!==-1){this.folderPathComponents=path.substring(0,lastSlashIndex);this.lastPathComponent=path.substring(lastSlashIndex+1);}else
this.lastPathComponent=path;}
WebInspector.ParsedURL.splitURLIntoPathComponents=function(url)
{if(url.startsWith("/"))
url="file://"+url;var parsedURL=new WebInspector.ParsedURL(url);var origin;var folderPath;var name;if(parsedURL.isValid){origin=parsedURL.scheme+"://"+parsedURL.host;if(parsedURL.port)
origin+=":"+parsedURL.port;folderPath=parsedURL.folderPathComponents;name=parsedURL.lastPathComponent;if(parsedURL.queryParams)
name+="?"+parsedURL.queryParams;}else{origin="";folderPath="";name=url;}
var result=[origin];var splittedPath=folderPath.split("/");for(var i=1;i<splittedPath.length;++i){if(!splittedPath[i])
continue;result.push(splittedPath[i]);}
result.push(name);return result;}
WebInspector.ParsedURL.extractOrigin=function(url)
{var parsedURL=new WebInspector.ParsedURL(url);if(!parsedURL.isValid)
return"";var origin=parsedURL.scheme+"://"+parsedURL.host;if(parsedURL.port)
origin+=":"+parsedURL.port;return origin;}
WebInspector.ParsedURL.extractExtension=function(url)
{var lastIndexOfDot=url.lastIndexOf(".");var extension=lastIndexOfDot!==-1?url.substr(lastIndexOfDot+1):"";var indexOfQuestionMark=extension.indexOf("?");if(indexOfQuestionMark!==-1)
extension=extension.substr(0,indexOfQuestionMark);return extension;}
WebInspector.ParsedURL.extractName=function(url)
{var index=url.lastIndexOf("/");return index!==-1?url.substr(index+1):url;}
WebInspector.ParsedURL.completeURL=function(baseURL,href)
{if(href){var trimmedHref=href.trim();if(trimmedHref.startsWith("data:")||trimmedHref.startsWith("blob:")||trimmedHref.startsWith("javascript:"))
return href;var parsedHref=trimmedHref.asParsedURL();if(parsedHref&&parsedHref.scheme)
return trimmedHref;}else{return baseURL;}
var parsedURL=baseURL.asParsedURL();if(parsedURL){if(parsedURL.isDataURL())
return href;var path=href;var query=path.indexOf("?");var postfix="";if(query!==-1){postfix=path.substring(query);path=path.substring(0,query);}else{var fragment=path.indexOf("#");if(fragment!==-1){postfix=path.substring(fragment);path=path.substring(0,fragment);}}
if(!path){var basePath=parsedURL.path;if(postfix.charAt(0)==="?"){var baseQuery=parsedURL.path.indexOf("?");if(baseQuery!==-1)
basePath=basePath.substring(0,baseQuery);}
return parsedURL.scheme+"://"+parsedURL.host+(parsedURL.port?(":"+parsedURL.port):"")+basePath+postfix;}else if(path.charAt(0)!=="/"){var prefix=parsedURL.path;var prefixQuery=prefix.indexOf("?");if(prefixQuery!==-1)
prefix=prefix.substring(0,prefixQuery);prefix=prefix.substring(0,prefix.lastIndexOf("/"))+"/";path=prefix+path;}else if(path.length>1&&path.charAt(1)==="/"){return parsedURL.scheme+":"+path+postfix;}
return parsedURL.scheme+"://"+parsedURL.host+(parsedURL.port?(":"+parsedURL.port):"")+Runtime.normalizePath(path)+postfix;}
return null;}
WebInspector.ParsedURL.prototype={get displayName()
{if(this._displayName)
return this._displayName;if(this.isDataURL())
return this.dataURLDisplayName();if(this.isAboutBlank())
return this.url;this._displayName=this.lastPathComponent;if(!this._displayName)
this._displayName=(this.host||"")+"/";if(this._displayName==="/")
this._displayName=this.url;return this._displayName;},dataURLDisplayName:function()
{if(this._dataURLDisplayName)
return this._dataURLDisplayName;if(!this.isDataURL())
return"";this._dataURLDisplayName=this.url.trimEnd(20);return this._dataURLDisplayName;},isAboutBlank:function()
{return this.url==="about:blank";},isDataURL:function()
{return this.scheme==="data";},lastPathComponentWithFragment:function()
{return this.lastPathComponent+(this.fragment?"#"+this.fragment:"");},domain:function()
{if(this.isDataURL())
return"data:";return this.host+(this.port?":"+this.port:"");},securityOrigin:function()
{if(this.isDataURL())
return"data:";return this.scheme+"://"+this.domain();},urlWithoutScheme:function()
{if(this.scheme&&this.url.startsWith(this.scheme+"://"))
return this.url.substring(this.scheme.length+3);return this.url;},}
WebInspector.ParsedURL.splitLineAndColumn=function(string)
{var lineColumnRegEx=/(?::(\d+))?(?::(\d+))?$/;var lineColumnMatch=lineColumnRegEx.exec(string);var lineNumber;var columnNumber;console.assert(lineColumnMatch);if(typeof(lineColumnMatch[1])==="string"){lineNumber=parseInt(lineColumnMatch[1],10);lineNumber=isNaN(lineNumber)?undefined:lineNumber-1;}
if(typeof(lineColumnMatch[2])==="string"){columnNumber=parseInt(lineColumnMatch[2],10);columnNumber=isNaN(columnNumber)?undefined:columnNumber-1;}
return{url:string.substring(0,string.length-lineColumnMatch[0].length),lineNumber:lineNumber,columnNumber:columnNumber};}
WebInspector.ParsedURL.isRelativeURL=function(url)
{return!(/^[A-Za-z][A-Za-z0-9+.-]*:/.test(url));}
String.prototype.asParsedURL=function()
{var parsedURL=new WebInspector.ParsedURL(this.toString());if(parsedURL.isValid)
return parsedURL;return null;}},{}],210:[function(require,module,exports){WebInspector.ResourceType=function(name,title,category,isTextType)
{this._name=name;this._title=title;this._category=category;this._isTextType=isTextType;}
WebInspector.ResourceType.prototype={name:function()
{return this._name;},title:function()
{return this._title;},category:function()
{return this._category;},isTextType:function()
{return this._isTextType;},isScript:function()
{return this._name==="script"||this._name==="sm-script";},hasScripts:function()
{return this.isScript()||this.isDocument();},isStyleSheet:function()
{return this._name==="stylesheet"||this._name==="sm-stylesheet";},isDocument:function()
{return this._name==="document";},isDocumentOrScriptOrStyleSheet:function()
{return this.isDocument()||this.isScript()||this.isStyleSheet();},isFromSourceMap:function()
{return this._name.startsWith("sm-");},toString:function()
{return this._name;},canonicalMimeType:function()
{if(this.isDocument())
return"text/html";if(this.isScript())
return"text/javascript";if(this.isStyleSheet())
return"text/css";return"";}}
WebInspector.ResourceCategory=function(title,shortTitle)
{this.title=title;this.shortTitle=shortTitle;}
WebInspector.resourceCategories={XHR:new WebInspector.ResourceCategory("XHR and Fetch","XHR"),Script:new WebInspector.ResourceCategory("Scripts","JS"),Stylesheet:new WebInspector.ResourceCategory("Stylesheets","CSS"),Image:new WebInspector.ResourceCategory("Images","Img"),Media:new WebInspector.ResourceCategory("Media","Media"),Font:new WebInspector.ResourceCategory("Fonts","Font"),Document:new WebInspector.ResourceCategory("Documents","Doc"),WebSocket:new WebInspector.ResourceCategory("WebSockets","WS"),Manifest:new WebInspector.ResourceCategory("Manifest","Manifest"),Other:new WebInspector.ResourceCategory("Other","Other")}
WebInspector.resourceTypes={XHR:new WebInspector.ResourceType("xhr","XHR",WebInspector.resourceCategories.XHR,true),Fetch:new WebInspector.ResourceType("fetch","Fetch",WebInspector.resourceCategories.XHR,true),EventSource:new WebInspector.ResourceType("eventsource","EventSource",WebInspector.resourceCategories.XHR,true),Script:new WebInspector.ResourceType("script","Script",WebInspector.resourceCategories.Script,true),Stylesheet:new WebInspector.ResourceType("stylesheet","Stylesheet",WebInspector.resourceCategories.Stylesheet,true),Image:new WebInspector.ResourceType("image","Image",WebInspector.resourceCategories.Image,false),Media:new WebInspector.ResourceType("media","Media",WebInspector.resourceCategories.Media,false),Font:new WebInspector.ResourceType("font","Font",WebInspector.resourceCategories.Font,false),Document:new WebInspector.ResourceType("document","Document",WebInspector.resourceCategories.Document,true),TextTrack:new WebInspector.ResourceType("texttrack","TextTrack",WebInspector.resourceCategories.Other,true),WebSocket:new WebInspector.ResourceType("websocket","WebSocket",WebInspector.resourceCategories.WebSocket,false),Other:new WebInspector.ResourceType("other","Other",WebInspector.resourceCategories.Other,false),SourceMapScript:new WebInspector.ResourceType("sm-script","Script",WebInspector.resourceCategories.Script,false),SourceMapStyleSheet:new WebInspector.ResourceType("sm-stylesheet","Stylesheet",WebInspector.resourceCategories.Stylesheet,false),Manifest:new WebInspector.ResourceType("manifest","Manifest",WebInspector.resourceCategories.Manifest,true),}
WebInspector.ResourceType.mimeFromURL=function(url)
{var name=WebInspector.ParsedURL.extractName(url);if(WebInspector.ResourceType._mimeTypeByName.has(name)){return WebInspector.ResourceType._mimeTypeByName.get(name);}
var ext=WebInspector.ParsedURL.extractExtension(url).toLowerCase();return WebInspector.ResourceType._mimeTypeByExtension.get(ext);}
WebInspector.ResourceType._mimeTypeByName=new Map([["Cakefile","text/x-coffeescript"]]);WebInspector.ResourceType._mimeTypeByExtension=new Map([["js","text/javascript"],["css","text/css"],["html","text/html"],["htm","text/html"],["xml","application/xml"],["xsl","application/xml"],["asp","application/x-aspx"],["aspx","application/x-aspx"],["jsp","application/x-jsp"],["c","text/x-c++src"],["cc","text/x-c++src"],["cpp","text/x-c++src"],["h","text/x-c++src"],["m","text/x-c++src"],["mm","text/x-c++src"],["coffee","text/x-coffeescript"],["dart","text/javascript"],["ts","text/typescript"],["tsx","text/typescript"],["json","application/json"],["gyp","application/json"],["gypi","application/json"],["cs","text/x-csharp"],["java","text/x-java"],["less","text/x-less"],["php","text/x-php"],["phtml","application/x-httpd-php"],["py","text/x-python"],["sh","text/x-sh"],["scss","text/x-scss"],["vtt","text/vtt"],["ls","text/x-livescript"],["cljs","text/x-clojure"],["cljc","text/x-clojure"],["cljx","text/x-clojure"],["styl","text/x-styl"],["jsx","text/jsx"],["jpeg","image/jpeg"],["jpg","image/jpeg"],["svg","image/svg"],["gif","image/gif"],["webp","image/webp"],["png","image/png"],["ico","image/ico"],["tiff","image/tiff"],["tif","image/tif"],["bmp","image/bmp"],["ttf","font/opentype"],["otf","font/opentype"],["ttc","font/opentype"],["woff","application/font-woff"]]);},{}],211:[function(require,module,exports){WebInspector.Segment=function(begin,end,data)
{if(begin>end)
console.assert(false,"Invalid segment");this.begin=begin;this.end=end;this.data=data;}
WebInspector.Segment.prototype={intersects:function(that)
{return this.begin<that.end&&that.begin<this.end;}};WebInspector.SegmentedRange=function(mergeCallback)
{this._segments=[];this._mergeCallback=mergeCallback;}
WebInspector.SegmentedRange.prototype={append:function(newSegment)
{var startIndex=this._segments.lowerBound(newSegment,(a,b)=>a.begin-b.begin);var endIndex=startIndex;var merged=null;if(startIndex>0){var precedingSegment=this._segments[startIndex-1];merged=this._tryMerge(precedingSegment,newSegment);if(merged){--startIndex;newSegment=merged;}else if(this._segments[startIndex-1].end>=newSegment.begin){if(newSegment.end<precedingSegment.end)
this._segments.splice(startIndex,0,new WebInspector.Segment(newSegment.end,precedingSegment.end,precedingSegment.data));precedingSegment.end=newSegment.begin;}}
while(endIndex<this._segments.length&&this._segments[endIndex].end<=newSegment.end)
++endIndex;if(endIndex<this._segments.length){merged=this._tryMerge(newSegment,this._segments[endIndex]);if(merged){endIndex++;newSegment=merged;}else if(newSegment.intersects(this._segments[endIndex]))
this._segments[endIndex].begin=newSegment.end;}
this._segments.splice(startIndex,endIndex-startIndex,newSegment);},appendRange:function(that)
{that.segments().forEach(segment=>this.append(segment));},segments:function()
{return this._segments;},_tryMerge:function(first,second)
{var merged=this._mergeCallback&&this._mergeCallback(first,second);if(!merged)
return null;merged.begin=first.begin;merged.end=Math.max(first.end,second.end);return merged;}}},{}],212:[function(require,module,exports){WebInspector.TextRange=function(startLine,startColumn,endLine,endColumn)
{this.startLine=startLine;this.startColumn=startColumn;this.endLine=endLine;this.endColumn=endColumn;}
WebInspector.TextRange.createFromLocation=function(line,column)
{return new WebInspector.TextRange(line,column,line,column);}
WebInspector.TextRange.fromObject=function(serializedTextRange)
{return new WebInspector.TextRange(serializedTextRange.startLine,serializedTextRange.startColumn,serializedTextRange.endLine,serializedTextRange.endColumn);}
WebInspector.TextRange.comparator=function(range1,range2)
{return range1.compareTo(range2);}
WebInspector.TextRange.prototype={isEmpty:function()
{return this.startLine===this.endLine&&this.startColumn===this.endColumn;},immediatelyPrecedes:function(range)
{if(!range)
return false;return this.endLine===range.startLine&&this.endColumn===range.startColumn;},immediatelyFollows:function(range)
{if(!range)
return false;return range.immediatelyPrecedes(this);},follows:function(range)
{return(range.endLine===this.startLine&&range.endColumn<=this.startColumn)||range.endLine<this.startLine;},get linesCount()
{return this.endLine-this.startLine;},collapseToEnd:function()
{return new WebInspector.TextRange(this.endLine,this.endColumn,this.endLine,this.endColumn);},collapseToStart:function()
{return new WebInspector.TextRange(this.startLine,this.startColumn,this.startLine,this.startColumn);},normalize:function()
{if(this.startLine>this.endLine||(this.startLine===this.endLine&&this.startColumn>this.endColumn))
return new WebInspector.TextRange(this.endLine,this.endColumn,this.startLine,this.startColumn);else
return this.clone();},clone:function()
{return new WebInspector.TextRange(this.startLine,this.startColumn,this.endLine,this.endColumn);},serializeToObject:function()
{var serializedTextRange={};serializedTextRange.startLine=this.startLine;serializedTextRange.startColumn=this.startColumn;serializedTextRange.endLine=this.endLine;serializedTextRange.endColumn=this.endColumn;return serializedTextRange;},compareTo:function(other)
{if(this.startLine>other.startLine)
return 1;if(this.startLine<other.startLine)
return-1;if(this.startColumn>other.startColumn)
return 1;if(this.startColumn<other.startColumn)
return-1;return 0;},compareToPosition:function(lineNumber,columnNumber)
{if(lineNumber<this.startLine||(lineNumber===this.startLine&&columnNumber<this.startColumn))
return-1;if(lineNumber>this.endLine||(lineNumber===this.endLine&&columnNumber>this.endColumn))
return 1;return 0;},equal:function(other)
{return this.startLine===other.startLine&&this.endLine===other.endLine&&this.startColumn===other.startColumn&&this.endColumn===other.endColumn;},relativeTo:function(line,column)
{var relative=this.clone();if(this.startLine===line)
relative.startColumn-=column;if(this.endLine===line)
relative.endColumn-=column;relative.startLine-=line;relative.endLine-=line;return relative;},rebaseAfterTextEdit:function(originalRange,editedRange)
{console.assert(originalRange.startLine===editedRange.startLine);console.assert(originalRange.startColumn===editedRange.startColumn);var rebase=this.clone();if(!this.follows(originalRange))
return rebase;var lineDelta=editedRange.endLine-originalRange.endLine;var columnDelta=editedRange.endColumn-originalRange.endColumn;rebase.startLine+=lineDelta;rebase.endLine+=lineDelta;if(rebase.startLine===editedRange.endLine)
rebase.startColumn+=columnDelta;if(rebase.endLine===editedRange.endLine)
rebase.endColumn+=columnDelta;return rebase;},toString:function()
{return JSON.stringify(this);},containsLocation:function(lineNumber,columnNumber)
{if(this.startLine===this.endLine)
return this.startLine===lineNumber&&this.startColumn<=columnNumber&&columnNumber<=this.endColumn;if(this.startLine===lineNumber)
return this.startColumn<=columnNumber;if(this.endLine===lineNumber)
return columnNumber<=this.endColumn;return this.startLine<lineNumber&&lineNumber<this.endLine;}}
WebInspector.TextRange.fromEdit=function(oldRange,newText)
{var endLine=oldRange.startLine;var endColumn=oldRange.startColumn+newText.length;var lineEndings=newText.computeLineEndings();if(lineEndings.length>1){endLine=oldRange.startLine+lineEndings.length-1;var len=lineEndings.length;endColumn=lineEndings[len-1]-lineEndings[len-2]-1;}
return new WebInspector.TextRange(oldRange.startLine,oldRange.startColumn,endLine,endColumn);}
WebInspector.SourceRange=function(offset,length)
{this.offset=offset;this.length=length;}
WebInspector.SourceEdit=function(sourceURL,oldRange,newText)
{this.sourceURL=sourceURL;this.oldRange=oldRange;this.newText=newText;}
WebInspector.SourceEdit.prototype={newRange:function()
{return WebInspector.TextRange.fromEdit(this.oldRange,this.newText);},}
WebInspector.SourceEdit.comparator=function(edit1,edit2)
{return WebInspector.TextRange.comparator(edit1.oldRange,edit2.oldRange);}},{}],213:[function(require,module,exports){WebInspector.UIString=function(string,vararg)
{return String.vsprintf(WebInspector.localize(string),Array.prototype.slice.call(arguments,1));}
WebInspector.UIString.capitalize=function(string,vararg)
{if(WebInspector._useLowerCaseMenuTitles===undefined)
throw"WebInspector.setLocalizationPlatform() has not been called";var localized=WebInspector.localize(string);var capitalized;if(WebInspector._useLowerCaseMenuTitles)
capitalized=localized.replace(/\^(.)/g,"$1");else
capitalized=localized.replace(/\^(.)/g,function(str,char){return char.toUpperCase();});return String.vsprintf(capitalized,Array.prototype.slice.call(arguments,1));}
WebInspector.setLocalizationPlatform=function(platform)
{WebInspector._useLowerCaseMenuTitles=platform==="windows";}
WebInspector.localize=function(string)
{return string;}
WebInspector.UIStringFormat=function(format)
{this._localizedFormat=WebInspector.localize(format);this._tokenizedFormat=String.tokenizeFormatString(this._localizedFormat,String.standardFormatters);}
WebInspector.UIStringFormat._append=function(a,b)
{return a+b;}
WebInspector.UIStringFormat.prototype={format:function(vararg)
{return String.format(this._localizedFormat,arguments,String.standardFormatters,"",WebInspector.UIStringFormat._append,this._tokenizedFormat).formattedResult;}}},{}],214:[function(require,module,exports){WebInspector.FilmStripModel=function(tracingModel,zeroTime)
{this.reset(tracingModel,zeroTime);}
WebInspector.FilmStripModel._category="disabled-by-default-devtools.screenshot";WebInspector.FilmStripModel.TraceEvents={CaptureFrame:"CaptureFrame",Screenshot:"Screenshot"}
WebInspector.FilmStripModel.prototype={reset:function(tracingModel,zeroTime)
{this._zeroTime=zeroTime||tracingModel.minimumRecordTime();this._spanTime=tracingModel.maximumRecordTime()-this._zeroTime;this._frames=[];var browserMain=WebInspector.TracingModel.browserMainThread(tracingModel);if(!browserMain)
return;var events=browserMain.events();for(var i=0;i<events.length;++i){var event=events[i];if(event.startTime<this._zeroTime)
continue;if(!event.hasCategory(WebInspector.FilmStripModel._category))
continue;if(event.name===WebInspector.FilmStripModel.TraceEvents.CaptureFrame){var data=event.args["data"];if(data)
this._frames.push(WebInspector.FilmStripModel.Frame._fromEvent(this,event,this._frames.length));}else if(event.name===WebInspector.FilmStripModel.TraceEvents.Screenshot){this._frames.push(WebInspector.FilmStripModel.Frame._fromSnapshot(this,(event),this._frames.length));}}},frames:function()
{return this._frames;},zeroTime:function()
{return this._zeroTime;},spanTime:function()
{return this._spanTime;},frameByTimestamp:function(timestamp)
{var index=this._frames.upperBound(timestamp,(timestamp,frame)=>timestamp-frame.timestamp)-1;return index>=0?this._frames[index]:null;}}
WebInspector.FilmStripModel.Frame=function(model,timestamp,index)
{this._model=model;this.timestamp=timestamp;this.index=index;this._imageData=null;this._snapshot=null;}
WebInspector.FilmStripModel.Frame._fromEvent=function(model,event,index)
{var frame=new WebInspector.FilmStripModel.Frame(model,event.startTime,index);frame._imageData=event.args["data"];return frame;}
WebInspector.FilmStripModel.Frame._fromSnapshot=function(model,snapshot,index)
{var frame=new WebInspector.FilmStripModel.Frame(model,snapshot.startTime,index);frame._snapshot=snapshot;return frame;}
WebInspector.FilmStripModel.Frame.prototype={model:function()
{return this._model;},imageDataPromise:function()
{if(this._imageData||!this._snapshot)
return Promise.resolve(this._imageData);return(this._snapshot.objectPromise());}}},{}],215:[function(require,module,exports){WebInspector.SCSSParser=function()
{}
WebInspector.SCSSParser.prototype={parse:function(content)
{var ast=null;try{ast=gonzales.parse(content,{syntax:"scss"});}catch(e){return[];}
var rootBlock={properties:[],node:ast};var blocks=[rootBlock];ast.selectors=[];WebInspector.SCSSParser.extractNodes(ast,blocks,rootBlock);var rules=[];for(var block of blocks)
this._handleBlock(block,rules);return rules;},_handleBlock:function(block,output)
{var selectors=block.node.selectors.map(WebInspector.SCSSParser.rangeFromNode);var properties=[];var styleRange=WebInspector.SCSSParser.rangeFromNode(block.node);styleRange.startColumn+=1;styleRange.endColumn-=1;for(var node of block.properties){if(node.type==="declaration")
this._handleDeclaration(node,properties);else if(node.type==="include")
this._handleInclude(node,properties);else if(node.type==="multilineComment"&&node.start.line===node.end.line)
this._handleComment(node,properties);}
if(!selectors.length&&!properties.length)
return;var rule=new WebInspector.SCSSParser.Rule(selectors,properties,styleRange);output.push(rule);},_handleDeclaration:function(node,output)
{var propertyNode=node.content.find(node=>node.type==="property");var valueNode=node.content.find(node=>node.type==="value");if(!propertyNode||!valueNode)
return;var nameRange=WebInspector.SCSSParser.rangeFromNode(propertyNode);var valueRange=WebInspector.SCSSParser.rangeFromNode(valueNode);var range=(node.declarationRange);var property=new WebInspector.SCSSParser.Property(range,nameRange,valueRange,false);output.push(property);},_handleInclude:function(node,output)
{var mixinName=node.content.find(node=>node.type==="ident");if(!mixinName)
return;var nameRange=WebInspector.SCSSParser.rangeFromNode(mixinName);var mixinArguments=node.content.find(node=>node.type==="arguments");if(!mixinArguments)
return;var parameters=mixinArguments.content.filter(node=>node.type!=="delimiter"&&node.type!=="space");for(var parameter of parameters){var range=WebInspector.SCSSParser.rangeFromNode(node);var valueRange=WebInspector.SCSSParser.rangeFromNode(parameter);var property=new WebInspector.SCSSParser.Property(range,nameRange,valueRange,false);output.push(property);}},_handleComment:function(node,output)
{if(node.start.line!==node.end.line)
return;var innerText=(node.content);var innerResult=this.parse(innerText);if(innerResult.length!==1||innerResult[0].properties.length!==1)
return;var property=innerResult[0].properties[0];var disabledProperty=property.rebaseInsideOneLineComment(node);output.push(disabledProperty);},}
WebInspector.SCSSParser.rangeFromNode=function(node)
{return new WebInspector.TextRange(node.start.line-1,node.start.column-1,node.end.line-1,node.end.column);}
WebInspector.SCSSParser.Property=function(range,nameRange,valueRange,disabled)
{this.range=range;this.name=nameRange;this.value=valueRange;this.disabled=disabled;}
WebInspector.SCSSParser.Property.prototype={rebaseInsideOneLineComment:function(commentNode)
{var lineOffset=commentNode.start.line-1;var columnOffset=commentNode.start.column-1+2;var range=WebInspector.SCSSParser.rangeFromNode(commentNode);var name=rebaseRange(this.name,lineOffset,columnOffset);var value=rebaseRange(this.value,lineOffset,columnOffset);return new WebInspector.SCSSParser.Property(range,name,value,true);function rebaseRange(range,lineOffset,columnOffset)
{return new WebInspector.TextRange(range.startLine+lineOffset,range.startColumn+columnOffset,range.endLine+lineOffset,range.endColumn+columnOffset);}}}
WebInspector.SCSSParser.Rule=function(selectors,properties,styleRange)
{this.selectors=selectors;this.properties=properties;this.styleRange=styleRange;}
WebInspector.SCSSParser.extractNodes=function(node,blocks,lastBlock)
{if(!Array.isArray(node.content))
return;if(node.type==="block"){lastBlock={node:node,properties:[]};blocks.push(lastBlock);}
var lastDeclaration=null;var selectors=[];for(var i=0;i<node.content.length;++i){var child=node.content[i];if(child.type==="declarationDelimiter"&&lastDeclaration){lastDeclaration.declarationRange.endLine=child.end.line-1;lastDeclaration.declarationRange.endColumn=child.end.column;lastDeclaration=null;}else if(child.type==="selector"){selectors.push(child);}else if(child.type==="block"){child.selectors=selectors;selectors=[];}
if(child.type==="include"||child.type==="declaration"||child.type==="multilineComment")
lastBlock.properties.push(child);if(child.type==="declaration"){lastDeclaration=child;lastDeclaration.declarationRange=WebInspector.TextRange.createFromLocation(child.start.line-1,child.start.column-1);}
WebInspector.SCSSParser.extractNodes(child,blocks,lastBlock);}
if(lastDeclaration){lastDeclaration.declarationRange.endLine=node.end.line-1;lastDeclaration.declarationRange.endColumn=node.end.column-1;}}},{}],216:[function(require,module,exports){(function webpackUniversalModuleDefinition(root,factory){if(typeof exports==='object'&&typeof module==='object')
module.exports=factory();else if(typeof define==='function'&&define.amd)
define([],factory);else if(typeof exports==='object')
exports["gonzales"]=factory();else
root["gonzales"]=factory();})(this,function(){return(function(modules){var installedModules={};function __webpack_require__(moduleId){if(installedModules[moduleId])
return installedModules[moduleId].exports;var module=installedModules[moduleId]={exports:{},id:moduleId,loaded:false};modules[moduleId].call(module.exports,module,module.exports,__webpack_require__);module.loaded=true;return module.exports;}
__webpack_require__.m=modules;__webpack_require__.c=installedModules;__webpack_require__.p="";return __webpack_require__(0);})
([function(module,exports,__webpack_require__){'use strict';var Node=__webpack_require__(1);var parse=__webpack_require__(7);module.exports={createNode:function(options){return new Node(options);},parse:parse};},function(module,exports,__webpack_require__){'use strict';var _createClass=(function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if('value'in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};})();function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError('Cannot call a class as a function');}}
var Node=(function(){function Node(options){_classCallCheck(this,Node);this.type=options.type;this.content=options.content;this.syntax=options.syntax;if(options.start)this.start=options.start;if(options.end)this.end=options.end;}
Node.prototype.contains=function contains(type){return this.content.some(function(node){return node.type===type;});};Node.prototype.eachFor=function eachFor(type,callback){if(!Array.isArray(this.content))return;if(typeof type!=='string'){callback=type;type=null;}
var l=this.content.length;var breakLoop;for(var i=l;i--;){if(breakLoop===null)break;if(!type||this.content[i]&&this.content[i].type===type)breakLoop=callback(this.content[i],i,this);}
if(breakLoop===null)return null;};Node.prototype.first=function first(type){if(!Array.isArray(this.content))return null;if(!type)return this.content[0];var i=0;var l=this.content.length;for(;i<l;i++){if(this.content[i].type===type)return this.content[i];}
return null;};Node.prototype.forEach=function forEach(type,callback){if(!Array.isArray(this.content))return;if(typeof type!=='string'){callback=type;type=null;}
var i=0;var l=this.content.length;var breakLoop;for(;i<l;i++){if(breakLoop===null)break;if(!type||this.content[i]&&this.content[i].type===type)breakLoop=callback(this.content[i],i,this);}
if(breakLoop===null)return null;};Node.prototype.get=function get(index){if(!Array.isArray(this.content))return null;var node=this.content[index];return node?node:null;};Node.prototype.insert=function insert(index,node){if(!Array.isArray(this.content))return;this.content.splice(index,0,node);};Node.prototype.is=function is(type){return this.type===type;};Node.prototype.last=function last(type){if(!Array.isArray(this.content))return null;var i=this.content.length-1;if(!type)return this.content[i];for(;;i--){if(this.content[i].type===type)return this.content[i];}
return null;};Node.prototype.removeChild=function removeChild(index){if(!Array.isArray(this.content))return;var removedChild=this.content.splice(index,1);return removedChild;};Node.prototype.toJson=function toJson(){return JSON.stringify(this,false,2);};Node.prototype.toString=function toString(){var stringify=undefined;try{stringify=__webpack_require__(2)("./"+this.syntax+'/stringify');}catch(e){var message='Syntax "'+this.syntax+'" is not supported yet, sorry';return console.error(message);}
return stringify(this);};Node.prototype.traverse=function traverse(callback,index){var level=arguments.length<=2||arguments[2]===undefined?0:arguments[2];var parent=arguments.length<=3||arguments[3]===undefined?null:arguments[3];var breakLoop;var x;level++;callback(this,index,parent,level);if(!Array.isArray(this.content))return;for(var i=0,l=this.content.length;i<l;i++){breakLoop=this.content[i].traverse(callback,i,level,this);if(breakLoop===null)break;if(x=this.content.length-l){l+=x;i+=x;}}
if(breakLoop===null)return null;};Node.prototype.traverseByType=function traverseByType(type,callback){this.traverse(function(node){if(node.type===type)callback.apply(node,arguments);});};Node.prototype.traverseByTypes=function traverseByTypes(types,callback){this.traverse(function(node){if(types.indexOf(node.type)!==-1)callback.apply(node,arguments);});};_createClass(Node,[{key:'length',get:function(){if(!Array.isArray(this.content))return 0;return this.content.length;}}]);return Node;})();module.exports=Node;},function(module,exports,__webpack_require__){var map={"./css/stringify":3,"./less/stringify":4,"./sass/stringify":5,"./scss/stringify":6};function webpackContext(req){return __webpack_require__(webpackContextResolve(req));};function webpackContextResolve(req){return map[req]||(function(){throw new Error("Cannot find module '"+req+"'.")}());};webpackContext.keys=function webpackContextKeys(){return Object.keys(map);};webpackContext.resolve=webpackContextResolve;module.exports=webpackContext;webpackContext.id=2;},function(module,exports){'use strict';module.exports=function stringify(tree){if(!tree)throw new Error('We need tree to translate');function _t(tree){var type=tree.type;if(_unique[type])return _unique[type](tree);if(typeof tree.content==='string')return tree.content;if(Array.isArray(tree.content))return _composite(tree.content);return'';}
function _composite(t,i){if(!t)return'';var s='';i=i||0;for(;i<t.length;i++)s+=_t(t[i]);return s;}
var _unique={'arguments':function(t){return'('+_composite(t.content)+')';},'atkeyword':function(t){return'@'+_composite(t.content);},'attributeSelector':function(t){return'['+_composite(t.content)+']';},'block':function(t){return'{'+_composite(t.content)+'}';},'brackets':function(t){return'['+_composite(t.content)+']';},'class':function(t){return'.'+_composite(t.content);},'color':function(t){return'#'+t.content;},'expression':function(t){return'expression('+t.content+')';},'id':function(t){return'#'+_composite(t.content);},'multilineComment':function(t){return'/*'+t.content+'*/';},'nthSelector':function(t){return':'+_t(t.content[0])+'('+_composite(t.content.slice(1))+')';},'parentheses':function(t){return'('+_composite(t.content)+')';},'percentage':function(t){return _composite(t.content)+'%';},'pseudoClass':function(t){return':'+_composite(t.content);},'pseudoElement':function(t){return'::'+_composite(t.content);},'uri':function(t){return'url('+_composite(t.content)+')';}};return _t(tree);};},function(module,exports){'use strict';module.exports=function stringify(tree){if(!tree)throw new Error('We need tree to translate');function _t(tree){var type=tree.type;if(_unique[type])return _unique[type](tree);if(typeof tree.content==='string')return tree.content;if(Array.isArray(tree.content))return _composite(tree.content);return'';}
function _composite(t,i){if(!t)return'';var s='';i=i||0;for(;i<t.length;i++)s+=_t(t[i]);return s;}
var _unique={'arguments':function(t){return'('+_composite(t.content)+')';},'atkeyword':function(t){return'@'+_composite(t.content);},'attributeSelector':function(t){return'['+_composite(t.content)+']';},'block':function(t){return'{'+_composite(t.content)+'}';},'brackets':function(t){return'['+_composite(t.content)+']';},'class':function(t){return'.'+_composite(t.content);},'color':function(t){return'#'+t.content;},'escapedString':function(t){return'~'+t.content;},'expression':function(t){return'expression('+t.content+')';},'id':function(t){return'#'+_composite(t.content);},'interpolatedVariable':function(t){return'@{'+_composite(t.content)+'}';},'multilineComment':function(t){return'/*'+t.content+'*/';},'nthSelector':function(t){return':'+_t(t.content[0])+'('+_composite(t.content.slice(1))+')';},'parentheses':function(t){return'('+_composite(t.content)+')';},'percentage':function(t){return _composite(t.content)+'%';},'pseudoClass':function(t){return':'+_composite(t.content);},'pseudoElement':function(t){return'::'+_composite(t.content);},'singlelineComment':function(t){return'/'+'/'+t.content;},'uri':function(t){return'url('+_composite(t.content)+')';},'variable':function(t){return'@'+_composite(t.content);},'variablesList':function(t){return _composite(t.content)+'...';}};return _t(tree);};},function(module,exports){'use strict';module.exports=function stringify(tree){if(!tree)throw new Error('We need tree to translate');function _t(tree){var type=tree.type;if(_unique[type])return _unique[type](tree);if(typeof tree.content==='string')return tree.content;if(Array.isArray(tree.content))return _composite(tree.content);return'';}
function _composite(t,i){if(!t)return'';var s='';i=i||0;for(;i<t.length;i++)s+=_t(t[i]);return s;}
var _unique={'arguments':function(t){return'('+_composite(t.content)+')';},'atkeyword':function(t){return'@'+_composite(t.content);},'attributeSelector':function(t){return'['+_composite(t.content)+']';},'block':function(t){return _composite(t.content);},'brackets':function(t){return'['+_composite(t.content)+']';},'class':function(t){return'.'+_composite(t.content);},'color':function(t){return'#'+t.content;},'expression':function(t){return'expression('+t.content+')';},'id':function(t){return'#'+_composite(t.content);},'interpolation':function(t){return'#{'+_composite(t.content)+'}';},'multilineComment':function(t){return'/*'+t.content;},'nthSelector':function(t){return':'+_t(t.content[0])+'('+_composite(t.content.slice(1))+')';},'parentheses':function(t){return'('+_composite(t.content)+')';},'percentage':function(t){return _composite(t.content)+'%';},'placeholder':function(t){return'%'+_composite(t.content);},'pseudoClass':function(t){return':'+_composite(t.content);},'pseudoElement':function(t){return'::'+_composite(t.content);},'singlelineComment':function(t){return'/'+'/'+t.content;},'uri':function(t){return'url('+_composite(t.content)+')';},'variable':function(t){return'$'+_composite(t.content);},'variablesList':function(t){return _composite(t.content)+'...';}};return _t(tree);};},function(module,exports){'use strict';module.exports=function stringify(tree){if(!tree)throw new Error('We need tree to translate');function _t(tree){var type=tree.type;if(_unique[type])return _unique[type](tree);if(typeof tree.content==='string')return tree.content;if(Array.isArray(tree.content))return _composite(tree.content);return'';}
function _composite(t,i){if(!t)return'';var s='';i=i||0;for(;i<t.length;i++)s+=_t(t[i]);return s;}
var _unique={'arguments':function(t){return'('+_composite(t.content)+')';},'atkeyword':function(t){return'@'+_composite(t.content);},'attributeSelector':function(t){return'['+_composite(t.content)+']';},'block':function(t){return'{'+_composite(t.content)+'}';},'brackets':function(t){return'['+_composite(t.content)+']';},'class':function(t){return'.'+_composite(t.content);},'color':function(t){return'#'+t.content;},'expression':function(t){return'expression('+t.content+')';},'id':function(t){return'#'+_composite(t.content);},'interpolation':function(t){return'#{'+_composite(t.content)+'}';},'multilineComment':function(t){return'/*'+t.content+'*/';},'nthSelector':function(t){return':'+_t(t.content[0])+'('+_composite(t.content.slice(1))+')';},'parentheses':function(t){return'('+_composite(t.content)+')';},'percentage':function(t){return _composite(t.content)+'%';},'placeholder':function(t){return'%'+_composite(t.content);},'pseudoClass':function(t){return':'+_composite(t.content);},'pseudoElement':function(t){return'::'+_composite(t.content);},'singlelineComment':function(t){return'/'+'/'+t.content;},'uri':function(t){return'url('+_composite(t.content)+')';},'variable':function(t){return'$'+_composite(t.content);},'variablesList':function(t){return _composite(t.content)+'...';}};return _t(tree);};},function(module,exports,__webpack_require__){'use strict';var ParsingError=__webpack_require__(8);var syntaxes=__webpack_require__(10);var isInteger=Number.isInteger||function(value){return typeof value==='number'&&Math.floor(value)===value;};function parser(css,options){if(typeof css!=='string')throw new Error('Please, pass a string to parse');else if(!css)return __webpack_require__(16)();var syntax=options&&options.syntax||'css';var context=options&&options.context||'stylesheet';var tabSize=options&&options.tabSize;if(!isInteger(tabSize)||tabSize<1)tabSize=1;var syntaxParser=undefined;if(syntaxes[syntax]){syntaxParser=syntaxes[syntax];}else{syntaxParser=syntaxes;}
if(!syntaxParser){var message='Syntax "'+syntax+'" is not supported yet, sorry';return console.error(message);}
var getTokens=syntaxParser.tokenizer;var mark=syntaxParser.mark;var parse=syntaxParser.parse;var tokens=getTokens(css,tabSize);mark(tokens);var ast;try{ast=parse(tokens,context);}catch(e){if(!e.syntax)throw e;throw new ParsingError(e,css);}
return ast;}
module.exports=parser;},function(module,exports,__webpack_require__){'use strict';var parserPackage=__webpack_require__(9);function ParsingError(e,css){this.line=e.line;this.syntax=e.syntax;this.css_=css;}
ParsingError.prototype=Object.defineProperties({customMessage_:'',line:null,name:'Parsing error',syntax:null,version:parserPackage.version,toString:function(){return[this.name+': '+this.message,'',this.context,'','Syntax: '+this.syntax,'Gonzales PE version: '+this.version].join('\n');}},{context:{get:function(){var LINES_AROUND=2;var result=[];var currentLineNumber=this.line;var start=currentLineNumber-1-LINES_AROUND;var end=currentLineNumber+LINES_AROUND;var lines=this.css_.split(/\r\n|\r|\n/);for(var i=start;i<end;i++){var line=lines[i];if(!line)continue;var ln=i+1;var mark=ln===currentLineNumber?'*':' ';result.push(ln+mark+'| '+line);}
return result.join('\n');},configurable:true,enumerable:true},message:{get:function(){if(this.customMessage_){return this.customMessage_;}else{var message='Please check validity of the block';if(typeof this.line==='number')message+=' starting from line #'+this.line;return message;}},set:function(message){this.customMessage_=message;},configurable:true,enumerable:true}});module.exports=ParsingError;},function(module,exports){module.exports={"name":"gonzales-pe","description":"Gonzales Preprocessor Edition (fast CSS parser)","version":"3.3.1","homepage":"http://github.com/tonyganch/gonzales-pe","bugs":"http://github.com/tonyganch/gonzales-pe/issues","license":"MIT","author":{"name":"Tony Ganch","email":"tonyganch+github@gmail.com","url":"http://tonyganch.com"},"main":"./lib/gonzales","repository":{"type":"git","url":"http://github.com/tonyganch/gonzales-pe.git"},"scripts":{"autofix-tests":"bash ./scripts/build.sh && bash ./scripts/autofix-tests.sh","build":"bash ./scripts/build.sh","init":"bash ./scripts/init.sh","log":"bash ./scripts/log.sh","prepublish":"bash ./scripts/prepublish.sh","postpublish":"bash ./scripts/postpublish.sh","test":"bash ./scripts/build.sh && bash ./scripts/test.sh","watch":"bash ./scripts/watch.sh"},"bin":{"gonzales":"./bin/gonzales.js"},"dependencies":{"minimist":"1.1.x"},"devDependencies":{"babel-loader":"^5.3.2","coffee-script":"~1.7.1","jscs":"2.1.0","jshint":"2.8.0","json-loader":"^0.5.3","mocha":"2.2.x","webpack":"^1.12.2"},"engines":{"node":">=0.6.0"}};},function(module,exports,__webpack_require__){'use strict';exports.__esModule=true;exports['default']={mark:__webpack_require__(11),parse:__webpack_require__(13),stringify:__webpack_require__(6),tokenizer:__webpack_require__(15)};module.exports=exports['default'];},function(module,exports,__webpack_require__){'use strict';var TokenType=__webpack_require__(12);module.exports=(function(){function markSC(tokens){var tokensLength=tokens.length;var ws=-1;var sc=-1;var t=undefined;for(var i=0;i<tokensLength;i++){t=tokens[i];switch(t.type){case TokenType.Space:case TokenType.Tab:case TokenType.Newline:t.ws=true;t.sc=true;if(ws===-1)ws=i;if(sc===-1)sc=i;break;case TokenType.CommentML:case TokenType.CommentSL:if(ws!==-1){tokens[ws].ws_last=i-1;ws=-1;}
t.sc=true;break;default:if(ws!==-1){tokens[ws].ws_last=i-1;ws=-1;}
if(sc!==-1){tokens[sc].sc_last=i-1;sc=-1;}}}
if(ws!==-1)tokens[ws].ws_last=i-1;if(sc!==-1)tokens[sc].sc_last=i-1;}
function markBrackets(tokens){var tokensLength=tokens.length;var ps=[];var sbs=[];var cbs=[];var t=undefined;for(var i=0;i<tokensLength;i++){t=tokens[i];switch(t.type){case TokenType.LeftParenthesis:ps.push(i);break;case TokenType.RightParenthesis:if(ps.length){t.left=ps.pop();tokens[t.left].right=i;}
break;case TokenType.LeftSquareBracket:sbs.push(i);break;case TokenType.RightSquareBracket:if(sbs.length){t.left=sbs.pop();tokens[t.left].right=i;}
break;case TokenType.LeftCurlyBracket:cbs.push(i);break;case TokenType.RightCurlyBracket:if(cbs.length){t.left=cbs.pop();tokens[t.left].right=i;}
break;}}}
return function(tokens){markBrackets(tokens);markSC(tokens);};})();},function(module,exports){'use strict';module.exports={StringSQ:'StringSQ',StringDQ:'StringDQ',CommentML:'CommentML',CommentSL:'CommentSL',Newline:'Newline',Space:'Space',Tab:'Tab',ExclamationMark:'ExclamationMark',QuotationMark:'QuotationMark',NumberSign:'NumberSign',DollarSign:'DollarSign',PercentSign:'PercentSign',Ampersand:'Ampersand',Apostrophe:'Apostrophe',LeftParenthesis:'LeftParenthesis',RightParenthesis:'RightParenthesis',Asterisk:'Asterisk',PlusSign:'PlusSign',Comma:'Comma',HyphenMinus:'HyphenMinus',FullStop:'FullStop',Solidus:'Solidus',Colon:'Colon',Semicolon:'Semicolon',LessThanSign:'LessThanSign',EqualsSign:'EqualsSign',EqualitySign:'EqualitySign',InequalitySign:'InequalitySign',GreaterThanSign:'GreaterThanSign',QuestionMark:'QuestionMark',CommercialAt:'CommercialAt',LeftSquareBracket:'LeftSquareBracket',ReverseSolidus:'ReverseSolidus',RightSquareBracket:'RightSquareBracket',CircumflexAccent:'CircumflexAccent',LowLine:'LowLine',LeftCurlyBracket:'LeftCurlyBracket',VerticalLine:'VerticalLine',RightCurlyBracket:'RightCurlyBracket',Tilde:'Tilde',Identifier:'Identifier',DecimalNumber:'DecimalNumber'};},function(module,exports,__webpack_require__){'use strict';var Node=__webpack_require__(1);var NodeType=__webpack_require__(14);var TokenType=__webpack_require__(12);var tokens=undefined;var tokensLength=undefined;var pos=undefined;var contexts={'arguments':function(){return checkArguments(pos)&&getArguments();},'atkeyword':function(){return checkAtkeyword(pos)&&getAtkeyword();},'atrule':function(){return checkAtrule(pos)&&getAtrule();},'block':function(){return checkBlock(pos)&&getBlock();},'brackets':function(){return checkBrackets(pos)&&getBrackets();},'class':function(){return checkClass(pos)&&getClass();},'combinator':function(){return checkCombinator(pos)&&getCombinator();},'commentML':function(){return checkCommentML(pos)&&getCommentML();},'commentSL':function(){return checkCommentSL(pos)&&getCommentSL();},'condition':function(){return checkCondition(pos)&&getCondition();},'conditionalStatement':function(){return checkConditionalStatement(pos)&&getConditionalStatement();},'declaration':function(){return checkDeclaration(pos)&&getDeclaration();},'declDelim':function(){return checkDeclDelim(pos)&&getDeclDelim();},'default':function(){return checkDefault(pos)&&getDefault();},'delim':function(){return checkDelim(pos)&&getDelim();},'dimension':function(){return checkDimension(pos)&&getDimension();},'expression':function(){return checkExpression(pos)&&getExpression();},'extend':function(){return checkExtend(pos)&&getExtend();},'function':function(){return checkFunction(pos)&&getFunction();},'global':function(){return checkGlobal(pos)&&getGlobal();},'ident':function(){return checkIdent(pos)&&getIdent();},'important':function(){return checkImportant(pos)&&getImportant();},'include':function(){return checkInclude(pos)&&getInclude();},'interpolation':function(){return checkInterpolation(pos)&&getInterpolation();},'loop':function(){return checkLoop(pos)&&getLoop();},'mixin':function(){return checkMixin(pos)&&getMixin();},'namespace':function(){return checkNamespace(pos)&&getNamespace();},'number':function(){return checkNumber(pos)&&getNumber();},'operator':function(){return checkOperator(pos)&&getOperator();},'optional':function(){return checkOptional(pos)&&getOptional();},'parentheses':function(){return checkParentheses(pos)&&getParentheses();},'parentselector':function(){return checkParentSelector(pos)&&getParentSelector();},'percentage':function(){return checkPercentage(pos)&&getPercentage();},'placeholder':function(){return checkPlaceholder(pos)&&getPlaceholder();},'progid':function(){return checkProgid(pos)&&getProgid();},'property':function(){return checkProperty(pos)&&getProperty();},'propertyDelim':function(){return checkPropertyDelim(pos)&&getPropertyDelim();},'pseudoc':function(){return checkPseudoc(pos)&&getPseudoc();},'pseudoe':function(){return checkPseudoe(pos)&&getPseudoe();},'ruleset':function(){return checkRuleset(pos)&&getRuleset();},'s':function(){return checkS(pos)&&getS();},'selector':function(){return checkSelector(pos)&&getSelector();},'shash':function(){return checkShash(pos)&&getShash();},'string':function(){return checkString(pos)&&getString();},'stylesheet':function(){return checkStylesheet(pos)&&getStylesheet();},'unary':function(){return checkUnary(pos)&&getUnary();},'uri':function(){return checkUri(pos)&&getUri();},'value':function(){return checkValue(pos)&&getValue();},'variable':function(){return checkVariable(pos)&&getVariable();},'variableslist':function(){return checkVariablesList(pos)&&getVariablesList();},'vhash':function(){return checkVhash(pos)&&getVhash();}};function throwError(i){var ln=i?tokens[i].ln:tokens[pos].ln;throw{line:ln,syntax:'scss'};}function checkExcluding(exclude,i){var start=i;while(i<tokensLength){if(exclude[tokens[i++].type])break;}return i-start-2;}function joinValues(start,finish){var s='';for(var i=start;i<finish+1;i++){s+=tokens[i].value;}return s;}function joinValues2(start,num){if(start+num-1>=tokensLength)return;var s='';for(var i=0;i<num;i++){s+=tokens[start+i].value;}return s;}function getLastPosition(content,line,column,colOffset){return typeof content==='string'?getLastPositionForString(content,line,column,colOffset):getLastPositionForArray(content,line,column,colOffset);}function getLastPositionForString(content,line,column,colOffset){var position=[];if(!content){position=[line,column];if(colOffset)position[1]+=colOffset-1;return position;}var lastLinebreak=content.lastIndexOf('\n');var endsWithLinebreak=lastLinebreak===content.length-1;var splitContent=content.split('\n');var linebreaksCount=splitContent.length-1;var prevLinebreak=linebreaksCount===0||linebreaksCount===1?-1:content.length-splitContent[linebreaksCount-1].length-2;var offset=endsWithLinebreak?linebreaksCount-1:linebreaksCount;position[0]=line+offset;if(endsWithLinebreak){offset=prevLinebreak!==-1?content.length-prevLinebreak:content.length-1;}else{offset=linebreaksCount!==0?content.length-lastLinebreak-column-1:content.length-1;}position[1]=column+offset;if(!colOffset)return position;if(endsWithLinebreak){position[0]++;position[1]=colOffset;}else{position[1]+=colOffset;}return position;}function getLastPositionForArray(content,line,column,colOffset){var position;if(content.length===0){position=[line,column];}else{var c=content[content.length-1];if(c.hasOwnProperty('end')){position=[c.end.line,c.end.column];}else{position=getLastPosition(c.content,line,column);}}if(!colOffset)return position;if(tokens[pos-1].type!=='Newline'){position[1]+=colOffset;}else{position[0]++;position[1]=1;}return position;}function newNode(type,content,line,column,end){if(!end)end=getLastPosition(content,line,column);return new Node({type:type,content:content,start:{line:line,column:column},end:{line:end[0],column:end[1]},syntax:'scss'});}function checkAny(i){return checkBrackets(i)||checkParentheses(i)||checkString(i)||checkVariablesList(i)||checkVariable(i)||checkPlaceholder(i)||checkPercentage(i)||checkDimension(i)||checkNumber(i)||checkUri(i)||checkExpression(i)||checkFunction(i)||checkInterpolation(i)||checkIdent(i)||checkClass(i)||checkUnary(i);}function getAny(){if(checkBrackets(pos))return getBrackets();else if(checkParentheses(pos))return getParentheses();else if(checkString(pos))return getString();else if(checkVariablesList(pos))return getVariablesList();else if(checkVariable(pos))return getVariable();else if(checkPlaceholder(pos))return getPlaceholder();else if(checkPercentage(pos))return getPercentage();else if(checkDimension(pos))return getDimension();else if(checkNumber(pos))return getNumber();else if(checkUri(pos))return getUri();else if(checkExpression(pos))return getExpression();else if(checkFunction(pos))return getFunction();else if(checkInterpolation(pos))return getInterpolation();else if(checkIdent(pos))return getIdent();else if(checkClass(pos))return getClass();else if(checkUnary(pos))return getUnary();}function checkArguments(i){var start=i;var l=undefined;if(i>=tokensLength||tokens[i].type!==TokenType.LeftParenthesis)return 0;i++;while(i<tokens[start].right){if(l=checkArgument(i))i+=l;else return 0;}return tokens[start].right-start+1;}function checkArgument(i){return checkBrackets(i)||checkParentheses(i)||checkDeclaration(i)||checkFunction(i)||checkVariablesList(i)||checkVariable(i)||checkSC(i)||checkDelim(i)||checkDeclDelim(i)||checkString(i)||checkPercentage(i)||checkDimension(i)||checkNumber(i)||checkUri(i)||checkInterpolation(i)||checkIdent(i)||checkVhash(i)||checkOperator(i)||checkUnary(i);}function getArgument(){if(checkBrackets(pos))return getBrackets();else if(checkParentheses(pos))return getParentheses();else if(checkDeclaration(pos))return getDeclaration();else if(checkFunction(pos))return getFunction();else if(checkVariablesList(pos))return getVariablesList();else if(checkVariable(pos))return getVariable();else if(checkSC(pos))return getSC();else if(checkDelim(pos))return getDelim();else if(checkDeclDelim(pos))return getDeclDelim();else if(checkString(pos))return getString();else if(checkPercentage(pos))return getPercentage();else if(checkDimension(pos))return getDimension();else if(checkNumber(pos))return getNumber();else if(checkUri(pos))return getUri();else if(checkInterpolation(pos))return getInterpolation();else if(checkIdent(pos))return getIdent();else if(checkVhash(pos))return getVhash();else if(checkOperator(pos))return getOperator();else if(checkUnary(pos))return getUnary();}function checkAtkeyword(i){var l;if(i>=tokensLength||tokens[i++].type!==TokenType.CommercialAt)return 0;return(l=checkIdentOrInterpolation(i))?l+1:0;}function getAtkeyword(){var startPos=pos;var x=undefined;pos++;x=getIdentOrInterpolation();var token=tokens[startPos];return newNode(NodeType.AtkeywordType,x,token.ln,token.col);}function checkAtrule(i){var l;if(i>=tokensLength)return 0;if(tokens[i].atrule_l!==undefined)return tokens[i].atrule_l;if(l=checkKeyframesRule(i))tokens[i].atrule_type=4;else if(l=checkAtruler(i))tokens[i].atrule_type=1;else if(l=checkAtruleb(i))tokens[i].atrule_type=2;else if(l=checkAtrules(i))tokens[i].atrule_type=3;else return 0;tokens[i].atrule_l=l;return l;}function getAtrule(){switch(tokens[pos].atrule_type){case 1:return getAtruler();case 2:return getAtruleb();case 3:return getAtrules();case 4:return getKeyframesRule();}}function checkAtruleb(i){var start=i;var l=undefined;if(i>=tokensLength)return 0;if(l=checkAtkeyword(i))i+=l;else return 0;if(l=checkTsets(i))i+=l;if(l=checkBlock(i))i+=l;else return 0;return i-start;}function getAtruleb(){var startPos=pos;var x=undefined;x=[getAtkeyword()].concat(getTsets()).concat([getBlock()]);var token=tokens[startPos];return newNode(NodeType.AtruleType,x,token.ln,token.col);}function checkAtruler(i){var start=i;var l=undefined;if(i>=tokensLength)return 0;if(l=checkAtkeyword(i))i+=l;else return 0;if(l=checkTsets(i))i+=l;if(i<tokensLength&&tokens[i].type===TokenType.LeftCurlyBracket)i++;else return 0;if(l=checkAtrulers(i))i+=l;if(i<tokensLength&&tokens[i].type===TokenType.RightCurlyBracket)i++;else return 0;return i-start;}function getAtruler(){var startPos=pos;var x=undefined;x=[getAtkeyword()].concat(getTsets());x.push(getAtrulers());var token=tokens[startPos];return newNode(NodeType.AtruleType,x,token.ln,token.col);}function checkAtrulers(i){var start=i;var l=undefined;if(i>=tokensLength)return 0;while(l=checkRuleset(i)||checkAtrule(i)||checkSC(i)){i+=l;}if(i<tokensLength)tokens[i].atrulers_end=1;return i-start;}function getAtrulers(){var startPos=pos;var x=undefined;var token=tokens[startPos];var line=token.ln;var column=token.col;pos++;x=getSC();while(!tokens[pos].atrulers_end){if(checkSC(pos))x=x.concat(getSC());else if(checkAtrule(pos))x.push(getAtrule());else if(checkRuleset(pos))x.push(getRuleset());}x=x.concat(getSC());var end=getLastPosition(x,line,column,1);pos++;return newNode(NodeType.BlockType,x,token.ln,token.col,end);}function checkAtrules(i){var start=i;var l=undefined;if(i>=tokensLength)return 0;if(l=checkAtkeyword(i))i+=l;else return 0;if(l=checkTsets(i))i+=l;return i-start;}function getAtrules(){var startPos=pos;var x=undefined;x=[getAtkeyword()].concat(getTsets());var token=tokens[startPos];return newNode(NodeType.AtruleType,x,token.ln,token.col);}function checkBlock(i){return i<tokensLength&&tokens[i].type===TokenType.LeftCurlyBracket?tokens[i].right-i+1:0;}function getBlock(){var startPos=pos;var end=tokens[pos].right;var x=[];var token=tokens[startPos];var line=token.ln;var column=token.col;pos++;while(pos<end){if(checkBlockdecl(pos))x=x.concat(getBlockdecl());else throwError();}var end_=getLastPosition(x,line,column,1);pos=end+1;return newNode(NodeType.BlockType,x,token.ln,token.col,end_);}function checkBlockdecl(i){var l;if(i>=tokensLength)return 0;if(l=checkBlockdecl1(i))tokens[i].bd_type=1;else if(l=checkBlockdecl2(i))tokens[i].bd_type=2;else if(l=checkBlockdecl3(i))tokens[i].bd_type=3;else if(l=checkBlockdecl4(i))tokens[i].bd_type=4;else return 0;return l;}function getBlockdecl(){switch(tokens[pos].bd_type){case 1:return getBlockdecl1();case 2:return getBlockdecl2();case 3:return getBlockdecl3();case 4:return getBlockdecl4();}}function checkBlockdecl1(i){var start=i;var l=undefined;if(l=checkSC(i))i+=l;if(l=checkConditionalStatement(i))tokens[i].bd_kind=1;else if(l=checkInclude(i))tokens[i].bd_kind=2;else if(l=checkExtend(i))tokens[i].bd_kind=4;else if(l=checkLoop(i))tokens[i].bd_kind=3;else if(l=checkAtrule(i))tokens[i].bd_kind=6;else if(l=checkRuleset(i))tokens[i].bd_kind=7;else if(l=checkDeclaration(i))tokens[i].bd_kind=5;else return 0;i+=l;if(i<tokensLength&&(l=checkDeclDelim(i)))i+=l;else return 0;if(l=checkSC(i))i+=l;return i-start;}function getBlockdecl1(){var sc=getSC();var x=undefined;switch(tokens[pos].bd_kind){case 1:x=getConditionalStatement();break;case 2:x=getInclude();break;case 3:x=getLoop();break;case 4:x=getExtend();break;case 5:x=getDeclaration();break;case 6:x=getAtrule();break;case 7:x=getRuleset();break;}return sc.concat([x]).concat([getDeclDelim()]).concat(getSC());}function checkBlockdecl2(i){var start=i;var l=undefined;if(l=checkSC(i))i+=l;if(l=checkConditionalStatement(i))tokens[i].bd_kind=1;else if(l=checkInclude(i))tokens[i].bd_kind=2;else if(l=checkExtend(i))tokens[i].bd_kind=4;else if(l=checkMixin(i))tokens[i].bd_kind=8;else if(l=checkLoop(i))tokens[i].bd_kind=3;else if(l=checkAtrule(i))tokens[i].bd_kind=6;else if(l=checkRuleset(i))tokens[i].bd_kind=7;else if(l=checkDeclaration(i))tokens[i].bd_kind=5;else return 0;i+=l;if(l=checkSC(i))i+=l;return i-start;}function getBlockdecl2(){var sc=getSC();var x=undefined;switch(tokens[pos].bd_kind){case 1:x=getConditionalStatement();break;case 2:x=getInclude();break;case 3:x=getLoop();break;case 4:x=getExtend();break;case 5:x=getDeclaration();break;case 6:x=getAtrule();break;case 7:x=getRuleset();break;case 8:x=getMixin();break;}return sc.concat([x]).concat(getSC());}function checkBlockdecl3(i){var start=i;var l=undefined;if(l=checkSC(i))i+=l;if(l=checkDeclDelim(i))i+=l;else return 0;if(l=checkSC(i))i+=l;return i-start;}function getBlockdecl3(){return getSC().concat([getDeclDelim()]).concat(getSC());}function checkBlockdecl4(i){return checkSC(i);}function getBlockdecl4(){return getSC();}function checkBrackets(i){if(i>=tokensLength||tokens[i].type!==TokenType.LeftSquareBracket)return 0;return tokens[i].right-i+1;}function getBrackets(){var startPos=pos;var token=tokens[startPos];var line=token.ln;var column=token.col;pos++;var tsets=getTsets();var end=getLastPosition(tsets,line,column,1);pos++;return newNode(NodeType.BracketsType,tsets,token.ln,token.col,end);}function checkClass(i){var start=i;var l=undefined;if(i>=tokensLength)return 0;if(tokens[i].class_l)return tokens[i].class_l;if(tokens[i++].type!==TokenType.FullStop)return 0;if(l=checkIdentOrInterpolation(i))i+=l;else return 0;return i-start;}function getClass(){var startPos=pos;var x=[];pos++;x=x.concat(getIdentOrInterpolation());var token=tokens[startPos];return newNode(NodeType.ClassType,x,token.ln,token.col);}function checkCombinator(i){if(i>=tokensLength)return 0;var l=undefined;if(l=checkCombinator1(i))tokens[i].combinatorType=1;else if(l=checkCombinator2(i))tokens[i].combinatorType=2;else if(l=checkCombinator3(i))tokens[i].combinatorType=3;return l;}function getCombinator(){var type=tokens[pos].combinatorType;if(type===1)return getCombinator1();if(type===2)return getCombinator2();if(type===3)return getCombinator3();}function checkCombinator1(i){if(tokens[i].type===TokenType.VerticalLine&&tokens[i+1].type===TokenType.VerticalLine)return 2;else return 0;}function getCombinator1(){var type=NodeType.CombinatorType;var token=tokens[pos];var line=token.ln;var column=token.col;var content='||';pos+=2;return newNode(type,content,line,column);}function checkCombinator2(i){var type=tokens[i].type;if(type===TokenType.PlusSign||type===TokenType.GreaterThanSign||type===TokenType.Tilde)return 1;else return 0;}function getCombinator2(){var type=NodeType.CombinatorType;var token=tokens[pos];var line=token.ln;var column=token.col;var content=tokens[pos++].value;return newNode(type,content,line,column);}function checkCombinator3(i){var start=i;if(tokens[i].type===TokenType.Solidus)i++;else return 0;var l=undefined;if(l=checkIdent(i))i+=l;else return 0;if(tokens[i].type===TokenType.Solidus)i++;else return 0;return i-start;}function getCombinator3(){var type=NodeType.CombinatorType;var token=tokens[pos];var line=token.ln;var column=token.col;pos++;var ident=getIdent();pos++;var content='/'+ident.content+'/';return newNode(type,content,line,column);}function checkCommentML(i){return i<tokensLength&&tokens[i].type===TokenType.CommentML?1:0;}function getCommentML(){var startPos=pos;var s=tokens[pos].value.substring(2);var l=s.length;var token=tokens[startPos];var line=token.ln;var column=token.col;if(s.charAt(l-2)==='*'&&s.charAt(l-1)==='/')s=s.substring(0,l-2);var end=getLastPosition(s,line,column,2);if(end[0]===line)end[1]+=2;pos++;return newNode(NodeType.CommentMLType,s,token.ln,token.col,end);}function checkCommentSL(i){return i<tokensLength&&tokens[i].type===TokenType.CommentSL?1:0;}function getCommentSL(){var startPos=pos;var x=undefined;var token=tokens[startPos];var line=token.ln;var column=token.col;x=tokens[pos++].value.substring(2);var end=getLastPosition(x,line,column+2);return newNode(NodeType.CommentSLType,x,token.ln,token.col,end);}function checkCondition(i){var start=i;var l=undefined;var _i=undefined;var s=undefined;if(i>=tokensLength)return 0;if(l=checkAtkeyword(i))i+=l;else return 0;if(['if','else'].indexOf(tokens[start+1].value)<0)return 0;while(i<tokensLength){if(l=checkBlock(i))break;s=checkSC(i);_i=i+s;if(l=_checkCondition(_i))i+=l+s;else break;}return i-start;}function _checkCondition(i){return checkVariable(i)||checkNumber(i)||checkInterpolation(i)||checkIdent(i)||checkOperator(i)||checkCombinator(i)||checkString(i);}function getCondition(){var startPos=pos;var x=[];var s;var _pos;x.push(getAtkeyword());while(pos<tokensLength){if(checkBlock(pos))break;s=checkSC(pos);_pos=pos+s;if(!_checkCondition(_pos))break;if(s)x=x.concat(getSC());x.push(_getCondition());}var token=tokens[startPos];return newNode(NodeType.ConditionType,x,token.ln,token.col);}function _getCondition(){if(checkVariable(pos))return getVariable();if(checkNumber(pos))return getNumber();if(checkInterpolation(pos))return getInterpolation();if(checkIdent(pos))return getIdent();if(checkOperator(pos))return getOperator();if(checkCombinator(pos))return getCombinator();if(checkString(pos))return getString();}function checkConditionalStatement(i){var start=i;var l=undefined;if(i>=tokensLength)return 0;if(l=checkCondition(i))i+=l;else return 0;if(l=checkSC(i))i+=l;if(l=checkBlock(i))i+=l;else return 0;return i-start;}function getConditionalStatement(){var startPos=pos;var x=[];x.push(getCondition());x=x.concat(getSC());x.push(getBlock());var token=tokens[startPos];return newNode(NodeType.ConditionalStatementType,x,token.ln,token.col);}function checkDeclaration(i){var start=i;var l=undefined;if(i>=tokensLength)return 0;if(l=checkProperty(i))i+=l;else return 0;if(l=checkSC(i))i+=l;if(l=checkPropertyDelim(i))i++;else return 0;if(l=checkSC(i))i+=l;if(l=checkValue(i))i+=l;else return 0;return i-start;}function getDeclaration(){var startPos=pos;var x=[];x.push(getProperty());x=x.concat(getSC());x.push(getPropertyDelim());x=x.concat(getSC());x.push(getValue());var token=tokens[startPos];return newNode(NodeType.DeclarationType,x,token.ln,token.col);}function checkDeclDelim(i){return i<tokensLength&&tokens[i].type===TokenType.Semicolon?1:0;}function getDeclDelim(){var startPos=pos++;var token=tokens[startPos];return newNode(NodeType.DeclDelimType,';',token.ln,token.col);}function checkDefault(i){var start=i;var l=undefined;if(i>=tokensLength||tokens[i++].type!==TokenType.ExclamationMark)return 0;if(l=checkSC(i))i+=l;if(tokens[i].value==='default'){tokens[start].defaultEnd=i;return i-start+1;}else{return 0;}}function getDefault(){var token=tokens[pos];var line=token.ln;var column=token.col;var content=joinValues(pos,token.defaultEnd);pos=token.defaultEnd+1;return newNode(NodeType.DefaultType,content,line,column);}function checkDelim(i){return i<tokensLength&&tokens[i].type===TokenType.Comma?1:0;}function getDelim(){var startPos=pos;pos++;var token=tokens[startPos];return newNode(NodeType.DelimType,',',token.ln,token.col);}function checkDimension(i){var ln=checkNumber(i);var li=undefined;if(i>=tokensLength||!ln||i+ln>=tokensLength)return 0;return(li=checkNmName2(i+ln))?ln+li:0;}function getDimension(){var startPos=pos;var x=[getNumber()];var token=tokens[pos];var ident=newNode(NodeType.IdentType,getNmName2(),token.ln,token.col);x.push(ident);token=tokens[startPos];return newNode(NodeType.DimensionType,x,token.ln,token.col);}function checkExpression(i){var start=i;if(i>=tokensLength||tokens[i++].value!=='expression'||i>=tokensLength||tokens[i].type!==TokenType.LeftParenthesis)return 0;return tokens[i].right-start+1;}function getExpression(){var startPos=pos;var e;var token=tokens[startPos];var line=token.ln;var column=token.col;pos++;e=joinValues(pos+1,tokens[pos].right-1);var end=getLastPosition(e,line,column,1);if(end[0]===line)end[1]+=11;pos=tokens[pos].right+1;return newNode(NodeType.ExpressionType,e,token.ln,token.col,end);}function checkExtend(i){var l=0;if(l=checkExtend1(i))tokens[i].extend_child=1;else if(l=checkExtend2(i))tokens[i].extend_child=2;return l;}function getExtend(){var type=tokens[pos].extend_child;if(type===1)return getExtend1();else if(type===2)return getExtend2();}function checkExtend1(i){var start=i;var l;if(i>=tokensLength)return 0;if(l=checkAtkeyword(i))i+=l;else return 0;if(tokens[start+1].value!=='extend')return 0;if(l=checkSC(i))i+=l;else return 0;if(l=checkSelectorsGroup(i))i+=l;else return 0;if(l=checkSC(i))i+=l;else return 0;if(l=checkOptional(i))i+=l;else return 0;return i-start;}function getExtend1(){var startPos=pos;var x=[].concat([getAtkeyword()],getSC(),getSelectorsGroup(),getSC(),[getOptional()]);var token=tokens[startPos];return newNode(NodeType.ExtendType,x,token.ln,token.col);}function checkExtend2(i){var start=i;var l;if(i>=tokensLength)return 0;if(l=checkAtkeyword(i))i+=l;else return 0;if(tokens[start+1].value!=='extend')return 0;if(l=checkSC(i))i+=l;else return 0;if(l=checkSelectorsGroup(i))i+=l;else return 0;return i-start;}function getExtend2(){var startPos=pos;var x=[].concat([getAtkeyword()],getSC(),getSelectorsGroup());var token=tokens[startPos];return newNode(NodeType.ExtendType,x,token.ln,token.col);}function checkFunction(i){var start=i;var l=undefined;if(i>=tokensLength)return 0;if(l=checkIdentOrInterpolation(i))i+=l;else return 0;return i<tokensLength&&tokens[i].type===TokenType.LeftParenthesis?tokens[i].right-start+1:0;}function getFunction(){var startPos=pos;var x=getIdentOrInterpolation();var body=undefined;body=getArguments();x.push(body);var token=tokens[startPos];return newNode(NodeType.FunctionType,x,token.ln,token.col);}function getArguments(){var startPos=pos;var x=[];var body=undefined;var token=tokens[startPos];var line=token.ln;var column=token.col;pos++;while(pos<tokensLength&&tokens[pos].type!==TokenType.RightParenthesis){if(checkDeclaration(pos))x.push(getDeclaration());else if(checkArgument(pos)){body=getArgument();if(typeof body.content==='string')x.push(body);else x=x.concat(body);}else if(checkClass(pos))x.push(getClass());else throwError();}var end=getLastPosition(x,line,column,1);pos++;return newNode(NodeType.ArgumentsType,x,token.ln,token.col,end);}function checkIdent(i){var start=i;var interpolations=[];var wasIdent=undefined;var wasInt=false;var l=undefined;if(i>=tokensLength)return 0;if(tokens[i].type===TokenType.LowLine)return checkIdentLowLine(i);if(tokens[i].type===TokenType.HyphenMinus&&tokens[i+1].type===TokenType.DecimalNumber)return 0;if(l=_checkIdent(i))i+=l;else return 0;wasIdent=tokens[i-1].type===TokenType.Identifier;while(i<tokensLength){l=_checkIdent(i);if(!l)break;wasIdent=true;i+=l;}if(!wasIdent&&!wasInt&&tokens[start].type!==TokenType.Asterisk)return 0;tokens[start].ident_last=i-1;if(interpolations.length)tokens[start].interpolations=interpolations;return i-start;}function _checkIdent(i){if(tokens[i].type===TokenType.HyphenMinus||tokens[i].type===TokenType.Identifier||tokens[i].type===TokenType.DollarSign||tokens[i].type===TokenType.LowLine||tokens[i].type===TokenType.DecimalNumber||tokens[i].type===TokenType.Asterisk)return 1;return 0;}function checkIdentLowLine(i){var start=i;if(i++>=tokensLength)return 0;for(;i<tokensLength;i++){if(tokens[i].type!==TokenType.HyphenMinus&&tokens[i].type!==TokenType.DecimalNumber&&tokens[i].type!==TokenType.LowLine&&tokens[i].type!==TokenType.Identifier)break;}
tokens[start].ident_last=i-1;return i-start;}function getIdent(){var startPos=pos;var x=joinValues(pos,tokens[pos].ident_last);pos=tokens[pos].ident_last+1;var token=tokens[startPos];return newNode(NodeType.IdentType,x,token.ln,token.col);}function checkIdentOrInterpolation(i){var start=i;var l=undefined;while(i<tokensLength){if(l=checkInterpolation(i)||checkIdent(i))i+=l;else break;}return i-start;}function getIdentOrInterpolation(){var x=[];while(pos<tokensLength){if(checkInterpolation(pos))x.push(getInterpolation());else if(checkIdent(pos))x.push(getIdent());else break;}return x;}function checkImportant(i){var start=i;var l=undefined;if(i>=tokensLength||tokens[i++].type!==TokenType.ExclamationMark)return 0;if(l=checkSC(i))i+=l;if(tokens[i].value==='important'){tokens[start].importantEnd=i;return i-start+1;}else{return 0;}}function getImportant(){var token=tokens[pos];var line=token.ln;var column=token.col;var content=joinValues(pos,token.importantEnd);pos=token.importantEnd+1;return newNode(NodeType.ImportantType,content,line,column);}function checkInclude(i){var l;if(i>=tokensLength)return 0;if(l=checkInclude1(i))tokens[i].include_type=1;else if(l=checkInclude2(i))tokens[i].include_type=2;else if(l=checkInclude3(i))tokens[i].include_type=3;else if(l=checkInclude4(i))tokens[i].include_type=4;else if(l=checkInclude5(i))tokens[i].include_type=5;return l;}function checkGlobal(i){var start=i;var l=undefined;if(i>=tokensLength||tokens[i++].type!==TokenType.ExclamationMark)return 0;if(l=checkSC(i))i+=l;if(tokens[i].value==='global'){tokens[start].globalEnd=i;return i-start+1;}else{return 0;}}function getGlobal(){var token=tokens[pos];var line=token.ln;var column=token.col;var content=joinValues(pos,token.globalEnd);pos=token.globalEnd+1;return newNode(NodeType.GlobalType,content,line,column);}function getInclude(){switch(tokens[pos].include_type){case 1:return getInclude1();case 2:return getInclude2();case 3:return getInclude3();case 4:return getInclude4();case 5:return getInclude5();}}function checkInclude1(i){var start=i;var l=undefined;if(l=checkAtkeyword(i))i+=l;else return 0;if(tokens[start+1].value!=='include')return 0;if(l=checkSC(i))i+=l;else return 0;if(l=checkIdentOrInterpolation(i))i+=l;else return 0;if(l=checkSC(i))i+=l;if(l=checkArguments(i))i+=l;else return 0;if(l=checkSC(i))i+=l;if(l=checkKeyframesBlocks(i))i+=l;else return 0;return i-start;}function getInclude1(){var startPos=pos;var x=[].concat(getAtkeyword(),getSC(),getIdentOrInterpolation(),getSC(),getArguments(),getSC(),getKeyframesBlocks());var token=tokens[startPos];return newNode(NodeType.IncludeType,x,token.ln,token.col);}function checkInclude2(i){var start=i;var l=undefined;if(l=checkAtkeyword(i))i+=l;else return 0;if(tokens[start+1].value!=='include')return 0;if(l=checkSC(i))i+=l;else return 0;if(l=checkIdentOrInterpolation(i))i+=l;else return 0;if(l=checkSC(i))i+=l;if(l=checkArguments(i))i+=l;else return 0;if(l=checkSC(i))i+=l;if(l=checkBlock(i))i+=l;else return 0;return i-start;}function getInclude2(){var startPos=pos;var x=[].concat(getAtkeyword(),getSC(),getIdentOrInterpolation(),getSC(),getArguments(),getSC(),getBlock());var token=tokens[startPos];return newNode(NodeType.IncludeType,x,token.ln,token.col);}function checkInclude3(i){var start=i;var l=undefined;if(l=checkAtkeyword(i))i+=l;else return 0;if(tokens[start+1].value!=='include')return 0;if(l=checkSC(i))i+=l;else return 0;if(l=checkIdentOrInterpolation(i))i+=l;else return 0;if(l=checkSC(i))i+=l;if(l=checkArguments(i))i+=l;else return 0;return i-start;}function getInclude3(){var startPos=pos;var x=[].concat(getAtkeyword(),getSC(),getIdentOrInterpolation(),getSC(),getArguments());var token=tokens[startPos];return newNode(NodeType.IncludeType,x,token.ln,token.col);}function checkInclude4(i){var start=i;var l=undefined;if(l=checkAtkeyword(i))i+=l;else return 0;if(tokens[start+1].value!=='include')return 0;if(l=checkSC(i))i+=l;else return 0;if(l=checkIdentOrInterpolation(i))i+=l;else return 0;if(l=checkSC(i))i+=l;if(l=checkBlock(i))i+=l;else return 0;return i-start;}function getInclude4(){var startPos=pos;var x=[].concat(getAtkeyword(),getSC(),getIdentOrInterpolation(),getSC(),getBlock());var token=tokens[startPos];return newNode(NodeType.IncludeType,x,token.ln,token.col);}function checkInclude5(i){var start=i;var l=undefined;if(l=checkAtkeyword(i))i+=l;else return 0;if(tokens[start+1].value!=='include')return 0;if(l=checkSC(i))i+=l;else return 0;if(l=checkIdentOrInterpolation(i))i+=l;else return 0;return i-start;}function getInclude5(){var startPos=pos;var x=[].concat(getAtkeyword(),getSC(),getIdentOrInterpolation());var token=tokens[startPos];return newNode(NodeType.IncludeType,x,token.ln,token.col);}function checkInterpolation(i){var start=i;var l=undefined;if(i>=tokensLength)return 0;if(tokens[i].type!==TokenType.NumberSign||!tokens[i+1]||tokens[i+1].type!==TokenType.LeftCurlyBracket)return 0;i+=2;while(tokens[i].type!==TokenType.RightCurlyBracket){if(l=checkArgument(i))i+=l;else return 0;}return tokens[i].type===TokenType.RightCurlyBracket?i-start+1:0;}function getInterpolation(){var startPos=pos;var x=[];var token=tokens[startPos];var line=token.ln;var column=token.col;pos+=2;while(pos<tokensLength&&tokens[pos].type!==TokenType.RightCurlyBracket){var body=getArgument();if(typeof body.content==='string')x.push(body);else x=x.concat(body);}var end=getLastPosition(x,line,column,1);pos++;return newNode(NodeType.InterpolationType,x,token.ln,token.col,end);}function checkKeyframesBlock(i){var start=i;var l=undefined;if(i>=tokensLength)return 0;if(l=checkKeyframesSelector(i))i+=l;else return 0;if(l=checkSC(i))i+=l;if(l=checkBlock(i))i+=l;else return 0;return i-start;}function getKeyframesBlock(){var type=NodeType.RulesetType;var token=tokens[pos];var line=token.ln;var column=token.col;var content=[].concat([getKeyframesSelector()],getSC(),[getBlock()]);return newNode(type,content,line,column);}function checkKeyframesBlocks(i){var start=i;var l=undefined;if(i<tokensLength&&tokens[i].type===TokenType.LeftCurlyBracket)i++;else return 0;if(l=checkSC(i))i+=l;if(l=checkKeyframesBlock(i))i+=l;else return 0;while(tokens[i].type!==TokenType.RightCurlyBracket){if(l=checkSC(i))i+=l;else if(l=checkKeyframesBlock(i))i+=l;else break;}if(i<tokensLength&&tokens[i].type===TokenType.RightCurlyBracket)i++;else return 0;return i-start;}function getKeyframesBlocks(){var type=NodeType.BlockType;var token=tokens[pos];var line=token.ln;var column=token.col;var content=[];var keyframesBlocksEnd=token.right;pos++;while(pos<keyframesBlocksEnd){if(checkSC(pos))content=content.concat(getSC());else if(checkKeyframesBlock(pos))content.push(getKeyframesBlock());}var end=getLastPosition(content,line,column,1);pos++;return newNode(type,content,line,column,end);}function checkKeyframesRule(i){var start=i;var l=undefined;if(i>=tokensLength)return 0;if(l=checkAtkeyword(i))i+=l;else return 0;var atruleName=joinValues2(i-l,l);if(atruleName.indexOf('keyframes')===-1)return 0;if(l=checkSC(i))i+=l;else return 0;if(l=checkIdentOrInterpolation(i))i+=l;else return 0;if(l=checkSC(i))i+=l;if(l=checkKeyframesBlocks(i))i+=l;else return 0;return i-start;}function getKeyframesRule(){var type=NodeType.AtruleType;var token=tokens[pos];var line=token.ln;var column=token.col;var content=[].concat([getAtkeyword()],getSC(),getIdentOrInterpolation(),getSC(),[getKeyframesBlocks()]);return newNode(type,content,line,column);}function checkKeyframesSelector(i){var start=i;var l=undefined;if(i>=tokensLength)return 0;if(l=checkIdent(i)){var selector=joinValues2(i,l);if(selector!=='from'&&selector!=='to')return 0;i+=l;tokens[start].keyframesSelectorType=1;}else if(l=checkPercentage(i)){i+=l;tokens[start].keyframesSelectorType=2;}else if(l=checkInterpolation(i)){i+=l;tokens[start].keyframesSelectorType=3;}else{return 0;}return i-start;}function getKeyframesSelector(){var keyframesSelectorType=NodeType.KeyframesSelectorType;var selectorType=NodeType.SelectorType;var token=tokens[pos];var line=token.ln;var column=token.col;var content=[];if(token.keyframesSelectorType===1){content.push(getIdent());}else if(token.keyframesSelectorType===2){content.push(getPercentage());}else{content.push(getInterpolation());}var keyframesSelector=newNode(keyframesSelectorType,content,line,column);return newNode(selectorType,[keyframesSelector],line,column);}function checkLoop(i){var start=i;var l=undefined;if(i>=tokensLength)return 0;if(l=checkAtkeyword(i))i+=l;else return 0;if(['for','each','while'].indexOf(tokens[start+1].value)<0)return 0;while(i<tokensLength){if(l=checkBlock(i)){i+=l;break;}else if(l=checkVariable(i)||checkNumber(i)||checkInterpolation(i)||checkIdent(i)||checkSC(i)||checkOperator(i)||checkCombinator(i)||checkString(i))i+=l;else return 0;}return i-start;}function getLoop(){var startPos=pos;var x=[];x.push(getAtkeyword());while(pos<tokensLength){if(checkBlock(pos)){x.push(getBlock());break;}else if(checkVariable(pos))x.push(getVariable());else if(checkNumber(pos))x.push(getNumber());else if(checkInterpolation(pos))x.push(getInterpolation());else if(checkIdent(pos))x.push(getIdent());else if(checkOperator(pos))x.push(getOperator());else if(checkCombinator(pos))x.push(getCombinator());else if(checkSC(pos))x=x.concat(getSC());else if(checkString(pos))x.push(getString());}var token=tokens[startPos];return newNode(NodeType.LoopType,x,token.ln,token.col);}function checkMixin(i){var start=i;var l=undefined;if(i>=tokensLength)return 0;if((l=checkAtkeyword(i))&&tokens[i+1].value==='mixin')i+=l;else return 0;if(l=checkSC(i))i+=l;if(l=checkIdentOrInterpolation(i))i+=l;else return 0;if(l=checkSC(i))i+=l;if(l=checkArguments(i))i+=l;if(l=checkSC(i))i+=l;if(l=checkBlock(i))i+=l;else return 0;return i-start;}function getMixin(){var startPos=pos;var x=[getAtkeyword()];x=x.concat(getSC());if(checkIdentOrInterpolation(pos))x=x.concat(getIdentOrInterpolation());x=x.concat(getSC());if(checkArguments(pos))x.push(getArguments());x=x.concat(getSC());if(checkBlock(pos))x.push(getBlock());var token=tokens[startPos];return newNode(NodeType.MixinType,x,token.ln,token.col);}function checkNamespace(i){return i<tokensLength&&tokens[i].type===TokenType.VerticalLine?1:0;}function getNamespace(){var startPos=pos;pos++;var token=tokens[startPos];return newNode(NodeType.NamespaceType,'|',token.ln,token.col);}function checkNmName2(i){if(tokens[i].type===TokenType.Identifier)return 1;else if(tokens[i].type!==TokenType.DecimalNumber)return 0;i++;return i<tokensLength&&tokens[i].type===TokenType.Identifier?2:1;}function getNmName2(){var s=tokens[pos].value;if(tokens[pos++].type===TokenType.DecimalNumber&&pos<tokensLength&&tokens[pos].type===TokenType.Identifier)s+=tokens[pos++].value;return s;}function checkNumber(i){if(i>=tokensLength)return 0;if(tokens[i].number_l)return tokens[i].number_l;if(i<tokensLength&&tokens[i].type===TokenType.DecimalNumber&&(!tokens[i+1]||tokens[i+1]&&tokens[i+1].type!==TokenType.FullStop))return tokens[i].number_l=1,tokens[i].number_l;if(i<tokensLength&&tokens[i].type===TokenType.DecimalNumber&&tokens[i+1]&&tokens[i+1].type===TokenType.FullStop&&(!tokens[i+2]||tokens[i+2].type!==TokenType.DecimalNumber))return tokens[i].number_l=2,tokens[i].number_l;if(i<tokensLength&&tokens[i].type===TokenType.FullStop&&tokens[i+1].type===TokenType.DecimalNumber)return tokens[i].number_l=2,tokens[i].number_l;if(i<tokensLength&&tokens[i].type===TokenType.DecimalNumber&&tokens[i+1]&&tokens[i+1].type===TokenType.FullStop&&tokens[i+2]&&tokens[i+2].type===TokenType.DecimalNumber)return tokens[i].number_l=3,tokens[i].number_l;return 0;}function getNumber(){var s='';var startPos=pos;var l=tokens[pos].number_l;for(var j=0;j<l;j++){s+=tokens[pos+j].value;}pos+=l;var token=tokens[startPos];return newNode(NodeType.NumberType,s,token.ln,token.col);}function checkOperator(i){if(i>=tokensLength)return 0;switch(tokens[i].type){case TokenType.Solidus:case TokenType.PercentSign:case TokenType.Comma:case TokenType.Colon:case TokenType.EqualsSign:case TokenType.EqualitySign:case TokenType.InequalitySign:case TokenType.LessThanSign:case TokenType.GreaterThanSign:case TokenType.Asterisk:return 1;}return 0;}function getOperator(){var startPos=pos;var x=tokens[pos++].value;var token=tokens[startPos];return newNode(NodeType.OperatorType,x,token.ln,token.col);}function checkOptional(i){var start=i;var l=undefined;if(i>=tokensLength||tokens[i++].type!==TokenType.ExclamationMark)return 0;if(l=checkSC(i))i+=l;if(tokens[i].value==='optional'){tokens[start].optionalEnd=i;return i-start+1;}else{return 0;}}function getOptional(){var token=tokens[pos];var line=token.ln;var column=token.col;var content=joinValues(pos,token.optionalEnd);pos=token.optionalEnd+1;return newNode(NodeType.OptionalType,content,line,column);}function checkParentheses(i){if(i>=tokensLength||tokens[i].type!==TokenType.LeftParenthesis)return 0;return tokens[i].right-i+1;}function getParentheses(){var type=NodeType.ParenthesesType;var token=tokens[pos];var line=token.ln;var column=token.col;pos++;var tsets=getTsets();var end=getLastPosition(tsets,line,column,1);pos++;return newNode(type,tsets,line,column,end);}function checkParentSelector(i){return i<tokensLength&&tokens[i].type===TokenType.Ampersand?1:0;}function getParentSelector(){var startPos=pos;pos++;var token=tokens[startPos];return newNode(NodeType.ParentSelectorType,'&',token.ln,token.col);}function checkParentSelectorExtension(i){if(i>=tokensLength)return 0;var start=i;var l=undefined;while(i<tokensLength){if(l=checkNumber(i)||checkIdentOrInterpolation(i))i+=l;else break;}return i-start;}function getParentSelectorExtension(){var type=NodeType.ParentSelectorExtensionType;var token=tokens[pos];var line=token.ln;var column=token.col;var content=[];while(pos<tokensLength){if(checkNumber(pos))content.push(getNumber());else if(checkIdentOrInterpolation(pos))content=content.concat(getIdentOrInterpolation());else break;}return newNode(type,content,line,column);}function checkParentSelectorWithExtension(i){if(i>=tokensLength)return 0;var start=i;var l=undefined;if(l=checkParentSelector(i))i+=l;else return 0;if(l=checkParentSelectorExtension(i))i+=l;return i-start;}function getParentSelectorWithExtension(){var content=[getParentSelector()];if(checkParentSelectorExtension(pos))content.push(getParentSelectorExtension());return content;}function checkPercentage(i){var x;if(i>=tokensLength)return 0;x=checkNumber(i);if(!x||i+x>=tokensLength)return 0;return tokens[i+x].type===TokenType.PercentSign?x+1:0;}function getPercentage(){var startPos=pos;var x=[getNumber()];var token=tokens[startPos];var line=token.ln;var column=token.col;var end=getLastPosition(x,line,column,1);pos++;return newNode(NodeType.PercentageType,x,token.ln,token.col,end);}function checkPlaceholder(i){var l;if(i>=tokensLength)return 0;if(tokens[i].placeholder_l)return tokens[i].placeholder_l;if(tokens[i].type===TokenType.PercentSign&&(l=checkIdentOrInterpolation(i+1))){tokens[i].placeholder_l=l+1;return l+1;}else return 0;}function getPlaceholder(){var startPos=pos;pos++;var x=getIdentOrInterpolation();var token=tokens[startPos];return newNode(NodeType.PlaceholderType,x,token.ln,token.col);}function checkProgid(i){var start=i;var l=undefined;if(i>=tokensLength)return 0;if(joinValues2(i,6)==='progid:DXImageTransform.Microsoft.')i+=6;else return 0;if(l=checkIdentOrInterpolation(i))i+=l;else return 0;if(l=checkSC(i))i+=l;if(tokens[i].type===TokenType.LeftParenthesis){tokens[start].progid_end=tokens[i].right;i=tokens[i].right+1;}else return 0;return i-start;}function getProgid(){var startPos=pos;var progid_end=tokens[pos].progid_end;var x=joinValues(pos,progid_end);pos=progid_end+1;var token=tokens[startPos];return newNode(NodeType.ProgidType,x,token.ln,token.col);}function checkProperty(i){var start=i;var l=undefined;if(i>=tokensLength)return 0;if(l=checkVariable(i)||checkIdentOrInterpolation(i))i+=l;else return 0;return i-start;}function getProperty(){var startPos=pos;var x=[];if(checkVariable(pos)){x.push(getVariable());}else{x=x.concat(getIdentOrInterpolation());}var token=tokens[startPos];return newNode(NodeType.PropertyType,x,token.ln,token.col);}function checkPropertyDelim(i){return i<tokensLength&&tokens[i].type===TokenType.Colon?1:0;}function getPropertyDelim(){var startPos=pos;pos++;var token=tokens[startPos];return newNode(NodeType.PropertyDelimType,':',token.ln,token.col);}function checkPseudo(i){return checkPseudoe(i)||checkPseudoc(i);}function getPseudo(){if(checkPseudoe(pos))return getPseudoe();if(checkPseudoc(pos))return getPseudoc();}function checkPseudoe(i){var l;if(i>=tokensLength||tokens[i++].type!==TokenType.Colon||i>=tokensLength||tokens[i++].type!==TokenType.Colon)return 0;return(l=checkIdentOrInterpolation(i))?l+2:0;}function getPseudoe(){var startPos=pos;pos+=2;var x=getIdentOrInterpolation();var token=tokens[startPos];return newNode(NodeType.PseudoeType,x,token.ln,token.col);}function checkPseudoc(i){var l;if(i>=tokensLength||tokens[i].type!==TokenType.Colon)return 0;if(l=checkPseudoClass3(i))tokens[i].pseudoClassType=3;else if(l=checkPseudoClass4(i))tokens[i].pseudoClassType=4;else if(l=checkPseudoClass5(i))tokens[i].pseudoClassType=5;else if(l=checkPseudoClass1(i))tokens[i].pseudoClassType=1;else if(l=checkPseudoClass2(i))tokens[i].pseudoClassType=2;else if(l=checkPseudoClass6(i))tokens[i].pseudoClassType=6;else return 0;return l;}function getPseudoc(){var childType=tokens[pos].pseudoClassType;if(childType===1)return getPseudoClass1();if(childType===2)return getPseudoClass2();if(childType===3)return getPseudoClass3();if(childType===4)return getPseudoClass4();if(childType===5)return getPseudoClass5();if(childType===6)return getPseudoClass6();}function checkPseudoClass1(i){var start=i;i++;if(i>=tokensLength)return 0;var l=undefined;if(l=checkIdentOrInterpolation(i))i+=l;else return 0;if(i>=tokensLength||tokens[i].type!==TokenType.LeftParenthesis)return 0;var right=tokens[i].right;i++;if(l=checkSelectorsGroup(i))i+=l;else return 0;if(i!==right)return 0;return right-start+1;}function getPseudoClass1(){var type=NodeType.PseudocType;var token=tokens[pos];var line=token.ln;var column=token.col;var content=[];pos++;content=content.concat(getIdentOrInterpolation());{var _type=NodeType.ArgumentsType;var _token=tokens[pos];var _line=_token.ln;var _column=_token.col;pos++;var selectors=getSelectorsGroup();var end=getLastPosition(selectors,_line,_column,1);var args=newNode(_type,selectors,_line,_column,end);content.push(args);pos++;}return newNode(type,content,line,column);}function checkPseudoClass2(i){var start=i;var l=0;i++;if(i>=tokensLength)return 0;if(l=checkIdentOrInterpolation(i))i+=l;else return 0;if(i>=tokensLength||tokens[i].type!==TokenType.LeftParenthesis)return 0;var right=tokens[i].right;i++;if(l=checkSC(i))i+=l;if(l=checkIdentOrInterpolation(i))i+=l;else return 0;if(l=checkSC(i))i+=l;if(i!==right)return 0;return i-start+1;}function getPseudoClass2(){var type=NodeType.PseudocType;var token=tokens[pos];var line=token.ln;var column=token.col;var content=[];pos++;content=content.concat(getIdentOrInterpolation());var l=tokens[pos].ln;var c=tokens[pos].col;var value=[];pos++;value=value.concat(getSC()).concat(getIdentOrInterpolation()).concat(getSC());var end=getLastPosition(value,l,c,1);var args=newNode(NodeType.ArgumentsType,value,l,c,end);content.push(args);pos++;return newNode(type,content,line,column);}function checkPseudoClass3(i){var start=i;var l=0;i++;if(i>=tokensLength)return 0;if(l=checkIdentOrInterpolation(i))i+=l;else return 0;if(i>=tokensLength||tokens[i].type!==TokenType.LeftParenthesis)return 0;var right=tokens[i].right;i++;if(l=checkSC(i))i+=l;if(l=checkUnary(i))i+=l;if(i>=tokensLength)return 0;if(tokens[i].type===TokenType.DecimalNumber)i++;if(i>=tokensLength)return 0;if(tokens[i].value==='n')i++;else return 0;if(l=checkSC(i))i+=l;if(i>=tokensLength)return 0;if(tokens[i].value==='+'||tokens[i].value==='-')i++;else return 0;if(l=checkSC(i))i+=l;if(tokens[i].type===TokenType.DecimalNumber)i++;else return 0;if(l=checkSC(i))i+=l;if(i!==right)return 0;return i-start+1;}function getPseudoClass3(){var type=NodeType.PseudocType;var token=tokens[pos];var line=token.ln;var column=token.col;pos++;var content=getIdentOrInterpolation();var l=tokens[pos].ln;var c=tokens[pos].col;var value=[];pos++;if(checkUnary(pos))value.push(getUnary());if(checkNumber(pos))value.push(getNumber());{var _l=tokens[pos].ln;var _c=tokens[pos].col;var _content=tokens[pos].value;var ident=newNode(NodeType.IdentType,_content,_l,_c);value.push(ident);pos++;}value=value.concat(getSC());if(checkUnary(pos))value.push(getUnary());value=value.concat(getSC());if(checkNumber(pos))value.push(getNumber());value=value.concat(getSC());var end=getLastPosition(value,l,c,1);var args=newNode(NodeType.ArgumentsType,value,l,c,end);content.push(args);pos++;return newNode(type,content,line,column);}function checkPseudoClass4(i){var start=i;var l=0;i++;if(i>=tokensLength)return 0;if(l=checkIdentOrInterpolation(i))i+=l;else return 0;if(i>=tokensLength)return 0;if(tokens[i].type!==TokenType.LeftParenthesis)return 0;var right=tokens[i].right;i++;if(l=checkSC(i))i+=l;if(l=checkUnary(i))i+=l;if(tokens[i].type===TokenType.DecimalNumber)i++;if(tokens[i].value==='n')i++;else return 0;if(l=checkSC(i))i+=l;if(i!==right)return 0;return i-start+1;}function getPseudoClass4(){var type=NodeType.PseudocType;var token=tokens[pos];var line=token.ln;var column=token.col;pos++;var content=getIdentOrInterpolation();var l=tokens[pos].ln;var c=tokens[pos].col;var value=[];pos++;value=value.concat(getSC());if(checkUnary(pos))value.push(getUnary());if(checkNumber(pos))value.push(getNumber());if(checkIdent(pos))value.push(getIdent());value=value.concat(getSC());var end=getLastPosition(value,l,c,1);var args=newNode(NodeType.ArgumentsType,value,l,c,end);content.push(args);pos++;return newNode(type,content,line,column);}function checkPseudoClass5(i){var start=i;var l=0;i++;if(i>=tokensLength)return 0;if(l=checkIdentOrInterpolation(i))i+=l;else return 0;if(i>=tokensLength)return 0;if(tokens[i].type!==TokenType.LeftParenthesis)return 0;var right=tokens[i].right;i++;if(l=checkSC(i))i+=l;if(l=checkUnary(i))i+=l;if(tokens[i].type===TokenType.DecimalNumber)i++;else return 0;if(l=checkSC(i))i+=l;if(i!==right)return 0;return i-start+1;}function getPseudoClass5(){var type=NodeType.PseudocType;var token=tokens[pos];var line=token.ln;var column=token.col;pos++;var content=getIdentOrInterpolation();var l=tokens[pos].ln;var c=tokens[pos].col;var value=[];pos++;if(checkUnary(pos))value.push(getUnary());if(checkNumber(pos))value.push(getNumber());value=value.concat(getSC());var end=getLastPosition(value,l,c,1);var args=newNode(NodeType.ArgumentsType,value,l,c,end);content.push(args);pos++;return newNode(type,content,line,column);}function checkPseudoClass6(i){var start=i;var l=0;i++;if(i>=tokensLength)return 0;if(l=checkIdentOrInterpolation(i))i+=l;else return 0;return i-start;}function getPseudoClass6(){var type=NodeType.PseudocType;var token=tokens[pos];var line=token.ln;var column=token.col;pos++;var content=getIdentOrInterpolation();return newNode(type,content,line,column);}function checkRuleset(i){var start=i;var l=undefined;if(i>=tokensLength)return 0;if(l=checkSelectorsGroup(i))i+=l;else return 0;if(l=checkSC(i))i+=l;if(l=checkBlock(i))i+=l;else return 0;return i-start;}function getRuleset(){var type=NodeType.RulesetType;var token=tokens[pos];var line=token.ln;var column=token.col;var content=[];content=content.concat(getSelectorsGroup());content=content.concat(getSC());content.push(getBlock());return newNode(type,content,line,column);}function checkS(i){return i<tokensLength&&tokens[i].ws?tokens[i].ws_last-i+1:0;}function getS(){var startPos=pos;var x=joinValues(pos,tokens[pos].ws_last);pos=tokens[pos].ws_last+1;var token=tokens[startPos];return newNode(NodeType.SType,x,token.ln,token.col);}function checkSC(i){if(i>=tokensLength)return 0;var l=undefined;var lsc=0;while(i<tokensLength){if(!(l=checkS(i))&&!(l=checkCommentML(i))&&!(l=checkCommentSL(i)))break;i+=l;lsc+=l;}return lsc||0;}function getSC(){var sc=[];if(pos>=tokensLength)return sc;while(pos<tokensLength){if(checkS(pos))sc.push(getS());else if(checkCommentML(pos))sc.push(getCommentML());else if(checkCommentSL(pos))sc.push(getCommentSL());else break;}return sc;}function checkShash(i){var l;if(i>=tokensLength||tokens[i].type!==TokenType.NumberSign)return 0;return(l=checkIdentOrInterpolation(i+1))?l+1:0;}function getShash(){var startPos=pos;var token=tokens[startPos];pos++;var x=getIdentOrInterpolation();return newNode(NodeType.ShashType,x,token.ln,token.col);}function checkString(i){return i<tokensLength&&(tokens[i].type===TokenType.StringSQ||tokens[i].type===TokenType.StringDQ)?1:0;}function getString(){var startPos=pos;var x=tokens[pos++].value;var token=tokens[startPos];return newNode(NodeType.StringType,x,token.ln,token.col);}function checkStylesheet(i){var start=i;var l=undefined;while(i<tokensLength){if(l=checkSC(i)||checkDeclaration(i)||checkDeclDelim(i)||checkInclude(i)||checkExtend(i)||checkMixin(i)||checkLoop(i)||checkConditionalStatement(i)||checkAtrule(i)||checkRuleset(i))i+=l;else throwError(i);}return i-start;}function getStylesheet(){var startPos=pos;var x=[];while(pos<tokensLength){if(checkSC(pos))x=x.concat(getSC());else if(checkRuleset(pos))x.push(getRuleset());else if(checkInclude(pos))x.push(getInclude());else if(checkExtend(pos))x.push(getExtend());else if(checkMixin(pos))x.push(getMixin());else if(checkLoop(pos))x.push(getLoop());else if(checkConditionalStatement(pos))x.push(getConditionalStatement());else if(checkAtrule(pos))x.push(getAtrule());else if(checkDeclaration(pos))x.push(getDeclaration());else if(checkDeclDelim(pos))x.push(getDeclDelim());else throwError();}var token=tokens[startPos];return newNode(NodeType.StylesheetType,x,token.ln,token.col);}function checkTset(i){return checkVhash(i)||checkOperator(i)||checkAny(i)||checkSC(i)||checkInterpolation(i);}function getTset(){if(checkVhash(pos))return getVhash();else if(checkOperator(pos))return getOperator();else if(checkAny(pos))return getAny();else if(checkSC(pos))return getSC();else if(checkInterpolation(pos))return getInterpolation();}function checkTsets(i){var start=i;var l=undefined;if(i>=tokensLength)return 0;while(l=checkTset(i)){i+=l;}return i-start;}function getTsets(){var x=[];var t=undefined;while(t=getTset()){if(typeof t.content==='string')x.push(t);else x=x.concat(t);}return x;}function checkUnary(i){return i<tokensLength&&(tokens[i].type===TokenType.HyphenMinus||tokens[i].type===TokenType.PlusSign)?1:0;}function getUnary(){var startPos=pos;var x=tokens[pos++].value;var token=tokens[startPos];return newNode(NodeType.OperatorType,x,token.ln,token.col);}function checkUri(i){var start=i;if(i>=tokensLength||tokens[i++].value!=='url'||i>=tokensLength||tokens[i].type!==TokenType.LeftParenthesis)return 0;return tokens[i].right-start+1;}function getUri(){var startPos=pos;var uriExcluding={};var uri=undefined;var token=undefined;var l=undefined;var raw=undefined;pos+=2;uriExcluding[TokenType.Space]=1;uriExcluding[TokenType.Tab]=1;uriExcluding[TokenType.Newline]=1;uriExcluding[TokenType.LeftParenthesis]=1;uriExcluding[TokenType.RightParenthesis]=1;if(checkUriContent(pos)){uri=[].concat(getSC()).concat(getUriContent()).concat(getSC());}else{uri=[].concat(getSC());l=checkExcluding(uriExcluding,pos);token=tokens[pos];raw=newNode(NodeType.RawType,joinValues(pos,pos+l),token.ln,token.col);uri.push(raw);pos+=l+1;uri=uri.concat(getSC());}token=tokens[startPos];var line=token.ln;var column=token.col;var end=getLastPosition(uri,line,column,1);pos++;return newNode(NodeType.UriType,uri,token.ln,token.col,end);}function checkUriContent(i){return checkUri1(i)||checkFunction(i);}function getUriContent(){if(checkUri1(pos))return getString();else if(checkFunction(pos))return getFunction();}function checkUri1(i){var start=i;var l=undefined;if(i>=tokensLength)return 0;if(l=checkSC(i))i+=l;if(tokens[i].type!==TokenType.StringDQ&&tokens[i].type!==TokenType.StringSQ)return 0;i++;if(l=checkSC(i))i+=l;return i-start;}function checkValue(i){var start=i;var l=undefined;var s=undefined;var _i=undefined;while(i<tokensLength){if(checkDeclDelim(i))break;s=checkSC(i);_i=i+s;if(l=_checkValue(_i))i+=l+s;if(!l||checkBlock(i-l))break;}return i-start;}function _checkValue(i){return checkInterpolation(i)||checkVariable(i)||checkVhash(i)||checkBlock(i)||checkAtkeyword(i)||checkOperator(i)||checkImportant(i)||checkGlobal(i)||checkDefault(i)||checkProgid(i)||checkAny(i);}function getValue(){var startPos=pos;var x=[];var _pos=undefined;var s=undefined;while(pos<tokensLength){s=checkSC(pos);_pos=pos+s;if(checkDeclDelim(_pos))break;if(!_checkValue(_pos))break;if(s)x=x.concat(getSC());x.push(_getValue());if(checkBlock(_pos))break;}var token=tokens[startPos];return newNode(NodeType.ValueType,x,token.ln,token.col);}function _getValue(){if(checkInterpolation(pos))return getInterpolation();else if(checkVariable(pos))return getVariable();else if(checkVhash(pos))return getVhash();else if(checkBlock(pos))return getBlock();else if(checkAtkeyword(pos))return getAtkeyword();else if(checkOperator(pos))return getOperator();else if(checkImportant(pos))return getImportant();else if(checkGlobal(pos))return getGlobal();else if(checkDefault(pos))return getDefault();else if(checkProgid(pos))return getProgid();else if(checkAny(pos))return getAny();}function checkVariable(i){var l;if(i>=tokensLength||tokens[i].type!==TokenType.DollarSign)return 0;return(l=checkIdent(i+1))?l+1:0;}function getVariable(){var startPos=pos;var x=[];pos++;x.push(getIdent());var token=tokens[startPos];return newNode(NodeType.VariableType,x,token.ln,token.col);}function checkVariablesList(i){var d=0;var l=undefined;if(i>=tokensLength)return 0;if(l=checkVariable(i))i+=l;else return 0;while(i<tokensLength&&tokens[i].type===TokenType.FullStop){d++;i++;}return d===3?l+d:0;}function getVariablesList(){var startPos=pos;var x=getVariable();var token=tokens[startPos];var line=token.ln;var column=token.col;var end=getLastPosition([x],line,column,3);pos+=3;return newNode(NodeType.VariablesListType,[x],token.ln,token.col,end);}function checkVhash(i){var l;if(i>=tokensLength||tokens[i].type!==TokenType.NumberSign)return 0;return(l=checkNmName2(i+1))?l+1:0;}function getVhash(){var startPos=pos;var x=undefined;var token=tokens[startPos];var line=token.ln;var column=token.col;pos++;x=getNmName2();var end=getLastPosition(x,line,column+1);return newNode(NodeType.VhashType,x,token.ln,token.col,end);}module.exports=function(_tokens,context){tokens=_tokens;tokensLength=tokens.length;pos=0;return contexts[context]();};function checkSelectorsGroup(i){if(i>=tokensLength)return 0;var start=i;var l=undefined;if(l=checkSelector(i))i+=l;else return 0;while(i<tokensLength){var sb=checkSC(i);var c=checkDelim(i+sb);if(!c)break;var sa=checkSC(i+sb+c);if(l=checkSelector(i+sb+c+sa))i+=sb+c+sa+l;else break;}tokens[start].selectorsGroupEnd=i;return i-start;}function getSelectorsGroup(){var selectorsGroup=[];var selectorsGroupEnd=tokens[pos].selectorsGroupEnd;selectorsGroup.push(getSelector());while(pos<selectorsGroupEnd){selectorsGroup=selectorsGroup.concat(getSC());selectorsGroup.push(getDelim());selectorsGroup=selectorsGroup.concat(getSC());selectorsGroup.push(getSelector());}return selectorsGroup;}function checkSelector(i){var l;if(l=checkSelector1(i))tokens[i].selectorType=1;else if(l=checkSelector2(i))tokens[i].selectorType=2;return l;}function getSelector(){var selectorType=tokens[pos].selectorType;if(selectorType===1)return getSelector1();else return getSelector2();}function checkSelector1(i){if(i>=tokensLength)return 0;var start=i;var l=undefined;if(l=checkCompoundSelector(i))i+=l;else return 0;while(i<tokensLength){var s=checkSC(i);var c=checkCombinator(i+s);if(!s&&!c)break;if(c){i+=s+c;s=checkSC(i);}if(l=checkCompoundSelector(i+s))i+=s+l;else break;}tokens[start].selectorEnd=i;return i-start;}function getSelector1(){var type=NodeType.SelectorType;var token=tokens[pos];var line=token.ln;var column=token.col;var selectorEnd=token.selectorEnd;var content=getCompoundSelector();while(pos<selectorEnd){if(checkSC(pos))content=content.concat(getSC());else if(checkCombinator(pos))content.push(getCombinator());else if(checkCompoundSelector(pos))content=content.concat(getCompoundSelector());}return newNode(type,content,line,column);}function checkSelector2(i){if(i>=tokensLength)return 0;var start=i;var l=undefined;if(l=checkCombinator(i))i+=l;else return 0;while(i<tokensLength){var sb=checkSC(i);if(l=checkCompoundSelector(i+sb))i+=sb+l;else break;var sa=checkSC(i);var c=checkCombinator(i+sa);if(!sa&&!c)break;if(c){i+=sa+c;}}tokens[start].selectorEnd=i;return i-start;}function getSelector2(){var type=NodeType.SelectorType;var token=tokens[pos];var line=token.ln;var column=token.col;var selectorEnd=token.selectorEnd;var content=[getCombinator()];while(pos<selectorEnd){if(checkSC(pos))content=content.concat(getSC());else if(checkCombinator(pos))content.push(getCombinator());else if(checkCompoundSelector(pos))content=content.concat(getCompoundSelector());}return newNode(type,content,line,column);}function checkCompoundSelector(i){var l=undefined;if(l=checkCompoundSelector1(i)){tokens[i].compoundSelectorType=1;}else if(l=checkCompoundSelector2(i)){tokens[i].compoundSelectorType=2;}return l;}function getCompoundSelector(){var type=tokens[pos].compoundSelectorType;if(type===1)return getCompoundSelector1();if(type===2)return getCompoundSelector2();}function checkCompoundSelector1(i){if(i>=tokensLength)return 0;var start=i;var l=undefined;if(l=checkTypeSelector(i)||checkPlaceholder(i)||checkParentSelectorWithExtension(i))i+=l;else return 0;while(i<tokensLength){var _l2=checkShash(i)||checkClass(i)||checkAttributeSelector(i)||checkPseudo(i)||checkPlaceholder(i);if(_l2)i+=_l2;else break;}tokens[start].compoundSelectorEnd=i;return i-start;}function getCompoundSelector1(){var sequence=[];var compoundSelectorEnd=tokens[pos].compoundSelectorEnd;if(checkTypeSelector(pos))sequence.push(getTypeSelector());else if(checkPlaceholder(pos))sequence.push(getPlaceholder());else if(checkParentSelectorWithExtension(pos))sequence=sequence.concat(getParentSelectorWithExtension());while(pos<compoundSelectorEnd){if(checkShash(pos))sequence.push(getShash());else if(checkClass(pos))sequence.push(getClass());else if(checkAttributeSelector(pos))sequence.push(getAttributeSelector());else if(checkPseudo(pos))sequence.push(getPseudo());else if(checkPlaceholder(pos))sequence.push(getPlaceholder());}return sequence;}function checkCompoundSelector2(i){if(i>=tokensLength)return 0;var start=i;while(i<tokensLength){var l=checkShash(i)||checkClass(i)||checkAttributeSelector(i)||checkPseudo(i)||checkPlaceholder(i);if(l)i+=l;else break;}tokens[start].compoundSelectorEnd=i;return i-start;}function getCompoundSelector2(){var sequence=[];var compoundSelectorEnd=tokens[pos].compoundSelectorEnd;while(pos<compoundSelectorEnd){if(checkShash(pos))sequence.push(getShash());else if(checkClass(pos))sequence.push(getClass());else if(checkAttributeSelector(pos))sequence.push(getAttributeSelector());else if(checkPseudo(pos))sequence.push(getPseudo());else if(checkPlaceholder(pos))sequence.push(getPlaceholder());}return sequence;}function checkTypeSelector(i){if(i>=tokensLength)return 0;var start=i;var l=undefined;if(l=checkNamePrefix(i))i+=l;if(tokens[i].type===TokenType.Asterisk)i++;else if(l=checkIdentOrInterpolation(i))i+=l;else return 0;return i-start;}function getTypeSelector(){var type=NodeType.TypeSelectorType;var token=tokens[pos];var line=token.ln;var column=token.col;var content=[];if(checkNamePrefix(pos))content.push(getNamePrefix());if(checkIdentOrInterpolation(pos))content=content.concat(getIdentOrInterpolation());return newNode(type,content,line,column);}function checkAttributeSelector(i){var l=undefined;if(l=checkAttributeSelector1(i))tokens[i].attributeSelectorType=1;else if(l=checkAttributeSelector2(i))tokens[i].attributeSelectorType=2;return l;}function getAttributeSelector(){var type=tokens[pos].attributeSelectorType;if(type===1)return getAttributeSelector1();else return getAttributeSelector2();}function checkAttributeSelector1(i){var start=i;if(tokens[i].type===TokenType.LeftSquareBracket)i++;else return 0;var l=undefined;if(l=checkSC(i))i+=l;if(l=checkAttributeName(i))i+=l;else return 0;if(l=checkSC(i))i+=l;if(l=checkAttributeMatch(i))i+=l;else return 0;if(l=checkSC(i))i+=l;if(l=checkAttributeValue(i))i+=l;else return 0;if(l=checkSC(i))i+=l;if(l=checkAttributeFlags(i)){i+=l;if(l=checkSC(i))i+=l;}if(tokens[i].type===TokenType.RightSquareBracket)i++;else return 0;return i-start;}function getAttributeSelector1(){var type=NodeType.AttributeSelectorType;var token=tokens[pos];var line=token.ln;var column=token.col;var content=[];pos++;content=content.concat(getSC());content.push(getAttributeName());content=content.concat(getSC());content.push(getAttributeMatch());content=content.concat(getSC());content.push(getAttributeValue());content=content.concat(getSC());if(checkAttributeFlags(pos)){content.push(getAttributeFlags());content=content.concat(getSC());}
pos++;var end=getLastPosition(content,line,column,1);return newNode(type,content,line,column,end);}function checkAttributeSelector2(i){var start=i;if(tokens[i].type===TokenType.LeftSquareBracket)i++;else return 0;var l=undefined;if(l=checkSC(i))i+=l;if(l=checkAttributeName(i))i+=l;else return 0;if(l=checkSC(i))i+=l;if(tokens[i].type===TokenType.RightSquareBracket)i++;else return 0;return i-start;}function getAttributeSelector2(){var type=NodeType.AttributeSelectorType;var token=tokens[pos];var line=token.ln;var column=token.col;var content=[];pos++;content=content.concat(getSC());content.push(getAttributeName());content=content.concat(getSC());pos++;var end=getLastPosition(content,line,column,1);return newNode(type,content,line,column,end);}function checkAttributeName(i){var start=i;var l=undefined;if(l=checkNamePrefix(i))i+=l;if(l=checkIdentOrInterpolation(i))i+=l;else return 0;return i-start;}function getAttributeName(){var type=NodeType.AttributeNameType;var token=tokens[pos];var line=token.ln;var column=token.col;var content=[];if(checkNamePrefix(pos))content.push(getNamePrefix());content=content.concat(getIdentOrInterpolation());return newNode(type,content,line,column);}function checkAttributeMatch(i){var l=undefined;if(l=checkAttributeMatch1(i))tokens[i].attributeMatchType=1;else if(l=checkAttributeMatch2(i))tokens[i].attributeMatchType=2;return l;}function getAttributeMatch(){var type=tokens[pos].attributeMatchType;if(type===1)return getAttributeMatch1();else return getAttributeMatch2();}function checkAttributeMatch1(i){var start=i;var type=tokens[i].type;if(type===TokenType.Tilde||type===TokenType.VerticalLine||type===TokenType.CircumflexAccent||type===TokenType.DollarSign||type===TokenType.Asterisk)i++;else return 0;if(tokens[i].type===TokenType.EqualsSign)i++;else return 0;return i-start;}function getAttributeMatch1(){var type=NodeType.AttributeMatchType;var token=tokens[pos];var line=token.ln;var column=token.col;var content=tokens[pos].value+tokens[pos+1].value;pos+=2;return newNode(type,content,line,column);}function checkAttributeMatch2(i){if(tokens[i].type===TokenType.EqualsSign)return 1;else return 0;}function getAttributeMatch2(){var type=NodeType.AttributeMatchType;var token=tokens[pos];var line=token.ln;var column=token.col;var content='=';pos++;return newNode(type,content,line,column);}function checkAttributeValue(i){return checkString(i)||checkIdentOrInterpolation(i);}function getAttributeValue(){var type=NodeType.AttributeValueType;var token=tokens[pos];var line=token.ln;var column=token.col;var content=[];if(checkString(pos))content.push(getString());else content=content.concat(getIdentOrInterpolation());return newNode(type,content,line,column);}function checkAttributeFlags(i){return checkIdentOrInterpolation(i);}function getAttributeFlags(){var type=NodeType.AttributeFlagsType;var token=tokens[pos];var line=token.ln;var column=token.col;var content=getIdentOrInterpolation();return newNode(type,content,line,column);}function checkNamePrefix(i){if(i>=tokensLength)return 0;var l=undefined;if(l=checkNamePrefix1(i))tokens[i].namePrefixType=1;else if(l=checkNamePrefix2(i))tokens[i].namePrefixType=2;return l;}function getNamePrefix(){var type=tokens[pos].namePrefixType;if(type===1)return getNamePrefix1();else return getNamePrefix2();}function checkNamePrefix1(i){var start=i;var l=undefined;if(l=checkNamespacePrefix(i))i+=l;else return 0;if(l=checkCommentML(i))i+=l;if(l=checkNamespaceSeparator(i))i+=l;else return 0;return i-start;}function getNamePrefix1(){var type=NodeType.NamePrefixType;var token=tokens[pos];var line=token.ln;var column=token.col;var content=[];content.push(getNamespacePrefix());if(checkCommentML(pos))content.push(getCommentML());content.push(getNamespaceSeparator());return newNode(type,content,line,column);}function checkNamePrefix2(i){return checkNamespaceSeparator(i);}function getNamePrefix2(){var type=NodeType.NamePrefixType;var token=tokens[pos];var line=token.ln;var column=token.col;var content=[getNamespaceSeparator()];return newNode(type,content,line,column);}function checkNamespacePrefix(i){if(i>=tokensLength)return 0;var l=undefined;if(tokens[i].type===TokenType.Asterisk)return 1;else if(l=checkIdentOrInterpolation(i))return l;else return 0;}function getNamespacePrefix(){var type=NodeType.NamespacePrefixType;var token=tokens[pos];var line=token.ln;var column=token.col;var content=[];if(checkIdentOrInterpolation(pos))content=content.concat(getIdentOrInterpolation());return newNode(type,content,line,column);}function checkNamespaceSeparator(i){if(i>=tokensLength)return 0;if(tokens[i].type===TokenType.VerticalLine)return 1;else return 0;}function getNamespaceSeparator(){var type=NodeType.NamespaceSeparatorType;var token=tokens[pos];var line=token.ln;var column=token.col;var content='|';pos++;return newNode(type,content,line,column);}},function(module,exports){'use strict';module.exports={ArgumentsType:'arguments',AtkeywordType:'atkeyword',AtruleType:'atrule',AttributeSelectorType:'attributeSelector',AttributeNameType:'attributeName',AttributeFlagsType:'attributeFlags',AttributeMatchType:'attributeMatch',AttributeValueType:'attributeValue',BlockType:'block',BracketsType:'brackets',ClassType:'class',CombinatorType:'combinator',CommentMLType:'multilineComment',CommentSLType:'singlelineComment',ConditionType:'condition',ConditionalStatementType:'conditionalStatement',DeclarationType:'declaration',DeclDelimType:'declarationDelimiter',DefaultType:'default',DelimType:'delimiter',DimensionType:'dimension',EscapedStringType:'escapedString',ExtendType:'extend',ExpressionType:'expression',FunctionType:'function',GlobalType:'global',IdentType:'ident',ImportantType:'important',IncludeType:'include',InterpolationType:'interpolation',InterpolatedVariableType:'interpolatedVariable',KeyframesSelectorType:'keyframesSelector',LoopType:'loop',MixinType:'mixin',NamePrefixType:'namePrefix',NamespacePrefixType:'namespacePrefix',NamespaceSeparatorType:'namespaceSeparator',NumberType:'number',OperatorType:'operator',OptionalType:'optional',ParenthesesType:'parentheses',ParentSelectorType:'parentSelector',ParentSelectorExtensionType:'parentSelectorExtension',PercentageType:'percentage',PlaceholderType:'placeholder',ProgidType:'progid',PropertyType:'property',PropertyDelimType:'propertyDelimiter',PseudocType:'pseudoClass',PseudoeType:'pseudoElement',RawType:'raw',RulesetType:'ruleset',SType:'space',SelectorType:'selector',ShashType:'id',StringType:'string',StylesheetType:'stylesheet',TypeSelectorType:'typeSelector',UriType:'uri',ValueType:'value',VariableType:'variable',VariablesListType:'variablesList',VhashType:'color'};},function(module,exports,__webpack_require__){'use strict';module.exports=function(css,tabSize){var TokenType=__webpack_require__(12);var tokens=[];var urlMode=false;var blockMode=0;var c=undefined;var cn=undefined;var pos=0;var tn=0;var ln=1;var col=1;var Punctuation={' ':TokenType.Space,'\n':TokenType.Newline,'\r':TokenType.Newline,'\t':TokenType.Tab,'!':TokenType.ExclamationMark,'"':TokenType.QuotationMark,'#':TokenType.NumberSign,'$':TokenType.DollarSign,'%':TokenType.PercentSign,'&':TokenType.Ampersand,'\'':TokenType.Apostrophe,'(':TokenType.LeftParenthesis,')':TokenType.RightParenthesis,'*':TokenType.Asterisk,'+':TokenType.PlusSign,',':TokenType.Comma,'-':TokenType.HyphenMinus,'.':TokenType.FullStop,'/':TokenType.Solidus,':':TokenType.Colon,';':TokenType.Semicolon,'<':TokenType.LessThanSign,'=':TokenType.EqualsSign,'==':TokenType.EqualitySign,'!=':TokenType.InequalitySign,'>':TokenType.GreaterThanSign,'?':TokenType.QuestionMark,'@':TokenType.CommercialAt,'[':TokenType.LeftSquareBracket,']':TokenType.RightSquareBracket,'^':TokenType.CircumflexAccent,'_':TokenType.LowLine,'{':TokenType.LeftCurlyBracket,'|':TokenType.VerticalLine,'}':TokenType.RightCurlyBracket,'~':TokenType.Tilde};function pushToken(type,value,column){tokens.push({tn:tn++,ln:ln,col:column,type:type,value:value});}
function isDecimalDigit(c){return'0123456789'.indexOf(c)>=0;}
function parseSpaces(css){var start=pos;for(;pos<css.length;pos++){if(css.charAt(pos)!==' ')break;}
pushToken(TokenType.Space,css.substring(start,pos--),col);col+=pos-start;}
function parseString(css,q){var start=pos;for(pos++;pos<css.length;pos++){if(css.charAt(pos)==='\\')pos++;else if(css.charAt(pos)===q)break;}
var type=q==='"'?TokenType.StringDQ:TokenType.StringSQ;pushToken(type,css.substring(start,pos+1),col);col+=pos-start;}
function parseDecimalNumber(css){var start=pos;for(;pos<css.length;pos++){if(!isDecimalDigit(css.charAt(pos)))break;}
pushToken(TokenType.DecimalNumber,css.substring(start,pos--),col);col+=pos-start;}
function parseIdentifier(css){var start=pos;while(css.charAt(pos)==='/')pos++;for(;pos<css.length;pos++){if(css.charAt(pos)==='\\')pos++;else if(css.charAt(pos)in Punctuation)break;}
var ident=css.substring(start,pos--);if(!urlMode&&ident==='url'&&css.charAt(pos+1)==='('){urlMode=true;}
pushToken(TokenType.Identifier,ident,col);col+=pos-start;}
function parseEquality(){pushToken(TokenType.EqualitySign,'==',col);pos++;col++;}
function parseInequality(){pushToken(TokenType.InequalitySign,'!=',col);pos++;col++;}
function parseMLComment(css){var start=pos;for(pos+=2;pos<css.length;pos++){if(css.charAt(pos)==='*'&&css.charAt(pos+1)==='/'){pos++;break;}}
var comment=css.substring(start,pos+1);pushToken(TokenType.CommentML,comment,col);var newlines=comment.split('\n');if(newlines.length>1){ln+=newlines.length-1;col=newlines[newlines.length-1].length;}else{col+=pos-start;}}
function parseSLComment(css){var start=pos;for(pos+=2;pos<css.length;pos++){if(css.charAt(pos)==='\n'||css.charAt(pos)==='\r'){break;}}
pushToken(TokenType.CommentSL,css.substring(start,pos--),col);col+=pos-start;}
function getTokens(css){for(pos=0;pos<css.length;col++,pos++){c=css.charAt(pos);cn=css.charAt(pos+1);if(c==='/'&&cn==='*'){parseMLComment(css);}
else if(!urlMode&&c==='/'&&cn==='/'){parseSLComment(css);}
else if(c==='"'||c==="'"){parseString(css,c);}
else if(c===' '){parseSpaces(css);}
else if(c==='='&&cn==='='){parseEquality(css);}
else if(c==='!'&&cn==='='){parseInequality(css);}
else if(c in Punctuation){if(c==='\r'&&cn==='\n'||c==='\n'){if(c==='\r'){pushToken(TokenType.Newline,'\r\n',col);pos++;}else if(c==='\n'){pushToken(Punctuation[c],c,col);}
ln++;col=0;}else if(c!=='\r'&&c!=='\n'){pushToken(Punctuation[c],c,col);}
if(c===')')urlMode=false;if(c==='{')blockMode++;if(c==='}')blockMode--;else if(c==='\t'&&tabSize>1)col+=tabSize-1;}
else if(isDecimalDigit(c)){parseDecimalNumber(css);}
else{parseIdentifier(css);}}
return tokens;}
return getTokens(css);};},function(module,exports,__webpack_require__){'use strict';var Node=__webpack_require__(1);var NodeTypes=__webpack_require__(14);module.exports=function(){return new Node({type:NodeTypes.StylesheetType,content:[],start:[0,0],end:[0,0]});};}])});;},{}],217:[function(require,module,exports){console=console;console.__originalAssert=console.assert;console.assert=function(value,message)
{if(value)
return;console.__originalAssert(value,message);}
var ArrayLike;function mod(m,n)
{return((m%n)+n)%n;}
String.prototype.findAll=function(string)
{var matches=[];var i=this.indexOf(string);while(i!==-1){matches.push(i);i=this.indexOf(string,i+string.length);}
return matches;}
String.prototype.replaceControlCharacters=function()
{return this.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u0080-\u009f]/g,"�");}
String.prototype.isWhitespace=function()
{return/^\s*$/.test(this);}
String.prototype.computeLineEndings=function()
{var endings=this.findAll("\n");endings.push(this.length);return endings;}
String.prototype.escapeCharacters=function(chars)
{var foundChar=false;for(var i=0;i<chars.length;++i){if(this.indexOf(chars.charAt(i))!==-1){foundChar=true;break;}}
if(!foundChar)
return String(this);var result="";for(var i=0;i<this.length;++i){if(chars.indexOf(this.charAt(i))!==-1)
result+="\\";result+=this.charAt(i);}
return result;}
String.regexSpecialCharacters=function()
{return"^[]{}()\\.^$*+?|-,";}
String.prototype.escapeForRegExp=function()
{return this.escapeCharacters(String.regexSpecialCharacters());}
String.prototype.escapeHTML=function()
{return this.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;");}
String.prototype.unescapeHTML=function()
{return this.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&#58;/g,":").replace(/&quot;/g,"\"").replace(/&#60;/g,"<").replace(/&#62;/g,">").replace(/&amp;/g,"&");}
String.prototype.collapseWhitespace=function()
{return this.replace(/[\s\xA0]+/g," ");}
String.prototype.trimMiddle=function(maxLength)
{if(this.length<=maxLength)
return String(this);var leftHalf=maxLength>>1;var rightHalf=maxLength-leftHalf-1;return this.substr(0,leftHalf)+"\u2026"+this.substr(this.length-rightHalf,rightHalf);}
String.prototype.trimEnd=function(maxLength)
{if(this.length<=maxLength)
return String(this);return this.substr(0,maxLength-1)+"\u2026";}
String.prototype.trimURL=function(baseURLDomain)
{var result=this.replace(/^(https|http|file):\/\//i,"");if(baseURLDomain){if(result.toLowerCase().startsWith(baseURLDomain.toLowerCase()))
result=result.substr(baseURLDomain.length);}
return result;}
String.prototype.toTitleCase=function()
{return this.substring(0,1).toUpperCase()+this.substring(1);}
String.prototype.compareTo=function(other)
{if(this>other)
return 1;if(this<other)
return-1;return 0;}
String.prototype.removeURLFragment=function()
{var fragmentIndex=this.indexOf("#");if(fragmentIndex===-1)
fragmentIndex=this.length;return this.substring(0,fragmentIndex);}
String.hashCode=function(string)
{if(!string)
return 0;var p=((1<<30)*4-5);var z=0x5033d967;var z2=0x59d2f15d;var s=0;var zi=1;for(var i=0;i<string.length;i++){var xi=string.charCodeAt(i)*z2;s=(s+zi*xi)%p;zi=(zi*z)%p;}
s=(s+zi*(p-1))%p;return Math.abs(s|0);}
String.isDigitAt=function(string,index)
{var c=string.charCodeAt(index);return(48<=c&&c<=57);}
String.prototype.toBase64=function()
{function encodeBits(b)
{return b<26?b+65:b<52?b+71:b<62?b-4:b===62?43:b===63?47:65;}
var encoder=new TextEncoder();var data=encoder.encode(this.toString());var n=data.length;var encoded="";if(n===0)
return encoded;var shift;var v=0;for(var i=0;i<n;i++){shift=i%3;v|=data[i]<<(16>>>shift&24);if(shift===2){encoded+=String.fromCharCode(encodeBits(v>>>18&63),encodeBits(v>>>12&63),encodeBits(v>>>6&63),encodeBits(v&63));v=0;}}
if(shift===0)
encoded+=String.fromCharCode(encodeBits(v>>>18&63),encodeBits(v>>>12&63),61,61);else if(shift===1)
encoded+=String.fromCharCode(encodeBits(v>>>18&63),encodeBits(v>>>12&63),encodeBits(v>>>6&63),61);return encoded;}
String.naturalOrderComparator=function(a,b)
{var chunk=/^\d+|^\D+/;var chunka,chunkb,anum,bnum;while(1){if(a){if(!b)
return 1;}else{if(b)
return-1;else
return 0;}
chunka=a.match(chunk)[0];chunkb=b.match(chunk)[0];anum=!isNaN(chunka);bnum=!isNaN(chunkb);if(anum&&!bnum)
return-1;if(bnum&&!anum)
return 1;if(anum&&bnum){var diff=chunka-chunkb;if(diff)
return diff;if(chunka.length!==chunkb.length){if(!+chunka&&!+chunkb)
return chunka.length-chunkb.length;else
return chunkb.length-chunka.length;}}else if(chunka!==chunkb)
return(chunka<chunkb)?-1:1;a=a.substring(chunka.length);b=b.substring(chunkb.length);}}
String.caseInsensetiveComparator=function(a,b)
{a=a.toUpperCase();b=b.toUpperCase();if(a===b)
return 0;return a>b?1:-1;}
Number.constrain=function(num,min,max)
{if(num<min)
num=min;else if(num>max)
num=max;return num;}
Number.gcd=function(a,b)
{if(b===0)
return a;else
return Number.gcd(b,a%b);}
Number.toFixedIfFloating=function(value)
{if(!value||isNaN(value))
return value;var number=Number(value);return number%1?number.toFixed(3):String(number);}
Date.prototype.toISO8601Compact=function()
{function leadZero(x)
{return(x>9?"":"0")+x;}
return this.getFullYear()+
leadZero(this.getMonth()+1)+
leadZero(this.getDate())+"T"+
leadZero(this.getHours())+
leadZero(this.getMinutes())+
leadZero(this.getSeconds());}
Date.prototype.toConsoleTime=function()
{function leadZero2(x)
{return(x>9?"":"0")+x;}
function leadZero3(x)
{return"0".repeat(3-x.toString().length)+x;}
return this.getFullYear()+"-"+
leadZero2(this.getMonth()+1)+"-"+
leadZero2(this.getDate())+" "+
leadZero2(this.getHours())+":"+
leadZero2(this.getMinutes())+":"+
leadZero2(this.getSeconds())+"."+
leadZero3(this.getMilliseconds());}
Object.defineProperty(Array.prototype,"remove",{value:function(value,firstOnly)
{var index=this.indexOf(value);if(index===-1)
return false;if(firstOnly){this.splice(index,1);return true;}
for(var i=index+1,n=this.length;i<n;++i){if(this[i]!==value)
this[index++]=this[i];}
this.length=index;return true;}});Object.defineProperty(Array.prototype,"pushAll",{value:function(array)
{Array.prototype.push.apply(this,array);}});Object.defineProperty(Array.prototype,"rotate",{value:function(index)
{var result=[];for(var i=index;i<index+this.length;++i)
result.push(this[i%this.length]);return result;}});Object.defineProperty(Array.prototype,"sortNumbers",{value:function()
{function numericComparator(a,b)
{return a-b;}
this.sort(numericComparator);}});Object.defineProperty(Uint32Array.prototype,"sort",{value:Array.prototype.sort});(function(){var partition={value:function(comparator,left,right,pivotIndex)
{function swap(array,i1,i2)
{var temp=array[i1];array[i1]=array[i2];array[i2]=temp;}
var pivotValue=this[pivotIndex];swap(this,right,pivotIndex);var storeIndex=left;for(var i=left;i<right;++i){if(comparator(this[i],pivotValue)<0){swap(this,storeIndex,i);++storeIndex;}}
swap(this,right,storeIndex);return storeIndex;}};Object.defineProperty(Array.prototype,"partition",partition);Object.defineProperty(Uint32Array.prototype,"partition",partition);var sortRange={value:function(comparator,leftBound,rightBound,sortWindowLeft,sortWindowRight)
{function quickSortRange(array,comparator,left,right,sortWindowLeft,sortWindowRight)
{if(right<=left)
return;var pivotIndex=Math.floor(Math.random()*(right-left))+left;var pivotNewIndex=array.partition(comparator,left,right,pivotIndex);if(sortWindowLeft<pivotNewIndex)
quickSortRange(array,comparator,left,pivotNewIndex-1,sortWindowLeft,sortWindowRight);if(pivotNewIndex<sortWindowRight)
quickSortRange(array,comparator,pivotNewIndex+1,right,sortWindowLeft,sortWindowRight);}
if(leftBound===0&&rightBound===(this.length-1)&&sortWindowLeft===0&&sortWindowRight>=rightBound)
this.sort(comparator);else
quickSortRange(this,comparator,leftBound,rightBound,sortWindowLeft,sortWindowRight);return this;}}
Object.defineProperty(Array.prototype,"sortRange",sortRange);Object.defineProperty(Uint32Array.prototype,"sortRange",sortRange);})();Object.defineProperty(Array.prototype,"stableSort",{value:function(comparator)
{function defaultComparator(a,b)
{return a<b?-1:(a>b?1:0);}
comparator=comparator||defaultComparator;var indices=new Array(this.length);for(var i=0;i<this.length;++i)
indices[i]=i;var self=this;function indexComparator(a,b)
{var result=comparator(self[a],self[b]);return result?result:a-b;}
indices.sort(indexComparator);for(var i=0;i<this.length;++i){if(indices[i]<0||i===indices[i])
continue;var cyclical=i;var saved=this[i];while(true){var next=indices[cyclical];indices[cyclical]=-1;if(next===i){this[cyclical]=saved;break;}else{this[cyclical]=this[next];cyclical=next;}}}
return this;}});Object.defineProperty(Array.prototype,"qselect",{value:function(k,comparator)
{if(k<0||k>=this.length)
return;if(!comparator)
comparator=function(a,b){return a-b;}
var low=0;var high=this.length-1;for(;;){var pivotPosition=this.partition(comparator,low,high,Math.floor((high+low)/2));if(pivotPosition===k)
return this[k];else if(pivotPosition>k)
high=pivotPosition-1;else
low=pivotPosition+1;}}});Object.defineProperty(Array.prototype,"lowerBound",{value:function(object,comparator,left,right)
{function defaultComparator(a,b)
{return a<b?-1:(a>b?1:0);}
comparator=comparator||defaultComparator;var l=left||0;var r=right!==undefined?right:this.length;while(l<r){var m=(l+r)>>1;if(comparator(object,this[m])>0)
l=m+1;else
r=m;}
return r;}});Object.defineProperty(Array.prototype,"upperBound",{value:function(object,comparator,left,right)
{function defaultComparator(a,b)
{return a<b?-1:(a>b?1:0);}
comparator=comparator||defaultComparator;var l=left||0;var r=right!==undefined?right:this.length;while(l<r){var m=(l+r)>>1;if(comparator(object,this[m])>=0)
l=m+1;else
r=m;}
return r;}});Object.defineProperty(Uint32Array.prototype,"lowerBound",{value:Array.prototype.lowerBound});Object.defineProperty(Uint32Array.prototype,"upperBound",{value:Array.prototype.upperBound});Object.defineProperty(Float64Array.prototype,"lowerBound",{value:Array.prototype.lowerBound});Object.defineProperty(Array.prototype,"binaryIndexOf",{value:function(value,comparator)
{var index=this.lowerBound(value,comparator);return index<this.length&&comparator(value,this[index])===0?index:-1;}});Object.defineProperty(Array.prototype,"select",{value:function(field)
{var result=new Array(this.length);for(var i=0;i<this.length;++i)
result[i]=this[i][field];return result;}});Object.defineProperty(Array.prototype,"peekLast",{value:function()
{return this[this.length-1];}});(function(){function mergeOrIntersect(array1,array2,comparator,mergeNotIntersect)
{var result=[];var i=0;var j=0;while(i<array1.length&&j<array2.length){var compareValue=comparator(array1[i],array2[j]);if(mergeNotIntersect||!compareValue)
result.push(compareValue<=0?array1[i]:array2[j]);if(compareValue<=0)
i++;if(compareValue>=0)
j++;}
if(mergeNotIntersect){while(i<array1.length)
result.push(array1[i++]);while(j<array2.length)
result.push(array2[j++]);}
return result;}
Object.defineProperty(Array.prototype,"intersectOrdered",{value:function(array,comparator)
{return mergeOrIntersect(this,array,comparator,false);}});Object.defineProperty(Array.prototype,"mergeOrdered",{value:function(array,comparator)
{return mergeOrIntersect(this,array,comparator,true);}});})();String.sprintf=function(format,var_arg)
{return String.vsprintf(format,Array.prototype.slice.call(arguments,1));}
String.tokenizeFormatString=function(format,formatters)
{var tokens=[];var substitutionIndex=0;function addStringToken(str)
{if(tokens.length&&tokens[tokens.length-1].type==="string")
tokens[tokens.length-1].value+=str;else
tokens.push({type:"string",value:str});}
function addSpecifierToken(specifier,precision,substitutionIndex)
{tokens.push({type:"specifier",specifier:specifier,precision:precision,substitutionIndex:substitutionIndex});}
var index=0;for(var precentIndex=format.indexOf("%",index);precentIndex!==-1;precentIndex=format.indexOf("%",index)){if(format.length===index)
break;addStringToken(format.substring(index,precentIndex));index=precentIndex+1;if(format[index]==="%"){addStringToken("%");++index;continue;}
if(String.isDigitAt(format,index)){var number=parseInt(format.substring(index),10);while(String.isDigitAt(format,index))
++index;if(number>0&&format[index]==="$"){substitutionIndex=(number-1);++index;}}
var precision=-1;if(format[index]==="."){++index;precision=parseInt(format.substring(index),10);if(isNaN(precision))
precision=0;while(String.isDigitAt(format,index))
++index;}
if(!(format[index]in formatters)){addStringToken(format.substring(precentIndex,index+1));++index;continue;}
addSpecifierToken(format[index],precision,substitutionIndex);++substitutionIndex;++index;}
addStringToken(format.substring(index));return tokens;}
String.standardFormatters={d:function(substitution)
{return!isNaN(substitution)?substitution:0;},f:function(substitution,token)
{if(substitution&&token.precision>-1)
substitution=substitution.toFixed(token.precision);return!isNaN(substitution)?substitution:(token.precision>-1?Number(0).toFixed(token.precision):0);},s:function(substitution)
{return substitution;}}
String.vsprintf=function(format,substitutions)
{return String.format(format,substitutions,String.standardFormatters,"",function(a,b){return a+b;}).formattedResult;}
String.format=function(format,substitutions,formatters,initialValue,append,tokenizedFormat)
{if(!format||!substitutions||!substitutions.length)
return{formattedResult:append(initialValue,format),unusedSubstitutions:substitutions};function prettyFunctionName()
{return"String.format(\""+format+"\", \""+Array.prototype.join.call(substitutions,"\", \"")+"\")";}
function warn(msg)
{console.warn(prettyFunctionName()+": "+msg);}
function error(msg)
{console.error(prettyFunctionName()+": "+msg);}
var result=initialValue;var tokens=tokenizedFormat||String.tokenizeFormatString(format,formatters);var usedSubstitutionIndexes={};for(var i=0;i<tokens.length;++i){var token=tokens[i];if(token.type==="string"){result=append(result,token.value);continue;}
if(token.type!=="specifier"){error("Unknown token type \""+token.type+"\" found.");continue;}
if(token.substitutionIndex>=substitutions.length){error("not enough substitution arguments. Had "+substitutions.length+" but needed "+(token.substitutionIndex+1)+", so substitution was skipped.");result=append(result,"%"+(token.precision>-1?token.precision:"")+token.specifier);continue;}
usedSubstitutionIndexes[token.substitutionIndex]=true;if(!(token.specifier in formatters)){warn("unsupported format character \u201C"+token.specifier+"\u201D. Treating as a string.");result=append(result,substitutions[token.substitutionIndex]);continue;}
result=append(result,formatters[token.specifier](substitutions[token.substitutionIndex],token));}
var unusedSubstitutions=[];for(var i=0;i<substitutions.length;++i){if(i in usedSubstitutionIndexes)
continue;unusedSubstitutions.push(substitutions[i]);}
return{formattedResult:result,unusedSubstitutions:unusedSubstitutions};}
function createSearchRegex(query,caseSensitive,isRegex)
{var regexFlags=caseSensitive?"g":"gi";var regexObject;if(isRegex){try{regexObject=new RegExp(query,regexFlags);}catch(e){}}
if(!regexObject)
regexObject=createPlainTextSearchRegex(query,regexFlags);return regexObject;}
function createPlainTextSearchRegex(query,flags)
{var regexSpecialCharacters=String.regexSpecialCharacters();var regex="";for(var i=0;i<query.length;++i){var c=query.charAt(i);if(regexSpecialCharacters.indexOf(c)!==-1)
regex+="\\";regex+=c;}
return new RegExp(regex,flags||"");}
function countRegexMatches(regex,content)
{var text=content;var result=0;var match;while(text&&(match=regex.exec(text))){if(match[0].length>0)
++result;text=text.substring(match.index+1);}
return result;}
function spacesPadding(spacesCount)
{return"\u00a0".repeat(spacesCount);}
function numberToStringWithSpacesPadding(value,symbolsCount)
{var numberString=value.toString();var paddingLength=Math.max(0,symbolsCount-numberString.length);return spacesPadding(paddingLength)+numberString;}
Set.prototype.valuesArray=function()
{return Array.from(this.values());}
Set.prototype.addAll=function(iterable)
{for(var e of iterable)
this.add(e);}
Set.prototype.containsAll=function(iterable)
{for(var e of iterable){if(!this.has(e))
return false;}
return true;}
Map.prototype.remove=function(key)
{var value=this.get(key);this.delete(key);return value;}
Map.prototype.valuesArray=function()
{return Array.from(this.values());}
Map.prototype.keysArray=function()
{return Array.from(this.keys());}
Map.prototype.inverse=function()
{var result=new Multimap();for(var key of this.keys()){var value=this.get(key);result.set(value,key);}
return result;}
var Multimap=function()
{this._map=new Map();}
Multimap.prototype={set:function(key,value)
{var set=this._map.get(key);if(!set){set=new Set();this._map.set(key,set);}
set.add(value);},get:function(key)
{var result=this._map.get(key);if(!result)
result=new Set();return result;},has:function(key)
{return this._map.has(key);},hasValue:function(key,value)
{var set=this._map.get(key);if(!set)
return false;return set.has(value);},get size()
{return this._map.size;},remove:function(key,value)
{var values=this.get(key);values.delete(value);if(!values.size)
this._map.delete(key);},removeAll:function(key)
{this._map.delete(key);},keysArray:function()
{return this._map.keysArray();},valuesArray:function()
{var result=[];var keys=this.keysArray();for(var i=0;i<keys.length;++i)
result.pushAll(this.get(keys[i]).valuesArray());return result;},clear:function()
{this._map.clear();}}
function loadXHR(url)
{return new Promise(load);function load(successCallback,failureCallback)
{function onReadyStateChanged()
{if(xhr.readyState!==XMLHttpRequest.DONE)
return;if(xhr.status!==200){xhr.onreadystatechange=null;failureCallback(new Error(xhr.status));return;}
xhr.onreadystatechange=null;successCallback(xhr.responseText);}
var xhr=new XMLHttpRequest();xhr.withCredentials=false;xhr.open("GET",url,true);xhr.onreadystatechange=onReadyStateChanged;xhr.send(null);}}
function CallbackBarrier()
{this._pendingIncomingCallbacksCount=0;}
CallbackBarrier.prototype={createCallback:function(userCallback)
{console.assert(!this._outgoingCallback,"CallbackBarrier.createCallback() is called after CallbackBarrier.callWhenDone()");++this._pendingIncomingCallbacksCount;return this._incomingCallback.bind(this,userCallback);},callWhenDone:function(callback)
{console.assert(!this._outgoingCallback,"CallbackBarrier.callWhenDone() is called multiple times");this._outgoingCallback=callback;if(!this._pendingIncomingCallbacksCount)
this._outgoingCallback();},donePromise:function()
{return new Promise(promiseConstructor.bind(this));function promiseConstructor(success)
{this.callWhenDone(success);}},_incomingCallback:function(userCallback)
{console.assert(this._pendingIncomingCallbacksCount>0);if(userCallback){var args=Array.prototype.slice.call(arguments,1);userCallback.apply(null,args);}
if(!--this._pendingIncomingCallbacksCount&&this._outgoingCallback)
this._outgoingCallback();}}
function suppressUnused(value)
{}
self.setImmediate=function(callback)
{Promise.resolve().then(callback);return 0;}
Promise.prototype.spread=function(callback)
{return this.then(spreadPromise);function spreadPromise(arg)
{return callback.apply(null,arg);}}
Promise.prototype.catchException=function(defaultValue){return this.catch(function(error){console.error(error);return defaultValue;});}
Map.prototype.diff=function(other,isEqual)
{var leftKeys=this.keysArray();var rightKeys=other.keysArray();leftKeys.sort((a,b)=>a-b);rightKeys.sort((a,b)=>a-b);var removed=[];var added=[];var equal=[];var leftIndex=0;var rightIndex=0;while(leftIndex<leftKeys.length&&rightIndex<rightKeys.length){var leftKey=leftKeys[leftIndex];var rightKey=rightKeys[rightIndex];if(leftKey===rightKey&&isEqual(this.get(leftKey),other.get(rightKey))){equal.push(this.get(leftKey));++leftIndex;++rightIndex;continue;}
if(leftKey<=rightKey){removed.push(this.get(leftKey));++leftIndex;continue;}
added.push(other.get(rightKey));++rightIndex;}
while(leftIndex<leftKeys.length){var leftKey=leftKeys[leftIndex++];removed.push(this.get(leftKey));}
while(rightIndex<rightKeys.length){var rightKey=rightKeys[rightIndex++];added.push(other.get(rightKey));}
return{added:added,removed:removed,equal:equal}}},{}],218:[function(require,module,exports){WebInspector.CPUProfileNode=function(node,sampleTime)
{var callFrame=node.callFrame||({functionName:node["functionName"],scriptId:node["scriptId"],url:node["url"],lineNumber:node["lineNumber"]-1,columnNumber:node["columnNumber"]-1});WebInspector.ProfileNode.call(this,callFrame);this.id=node.id;this.self=node.hitCount*sampleTime;this.positionTicks=node.positionTicks;this.deoptReason=node.deoptReason&&node.deoptReason!=="no reason"?node.deoptReason:null;}
WebInspector.CPUProfileNode.prototype={__proto__:WebInspector.ProfileNode.prototype}
WebInspector.CPUProfileDataModel=function(profile)
{var isLegacyFormat=!!profile["head"];if(isLegacyFormat){this.profileStartTime=profile.startTime*1000;this.profileEndTime=profile.endTime*1000;this.timestamps=profile.timestamps;this._compatibilityConversionHeadToNodes(profile);}else{this.profileStartTime=profile.startTime/1000;this.profileEndTime=profile.endTime/1000;this.timestamps=this._convertTimeDeltas(profile);}
this.samples=profile.samples;this.totalHitCount=0;this.profileHead=this._translateProfileTree(profile.nodes);WebInspector.ProfileTreeModel.call(this,this.profileHead);this._extractMetaNodes();if(this.samples){this._buildIdToNodeMap();this._sortSamples();this._normalizeTimestamps();}}
WebInspector.CPUProfileDataModel.prototype={_compatibilityConversionHeadToNodes:function(profile)
{if(!profile.head||profile.nodes)
return;var nodes=[];convertNodesTree(profile.head);profile.nodes=nodes;delete profile.head;function convertNodesTree(node)
{nodes.push(node);node.children=((node.children)).map(convertNodesTree);return node.id;}},_convertTimeDeltas:function(profile)
{if(!profile.timeDeltas)
return null;var lastTimeUsec=profile.startTime;var timestamps=new Array(profile.timeDeltas.length);for(var i=0;i<timestamps.length;++i){lastTimeUsec+=profile.timeDeltas[i];timestamps[i]=lastTimeUsec;}
return timestamps;},_translateProfileTree:function(nodes)
{function isNativeNode(node)
{if(node.callFrame)
return!!node.callFrame.url&&node.callFrame.url.startsWith("native ");return!!node.url&&node.url.startsWith("native ");}
function buildChildrenFromParents(nodes)
{if(nodes[0].children)
return;nodes[0].children=[];for(var i=1;i<nodes.length;++i){var node=nodes[i];var parentNode=nodeByIdMap.get(node.parent);if(parentNode.children)
parentNode.children.push(node.id);else
parentNode.children=[node.id];}}
var nodeByIdMap=new Map();for(var i=0;i<nodes.length;++i){var node=nodes[i];nodeByIdMap.set(node.id,node);}
buildChildrenFromParents(nodes);this.totalHitCount=nodes.reduce((acc,node)=>acc+node.hitCount,0);var sampleTime=(this.profileEndTime-this.profileStartTime)/this.totalHitCount;var keepNatives=!!WebInspector.moduleSetting("showNativeFunctionsInJSProfile").get();var root=nodes[0];var idMap=new Map([[root.id,root.id]]);var resultRoot=new WebInspector.CPUProfileNode(root,sampleTime);var parentNodeStack=root.children.map(()=>resultRoot);var sourceNodeStack=root.children.map(id=>nodeByIdMap.get(id));while(sourceNodeStack.length){var parentNode=parentNodeStack.pop();var sourceNode=sourceNodeStack.pop();if(!sourceNode.children)
sourceNode.children=[];var targetNode=new WebInspector.CPUProfileNode(sourceNode,sampleTime);if(keepNatives||!isNativeNode(sourceNode)){parentNode.children.push(targetNode);parentNode=targetNode;}else{parentNode.self+=targetNode.self;}
idMap.set(sourceNode.id,parentNode.id);parentNodeStack.push.apply(parentNodeStack,sourceNode.children.map(()=>parentNode));sourceNodeStack.push.apply(sourceNodeStack,sourceNode.children.map(id=>nodeByIdMap.get(id)));}
if(this.samples)
this.samples=this.samples.map(id=>idMap.get(id));return resultRoot;},_sortSamples:function()
{var timestamps=this.timestamps;if(!timestamps)
return;var samples=this.samples;var indices=timestamps.map((x,index)=>index);indices.sort((a,b)=>timestamps[a]-timestamps[b]);for(var i=0;i<timestamps.length;++i){var index=indices[i];if(index===i)
continue;var savedTimestamp=timestamps[i];var savedSample=samples[i];var currentIndex=i;while(index!==i){samples[currentIndex]=samples[index];timestamps[currentIndex]=timestamps[index];currentIndex=index;index=indices[index];indices[currentIndex]=currentIndex;}
samples[currentIndex]=savedSample;timestamps[currentIndex]=savedTimestamp;}},_normalizeTimestamps:function()
{var timestamps=this.timestamps;if(!timestamps){var profileStartTime=this.profileStartTime;var interval=(this.profileEndTime-profileStartTime)/this.samples.length;timestamps=new Float64Array(this.samples.length+1);for(var i=0;i<timestamps.length;++i)
timestamps[i]=profileStartTime+i*interval;this.timestamps=timestamps;return;}
for(var i=0;i<timestamps.length;++i)
timestamps[i]/=1000;var averageSample=(timestamps.peekLast()-timestamps[0])/(timestamps.length-1);this.timestamps.push(timestamps.peekLast()+averageSample);this.profileStartTime=timestamps[0];this.profileEndTime=timestamps.peekLast();},_buildIdToNodeMap:function()
{this._idToNode=new Map();var idToNode=this._idToNode;var stack=[this.profileHead];while(stack.length){var node=stack.pop();idToNode.set(node.id,node);stack.push.apply(stack,node.children);}},_extractMetaNodes:function()
{var topLevelNodes=this.profileHead.children;for(var i=0;i<topLevelNodes.length&&!(this.gcNode&&this.programNode&&this.idleNode);i++){var node=topLevelNodes[i];if(node.functionName==="(garbage collector)")
this.gcNode=node;else if(node.functionName==="(program)")
this.programNode=node;else if(node.functionName==="(idle)")
this.idleNode=node;}},forEachFrame:function(openFrameCallback,closeFrameCallback,startTime,stopTime)
{if(!this.profileHead||!this.samples)
return;startTime=startTime||0;stopTime=stopTime||Infinity;var samples=this.samples;var timestamps=this.timestamps;var idToNode=this._idToNode;var gcNode=this.gcNode;var samplesCount=samples.length;var startIndex=timestamps.lowerBound(startTime);var stackTop=0;var stackNodes=[];var prevId=this.profileHead.id;var sampleTime=timestamps[samplesCount];var gcParentNode=null;if(!this._stackStartTimes)
this._stackStartTimes=new Float64Array(this.maxDepth+2);var stackStartTimes=this._stackStartTimes;if(!this._stackChildrenDuration)
this._stackChildrenDuration=new Float64Array(this.maxDepth+2);var stackChildrenDuration=this._stackChildrenDuration;for(var sampleIndex=startIndex;sampleIndex<samplesCount;sampleIndex++){sampleTime=timestamps[sampleIndex];if(sampleTime>=stopTime)
break;var id=samples[sampleIndex];if(id===prevId)
continue;var node=idToNode.get(id);var prevNode=idToNode.get(prevId);if(node===gcNode){gcParentNode=prevNode;openFrameCallback(gcParentNode.depth+1,gcNode,sampleTime);stackStartTimes[++stackTop]=sampleTime;stackChildrenDuration[stackTop]=0;prevId=id;continue;}
if(prevNode===gcNode){var start=stackStartTimes[stackTop];var duration=sampleTime-start;stackChildrenDuration[stackTop-1]+=duration;closeFrameCallback(gcParentNode.depth+1,gcNode,start,duration,duration-stackChildrenDuration[stackTop]);--stackTop;prevNode=gcParentNode;prevId=prevNode.id;gcParentNode=null;}
while(node.depth>prevNode.depth){stackNodes.push(node);node=node.parent;}
while(prevNode!==node){var start=stackStartTimes[stackTop];var duration=sampleTime-start;stackChildrenDuration[stackTop-1]+=duration;closeFrameCallback(prevNode.depth,(prevNode),start,duration,duration-stackChildrenDuration[stackTop]);--stackTop;if(node.depth===prevNode.depth){stackNodes.push(node);node=node.parent;}
prevNode=prevNode.parent;}
while(stackNodes.length){node=stackNodes.pop();openFrameCallback(node.depth,node,sampleTime);stackStartTimes[++stackTop]=sampleTime;stackChildrenDuration[stackTop]=0;}
prevId=id;}
if(idToNode.get(prevId)===gcNode){var start=stackStartTimes[stackTop];var duration=sampleTime-start;stackChildrenDuration[stackTop-1]+=duration;closeFrameCallback(gcParentNode.depth+1,node,start,duration,duration-stackChildrenDuration[stackTop]);--stackTop;}
for(var node=idToNode.get(prevId);node.parent;node=node.parent){var start=stackStartTimes[stackTop];var duration=sampleTime-start;stackChildrenDuration[stackTop-1]+=duration;closeFrameCallback(node.depth,(node),start,duration,duration-stackChildrenDuration[stackTop]);--stackTop;}},nodeByIndex:function(index)
{return this._idToNode.get(this.samples[index])||null;},__proto__:WebInspector.ProfileTreeModel.prototype}},{}],219:[function(require,module,exports){WebInspector.NetworkManager=function(target)
{WebInspector.SDKModel.call(this,WebInspector.NetworkManager,target);this._dispatcher=new WebInspector.NetworkDispatcher(this);this._target=target;this._networkAgent=target.networkAgent();target.registerNetworkDispatcher(this._dispatcher);if(WebInspector.moduleSetting("cacheDisabled").get())
this._networkAgent.setCacheDisabled(true);if(WebInspector.moduleSetting("monitoringXHREnabled").get())
this._networkAgent.setMonitoringXHREnabled(true);if(Runtime.queryParam("remoteFrontend")||Runtime.queryParam("ws"))
this._networkAgent.enable(10000000,5000000);else
this._networkAgent.enable();this._bypassServiceWorkerSetting=WebInspector.settings.createSetting("bypassServiceWorker",false);if(this._bypassServiceWorkerSetting.get())
this._bypassServiceWorkerChanged();this._bypassServiceWorkerSetting.addChangeListener(this._bypassServiceWorkerChanged,this);WebInspector.moduleSetting("cacheDisabled").addChangeListener(this._cacheDisabledSettingChanged,this);}
WebInspector.NetworkManager.Events={RequestStarted:Symbol("RequestStarted"),RequestUpdated:Symbol("RequestUpdated"),RequestFinished:Symbol("RequestFinished"),RequestUpdateDropped:Symbol("RequestUpdateDropped"),ResponseReceived:Symbol("ResponseReceived")}
WebInspector.NetworkManager._MIMETypes={"text/html":{"document":true},"text/xml":{"document":true},"text/plain":{"document":true},"application/xhtml+xml":{"document":true},"image/svg+xml":{"document":true},"text/css":{"stylesheet":true},"text/xsl":{"stylesheet":true},"text/vtt":{"texttrack":true},}
WebInspector.NetworkManager.fromTarget=function(target)
{return(target.model(WebInspector.NetworkManager));}
WebInspector.NetworkManager.Conditions;WebInspector.NetworkManager.NoThrottlingConditions={title:WebInspector.UIString("No throttling"),download:-1,upload:-1,latency:0};WebInspector.NetworkManager.OfflineConditions={title:WebInspector.UIString("Offline"),download:0,upload:0,latency:0};WebInspector.NetworkManager._connectionType=function(conditions)
{if(!conditions.download&&!conditions.upload)
return NetworkAgent.ConnectionType.None;var types=WebInspector.NetworkManager._connectionTypes;if(!types){WebInspector.NetworkManager._connectionTypes=[];types=WebInspector.NetworkManager._connectionTypes;types.push(["2g",NetworkAgent.ConnectionType.Cellular2g]);types.push(["3g",NetworkAgent.ConnectionType.Cellular3g]);types.push(["4g",NetworkAgent.ConnectionType.Cellular4g]);types.push(["bluetooth",NetworkAgent.ConnectionType.Bluetooth]);types.push(["wifi",NetworkAgent.ConnectionType.Wifi]);types.push(["wimax",NetworkAgent.ConnectionType.Wimax]);}
for(var type of types){if(conditions.title.toLowerCase().indexOf(type[0])!==-1)
return type[1];}
return NetworkAgent.ConnectionType.Other;}
WebInspector.NetworkManager.prototype={inflightRequestForURL:function(url)
{return this._dispatcher._inflightRequestsByURL[url];},_cacheDisabledSettingChanged:function(event)
{var enabled=(event.data);this._networkAgent.setCacheDisabled(enabled);},dispose:function()
{WebInspector.moduleSetting("cacheDisabled").removeChangeListener(this._cacheDisabledSettingChanged,this);},bypassServiceWorkerSetting:function()
{return this._bypassServiceWorkerSetting;},_bypassServiceWorkerChanged:function()
{this._networkAgent.setBypassServiceWorker(this._bypassServiceWorkerSetting.get());},__proto__:WebInspector.SDKModel.prototype}
WebInspector.NetworkDispatcher=function(manager)
{this._manager=manager;this._inflightRequestsById={};this._inflightRequestsByURL={};}
WebInspector.NetworkDispatcher.prototype={_headersMapToHeadersArray:function(headersMap)
{var result=[];for(var name in headersMap){var values=headersMap[name].split("\n");for(var i=0;i<values.length;++i)
result.push({name:name,value:values[i]});}
return result;},_updateNetworkRequestWithRequest:function(networkRequest,request)
{networkRequest.requestMethod=request.method;networkRequest.setRequestHeaders(this._headersMapToHeadersArray(request.headers));networkRequest.requestFormData=request.postData;networkRequest.setInitialPriority(request.initialPriority);networkRequest.mixedContentType=request.mixedContentType||NetworkAgent.RequestMixedContentType.None;},_updateNetworkRequestWithResponse:function(networkRequest,response)
{if(response.url&&networkRequest.url!==response.url)
networkRequest.url=response.url;networkRequest.mimeType=response.mimeType;networkRequest.statusCode=response.status;networkRequest.statusText=response.statusText;networkRequest.responseHeaders=this._headersMapToHeadersArray(response.headers);if(response.encodedDataLength>=0)
networkRequest.setTransferSize(response.encodedDataLength);if(response.headersText)
networkRequest.responseHeadersText=response.headersText;if(response.requestHeaders){networkRequest.setRequestHeaders(this._headersMapToHeadersArray(response.requestHeaders));networkRequest.setRequestHeadersText(response.requestHeadersText||"");}
networkRequest.connectionReused=response.connectionReused;networkRequest.connectionId=String(response.connectionId);if(response.remoteIPAddress)
networkRequest.setRemoteAddress(response.remoteIPAddress,response.remotePort||-1);if(response.fromServiceWorker)
networkRequest.fetchedViaServiceWorker=true;if(response.fromDiskCache)
networkRequest.setFromDiskCache();networkRequest.timing=response.timing;networkRequest.protocol=response.protocol;networkRequest.setSecurityState(response.securityState);if(!this._mimeTypeIsConsistentWithType(networkRequest)){var consoleModel=this._manager._target.consoleModel;consoleModel.addMessage(new WebInspector.ConsoleMessage(consoleModel.target(),WebInspector.ConsoleMessage.MessageSource.Network,WebInspector.ConsoleMessage.MessageLevel.Log,WebInspector.UIString("Resource interpreted as %s but transferred with MIME type %s: \"%s\".",networkRequest.resourceType().title(),networkRequest.mimeType,networkRequest.url),WebInspector.ConsoleMessage.MessageType.Log,"",0,0,networkRequest.requestId));}
if(response.securityDetails)
networkRequest.setSecurityDetails(response.securityDetails);},_mimeTypeIsConsistentWithType:function(networkRequest)
{if(networkRequest.hasErrorStatusCode()||networkRequest.statusCode===304||networkRequest.statusCode===204)
return true;var resourceType=networkRequest.resourceType();if(resourceType!==WebInspector.resourceTypes.Stylesheet&&resourceType!==WebInspector.resourceTypes.Document&&resourceType!==WebInspector.resourceTypes.TextTrack){return true;}
if(!networkRequest.mimeType)
return true;if(networkRequest.mimeType in WebInspector.NetworkManager._MIMETypes)
return resourceType.name()in WebInspector.NetworkManager._MIMETypes[networkRequest.mimeType];return false;},resourceChangedPriority:function(requestId,newPriority,timestamp)
{var networkRequest=this._inflightRequestsById[requestId];if(networkRequest)
networkRequest.setPriority(newPriority);},requestWillBeSent:function(requestId,frameId,loaderId,documentURL,request,time,wallTime,initiator,redirectResponse,resourceType)
{var networkRequest=this._inflightRequestsById[requestId];if(networkRequest){if(!redirectResponse)
return;this.responseReceived(requestId,frameId,loaderId,time,PageAgent.ResourceType.Other,redirectResponse);networkRequest=this._appendRedirect(requestId,time,request.url);}else
networkRequest=this._createNetworkRequest(requestId,frameId,loaderId,request.url,documentURL,initiator);networkRequest.hasNetworkData=true;this._updateNetworkRequestWithRequest(networkRequest,request);networkRequest.setIssueTime(time,wallTime);networkRequest.setResourceType(WebInspector.resourceTypes[resourceType]);this._startNetworkRequest(networkRequest);},requestServedFromCache:function(requestId)
{var networkRequest=this._inflightRequestsById[requestId];if(!networkRequest)
return;networkRequest.setFromMemoryCache();},responseReceived:function(requestId,frameId,loaderId,time,resourceType,response)
{var networkRequest=this._inflightRequestsById[requestId];if(!networkRequest){var eventData={};eventData.url=response.url;eventData.frameId=frameId;eventData.loaderId=loaderId;eventData.resourceType=resourceType;eventData.mimeType=response.mimeType;this._manager.dispatchEventToListeners(WebInspector.NetworkManager.Events.RequestUpdateDropped,eventData);return;}
networkRequest.responseReceivedTime=time;networkRequest.setResourceType(WebInspector.resourceTypes[resourceType]);this._updateNetworkRequestWithResponse(networkRequest,response);this._updateNetworkRequest(networkRequest);this._manager.dispatchEventToListeners(WebInspector.NetworkManager.Events.ResponseReceived,networkRequest);},dataReceived:function(requestId,time,dataLength,encodedDataLength)
{var networkRequest=this._inflightRequestsById[requestId];if(!networkRequest)
return;networkRequest.resourceSize+=dataLength;if(encodedDataLength!==-1)
networkRequest.increaseTransferSize(encodedDataLength);networkRequest.endTime=time;this._updateNetworkRequest(networkRequest);},loadingFinished:function(requestId,finishTime,encodedDataLength)
{var networkRequest=this._inflightRequestsById[requestId];if(!networkRequest)
return;this._finishNetworkRequest(networkRequest,finishTime,encodedDataLength);},loadingFailed:function(requestId,time,resourceType,localizedDescription,canceled,blockedReason)
{var networkRequest=this._inflightRequestsById[requestId];if(!networkRequest)
return;networkRequest.failed=true;networkRequest.setResourceType(WebInspector.resourceTypes[resourceType]);networkRequest.canceled=canceled;if(blockedReason){networkRequest.setBlockedReason(blockedReason);if(blockedReason===NetworkAgent.BlockedReason.Inspector){var consoleModel=this._manager._target.consoleModel;consoleModel.addMessage(new WebInspector.ConsoleMessage(consoleModel.target(),WebInspector.ConsoleMessage.MessageSource.Network,WebInspector.ConsoleMessage.MessageLevel.Warning,WebInspector.UIString("Request was blocked by DevTools: \"%s\".",networkRequest.url),WebInspector.ConsoleMessage.MessageType.Log,"",0,0,networkRequest.requestId));}}
networkRequest.localizedFailDescription=localizedDescription;this._finishNetworkRequest(networkRequest,time,-1);},webSocketCreated:function(requestId,requestURL,initiator)
{var networkRequest=new WebInspector.NetworkRequest(this._manager._target,requestId,requestURL,"","","",initiator||null);networkRequest.setResourceType(WebInspector.resourceTypes.WebSocket);this._startNetworkRequest(networkRequest);},webSocketWillSendHandshakeRequest:function(requestId,time,wallTime,request)
{var networkRequest=this._inflightRequestsById[requestId];if(!networkRequest)
return;networkRequest.requestMethod="GET";networkRequest.setRequestHeaders(this._headersMapToHeadersArray(request.headers));networkRequest.setIssueTime(time,wallTime);this._updateNetworkRequest(networkRequest);},webSocketHandshakeResponseReceived:function(requestId,time,response)
{var networkRequest=this._inflightRequestsById[requestId];if(!networkRequest)
return;networkRequest.statusCode=response.status;networkRequest.statusText=response.statusText;networkRequest.responseHeaders=this._headersMapToHeadersArray(response.headers);networkRequest.responseHeadersText=response.headersText;if(response.requestHeaders)
networkRequest.setRequestHeaders(this._headersMapToHeadersArray(response.requestHeaders));if(response.requestHeadersText)
networkRequest.setRequestHeadersText(response.requestHeadersText);networkRequest.responseReceivedTime=time;networkRequest.protocol="websocket";this._updateNetworkRequest(networkRequest);},webSocketFrameReceived:function(requestId,time,response)
{var networkRequest=this._inflightRequestsById[requestId];if(!networkRequest)
return;networkRequest.addFrame(response,time);networkRequest.responseReceivedTime=time;this._updateNetworkRequest(networkRequest);},webSocketFrameSent:function(requestId,time,response)
{var networkRequest=this._inflightRequestsById[requestId];if(!networkRequest)
return;networkRequest.addFrame(response,time,true);networkRequest.responseReceivedTime=time;this._updateNetworkRequest(networkRequest);},webSocketFrameError:function(requestId,time,errorMessage)
{var networkRequest=this._inflightRequestsById[requestId];if(!networkRequest)
return;networkRequest.addFrameError(errorMessage,time);networkRequest.responseReceivedTime=time;this._updateNetworkRequest(networkRequest);},webSocketClosed:function(requestId,time)
{var networkRequest=this._inflightRequestsById[requestId];if(!networkRequest)
return;this._finishNetworkRequest(networkRequest,time,-1);},eventSourceMessageReceived:function(requestId,time,eventName,eventId,data)
{var networkRequest=this._inflightRequestsById[requestId];if(!networkRequest)
return;networkRequest.addEventSourceMessage(time,eventName,eventId,data);},_appendRedirect:function(requestId,time,redirectURL)
{var originalNetworkRequest=this._inflightRequestsById[requestId];var previousRedirects=originalNetworkRequest.redirects||[];originalNetworkRequest.requestId=requestId+":redirected."+previousRedirects.length;delete originalNetworkRequest.redirects;if(previousRedirects.length>0)
originalNetworkRequest.redirectSource=previousRedirects[previousRedirects.length-1];this._finishNetworkRequest(originalNetworkRequest,time,-1);var newNetworkRequest=this._createNetworkRequest(requestId,originalNetworkRequest.frameId,originalNetworkRequest.loaderId,redirectURL,originalNetworkRequest.documentURL,originalNetworkRequest.initiator());newNetworkRequest.redirects=previousRedirects.concat(originalNetworkRequest);return newNetworkRequest;},_startNetworkRequest:function(networkRequest)
{this._inflightRequestsById[networkRequest.requestId]=networkRequest;this._inflightRequestsByURL[networkRequest.url]=networkRequest;this._dispatchEventToListeners(WebInspector.NetworkManager.Events.RequestStarted,networkRequest);},_updateNetworkRequest:function(networkRequest)
{this._dispatchEventToListeners(WebInspector.NetworkManager.Events.RequestUpdated,networkRequest);},_finishNetworkRequest:function(networkRequest,finishTime,encodedDataLength)
{networkRequest.endTime=finishTime;networkRequest.finished=true;if(encodedDataLength>=0)
networkRequest.setTransferSize(encodedDataLength);this._dispatchEventToListeners(WebInspector.NetworkManager.Events.RequestFinished,networkRequest);delete this._inflightRequestsById[networkRequest.requestId];delete this._inflightRequestsByURL[networkRequest.url];},_dispatchEventToListeners:function(eventType,networkRequest)
{this._manager.dispatchEventToListeners(eventType,networkRequest);},_createNetworkRequest:function(requestId,frameId,loaderId,url,documentURL,initiator)
{return new WebInspector.NetworkRequest(this._manager._target,requestId,url,documentURL,frameId,loaderId,initiator);}}
WebInspector.MultitargetNetworkManager=function()
{WebInspector.Object.call(this);WebInspector.targetManager.observeTargets(this);this._blockedURLs=new Set();this._blockedSetting=WebInspector.moduleSetting("blockedURLs");this._blockedSetting.addChangeListener(this._updateBlockedURLs,this);this._blockedSetting.set([]);this._updateBlockedURLs();this._userAgentOverride="";this._agents=new Set();this._networkConditions=WebInspector.NetworkManager.NoThrottlingConditions;}
WebInspector.MultitargetNetworkManager.Events={ConditionsChanged:Symbol("ConditionsChanged"),UserAgentChanged:Symbol("UserAgentChanged")}
WebInspector.MultitargetNetworkManager.patchUserAgentWithChromeVersion=function(uaString)
{var chromeRegex=new RegExp("(?:^|\\W)Chrome/(\\S+)");var chromeMatch=navigator.userAgent.match(chromeRegex);if(chromeMatch&&chromeMatch.length>1)
return String.sprintf(uaString,chromeMatch[1]);return uaString;}
WebInspector.MultitargetNetworkManager.prototype={targetAdded:function(target)
{var networkAgent=target.networkAgent();if(this._extraHeaders)
networkAgent.setExtraHTTPHeaders(this._extraHeaders);if(this._currentUserAgent())
networkAgent.setUserAgentOverride(this._currentUserAgent());for(var url of this._blockedURLs)
networkAgent.addBlockedURL(url);this._agents.add(networkAgent);if(this.isThrottling())
this._updateNetworkConditions(networkAgent);},targetRemoved:function(target)
{this._agents.delete(target.networkAgent());},isThrottling:function()
{return this._networkConditions.download>=0||this._networkConditions.upload>=0||this._networkConditions.latency>0;},isOffline:function()
{return!this._networkConditions.download&&!this._networkConditions.upload;},setNetworkConditions:function(conditions)
{this._networkConditions=conditions;for(var agent of this._agents)
this._updateNetworkConditions(agent);this.dispatchEventToListeners(WebInspector.MultitargetNetworkManager.Events.ConditionsChanged);},networkConditions:function()
{return this._networkConditions;},_updateNetworkConditions:function(networkAgent)
{var conditions=this._networkConditions;if(!this.isThrottling()){networkAgent.emulateNetworkConditions(false,0,0,0);}else{networkAgent.emulateNetworkConditions(this.isOffline(),conditions.latency,conditions.download<0?0:conditions.download,conditions.upload<0?0:conditions.upload,WebInspector.NetworkManager._connectionType(conditions));}},setExtraHTTPHeaders:function(headers)
{this._extraHeaders=headers;for(var target of WebInspector.targetManager.targets())
target.networkAgent().setExtraHTTPHeaders(this._extraHeaders);},_currentUserAgent:function()
{return this._customUserAgent?this._customUserAgent:this._userAgentOverride;},_updateUserAgentOverride:function()
{var userAgent=this._currentUserAgent();WebInspector.ResourceLoader.targetUserAgent=userAgent;for(var target of WebInspector.targetManager.targets())
target.networkAgent().setUserAgentOverride(userAgent);},setUserAgentOverride:function(userAgent)
{if(this._userAgentOverride===userAgent)
return;this._userAgentOverride=userAgent;if(!this._customUserAgent)
this._updateUserAgentOverride();this.dispatchEventToListeners(WebInspector.MultitargetNetworkManager.Events.UserAgentChanged);},userAgentOverride:function()
{return this._userAgentOverride;},setCustomUserAgentOverride:function(userAgent)
{this._customUserAgent=userAgent;this._updateUserAgentOverride();},_updateBlockedURLs:function()
{var blocked=this._blockedSetting.get();for(var url of blocked){if(!this._blockedURLs.has(url))
this._addBlockedURL(url);}
for(var url of this._blockedURLs){if(blocked.indexOf(url)===-1)
this._removeBlockedURL(url);}},_addBlockedURL:function(url)
{this._blockedURLs.add(url);for(var target of WebInspector.targetManager.targets())
target.networkAgent().addBlockedURL(url);},_removeBlockedURL:function(url)
{this._blockedURLs.delete(url);for(var target of WebInspector.targetManager.targets())
target.networkAgent().removeBlockedURL(url);},clearBrowserCache:function()
{for(var target of WebInspector.targetManager.targets())
target.networkAgent().clearBrowserCache();},clearBrowserCookies:function()
{for(var target of WebInspector.targetManager.targets())
target.networkAgent().clearBrowserCookies();},getCertificate:function(origin,callback)
{var target=WebInspector.targetManager.mainTarget();target.networkAgent().getCertificate(origin,mycallback);function mycallback(error,certificate)
{callback(error?[]:certificate);}},loadResource:function(url,callback)
{var headers={};var currentUserAgent=this._currentUserAgent();if(currentUserAgent)
headers["User-Agent"]=currentUserAgent;if(WebInspector.moduleSetting("cacheDisabled").get())
headers["Cache-Control"]="no-cache";WebInspector.ResourceLoader.load(url,headers,callback);},__proto__:WebInspector.Object.prototype}
WebInspector.multitargetNetworkManager;},{}],220:[function(require,module,exports){WebInspector.NetworkRequest=function(target,requestId,url,documentURL,frameId,loaderId,initiator)
{WebInspector.SDKObject.call(this,target);this._networkLog=(WebInspector.NetworkLog.fromTarget(target));this._networkManager=(WebInspector.NetworkManager.fromTarget(target));this._requestId=requestId;this.url=url;this._documentURL=documentURL;this._frameId=frameId;this._loaderId=loaderId;this._initiator=initiator;this._issueTime=-1;this._startTime=-1;this._endTime=-1;this._blockedReason=undefined;this.statusCode=0;this.statusText="";this.requestMethod="";this.requestTime=0;this.protocol="";this.mixedContentType=NetworkAgent.RequestMixedContentType.None;this._initialPriority=null;this._currentPriority=null;this._resourceType=WebInspector.resourceTypes.Other;this._contentEncoded=false;this._pendingContentCallbacks=[];this._frames=[];this._eventSourceMessages=[];this._responseHeaderValues={};this._remoteAddress="";this._securityState=SecurityAgent.SecurityState.Unknown;this._securityDetails=null;this.connectionId="0";}
WebInspector.NetworkRequest.Events={FinishedLoading:Symbol("FinishedLoading"),TimingChanged:Symbol("TimingChanged"),RemoteAddressChanged:Symbol("RemoteAddressChanged"),RequestHeadersChanged:Symbol("RequestHeadersChanged"),ResponseHeadersChanged:Symbol("ResponseHeadersChanged"),WebsocketFrameAdded:Symbol("WebsocketFrameAdded"),EventSourceMessageAdded:Symbol("EventSourceMessageAdded")}
WebInspector.NetworkRequest.InitiatorType={Other:"other",Parser:"parser",Redirect:"redirect",Script:"script"}
WebInspector.NetworkRequest.NameValue;WebInspector.NetworkRequest.WebSocketFrameType={Send:"send",Receive:"receive",Error:"error"}
WebInspector.NetworkRequest.WebSocketFrame;WebInspector.NetworkRequest.EventSourceMessage;WebInspector.NetworkRequest.prototype={indentityCompare:function(other)
{if(this._requestId>other._requestId)
return 1;if(this._requestId<other._requestId)
return-1;return 0;},get requestId()
{return this._requestId;},set requestId(requestId)
{this._requestId=requestId;},get url()
{return this._url;},set url(x)
{if(this._url===x)
return;this._url=x;this._parsedURL=new WebInspector.ParsedURL(x);delete this._queryString;delete this._parsedQueryParameters;delete this._name;delete this._path;},get documentURL()
{return this._documentURL;},get parsedURL()
{return this._parsedURL;},get frameId()
{return this._frameId;},get loaderId()
{return this._loaderId;},setRemoteAddress:function(ip,port)
{this._remoteAddress=ip+":"+port;this.dispatchEventToListeners(WebInspector.NetworkRequest.Events.RemoteAddressChanged,this);},remoteAddress:function()
{return this._remoteAddress;},securityState:function()
{return this._securityState;},setSecurityState:function(securityState)
{this._securityState=securityState;},securityDetails:function()
{return this._securityDetails;},setSecurityDetails:function(securityDetails)
{this._securityDetails=securityDetails;},get startTime()
{return this._startTime||-1;},setIssueTime:function(monotonicTime,wallTime)
{this._issueTime=monotonicTime;this._wallIssueTime=wallTime;this._startTime=monotonicTime;},issueTime:function()
{return this._issueTime;},pseudoWallTime:function(monotonicTime)
{return this._wallIssueTime?this._wallIssueTime-this._issueTime+monotonicTime:monotonicTime;},get responseReceivedTime()
{return this._responseReceivedTime||-1;},set responseReceivedTime(x)
{this._responseReceivedTime=x;},get endTime()
{return this._endTime||-1;},set endTime(x)
{if(this.timing&&this.timing.requestTime){this._endTime=Math.max(x,this.responseReceivedTime);}else{this._endTime=x;if(this._responseReceivedTime>x)
this._responseReceivedTime=x;}
this.dispatchEventToListeners(WebInspector.NetworkRequest.Events.TimingChanged,this);},get duration()
{if(this._endTime===-1||this._startTime===-1)
return-1;return this._endTime-this._startTime;},get latency()
{if(this._responseReceivedTime===-1||this._startTime===-1)
return-1;return this._responseReceivedTime-this._startTime;},get resourceSize()
{return this._resourceSize||0;},set resourceSize(x)
{this._resourceSize=x;},get transferSize()
{return this._transferSize||0;},increaseTransferSize:function(x)
{this._transferSize=(this._transferSize||0)+x;},setTransferSize:function(x)
{this._transferSize=x;},get finished()
{return this._finished;},set finished(x)
{if(this._finished===x)
return;this._finished=x;if(x){this.dispatchEventToListeners(WebInspector.NetworkRequest.Events.FinishedLoading,this);if(this._pendingContentCallbacks.length)
this._innerRequestContent();}},get failed()
{return this._failed;},set failed(x)
{this._failed=x;},get canceled()
{return this._canceled;},set canceled(x)
{this._canceled=x;},blockedReason:function()
{return this._blockedReason;},setBlockedReason:function(reason)
{this._blockedReason=reason;},wasBlocked:function()
{return!!this._blockedReason;},cached:function()
{return(!!this._fromMemoryCache||!!this._fromDiskCache)&&!this._transferSize;},cachedInMemory:function()
{return!!this._fromMemoryCache&&!this._transferSize;},setFromMemoryCache:function()
{this._fromMemoryCache=true;delete this._timing;},setFromDiskCache:function()
{this._fromDiskCache=true;},get fetchedViaServiceWorker()
{return this._fetchedViaServiceWorker;},set fetchedViaServiceWorker(x)
{this._fetchedViaServiceWorker=x;},get timing()
{return this._timing;},set timing(x)
{if(x&&!this._fromMemoryCache){this._startTime=x.requestTime;this._responseReceivedTime=x.requestTime+x.receiveHeadersEnd/1000.0;this._timing=x;this.dispatchEventToListeners(WebInspector.NetworkRequest.Events.TimingChanged,this);}},get mimeType()
{return this._mimeType;},set mimeType(x)
{this._mimeType=x;},get displayName()
{return this._parsedURL.displayName;},name:function()
{if(this._name)
return this._name;this._parseNameAndPathFromURL();return this._name;},path:function()
{if(this._path)
return this._path;this._parseNameAndPathFromURL();return this._path;},_parseNameAndPathFromURL:function()
{if(this._parsedURL.isDataURL()){this._name=this._parsedURL.dataURLDisplayName();this._path="";}else if(this._parsedURL.isAboutBlank()){this._name=this._parsedURL.url;this._path="";}else{this._path=this._parsedURL.host+this._parsedURL.folderPathComponents;var inspectedURL=this.target().inspectedURL().asParsedURL();this._path=this._path.trimURL(inspectedURL?inspectedURL.host:"");if(this._parsedURL.lastPathComponent||this._parsedURL.queryParams)
this._name=this._parsedURL.lastPathComponent+(this._parsedURL.queryParams?"?"+this._parsedURL.queryParams:"");else if(this._parsedURL.folderPathComponents){this._name=this._parsedURL.folderPathComponents.substring(this._parsedURL.folderPathComponents.lastIndexOf("/")+1)+"/";this._path=this._path.substring(0,this._path.lastIndexOf("/"));}else{this._name=this._parsedURL.host;this._path="";}}},get folder()
{var path=this._parsedURL.path;var indexOfQuery=path.indexOf("?");if(indexOfQuery!==-1)
path=path.substring(0,indexOfQuery);var lastSlashIndex=path.lastIndexOf("/");return lastSlashIndex!==-1?path.substring(0,lastSlashIndex):"";},resourceType:function()
{return this._resourceType;},setResourceType:function(resourceType)
{this._resourceType=resourceType;},get domain()
{return this._parsedURL.host;},get scheme()
{return this._parsedURL.scheme;},get redirectSource()
{if(this.redirects&&this.redirects.length>0)
return this.redirects[this.redirects.length-1];return this._redirectSource;},set redirectSource(x)
{this._redirectSource=x;delete this._initiatorInfo;},requestHeaders:function()
{return this._requestHeaders||[];},setRequestHeaders:function(headers)
{this._requestHeaders=headers;delete this._requestCookies;this.dispatchEventToListeners(WebInspector.NetworkRequest.Events.RequestHeadersChanged);},requestHeadersText:function()
{return this._requestHeadersText;},setRequestHeadersText:function(text)
{this._requestHeadersText=text;this.dispatchEventToListeners(WebInspector.NetworkRequest.Events.RequestHeadersChanged);},requestHeaderValue:function(headerName)
{return this._headerValue(this.requestHeaders(),headerName);},get requestCookies()
{if(!this._requestCookies)
this._requestCookies=WebInspector.CookieParser.parseCookie(this.target(),this.requestHeaderValue("Cookie"));return this._requestCookies;},get requestFormData()
{return this._requestFormData;},set requestFormData(x)
{this._requestFormData=x;delete this._parsedFormParameters;},requestHttpVersion:function()
{var headersText=this.requestHeadersText();if(!headersText)
return this.requestHeaderValue("version")||this.requestHeaderValue(":version")||"unknown";var firstLine=headersText.split(/\r\n/)[0];var match=firstLine.match(/(HTTP\/\d+\.\d+)$/);return match?match[1]:"HTTP/0.9";},get responseHeaders()
{return this._responseHeaders||[];},set responseHeaders(x)
{this._responseHeaders=x;delete this._sortedResponseHeaders;delete this._serverTimings;delete this._responseCookies;this._responseHeaderValues={};this.dispatchEventToListeners(WebInspector.NetworkRequest.Events.ResponseHeadersChanged);},get responseHeadersText()
{return this._responseHeadersText;},set responseHeadersText(x)
{this._responseHeadersText=x;this.dispatchEventToListeners(WebInspector.NetworkRequest.Events.ResponseHeadersChanged);},get sortedResponseHeaders()
{if(this._sortedResponseHeaders!==undefined)
return this._sortedResponseHeaders;this._sortedResponseHeaders=this.responseHeaders.slice();this._sortedResponseHeaders.sort(function(a,b){return a.name.toLowerCase().compareTo(b.name.toLowerCase());});return this._sortedResponseHeaders;},responseHeaderValue:function(headerName)
{var value=this._responseHeaderValues[headerName];if(value===undefined){value=this._headerValue(this.responseHeaders,headerName);this._responseHeaderValues[headerName]=(value!==undefined)?value:null;}
return(value!==null)?value:undefined;},get responseCookies()
{if(!this._responseCookies)
this._responseCookies=WebInspector.CookieParser.parseSetCookie(this.target(),this.responseHeaderValue("Set-Cookie"));return this._responseCookies;},get serverTimings()
{if(typeof this._serverTimings==="undefined")
this._serverTimings=WebInspector.ServerTiming.parseHeaders(this.responseHeaders);return this._serverTimings;},queryString:function()
{if(this._queryString!==undefined)
return this._queryString;var queryString=null;var url=this.url;var questionMarkPosition=url.indexOf("?");if(questionMarkPosition!==-1){queryString=url.substring(questionMarkPosition+1);var hashSignPosition=queryString.indexOf("#");if(hashSignPosition!==-1)
queryString=queryString.substring(0,hashSignPosition);}
this._queryString=queryString;return this._queryString;},get queryParameters()
{if(this._parsedQueryParameters)
return this._parsedQueryParameters;var queryString=this.queryString();if(!queryString)
return null;this._parsedQueryParameters=this._parseParameters(queryString);return this._parsedQueryParameters;},get formParameters()
{if(this._parsedFormParameters)
return this._parsedFormParameters;if(!this.requestFormData)
return null;var requestContentType=this.requestContentType();if(!requestContentType||!requestContentType.match(/^application\/x-www-form-urlencoded\s*(;.*)?$/i))
return null;this._parsedFormParameters=this._parseParameters(this.requestFormData);return this._parsedFormParameters;},responseHttpVersion:function()
{var headersText=this._responseHeadersText;if(!headersText)
return this.responseHeaderValue("version")||this.responseHeaderValue(":version")||"unknown";var firstLine=headersText.split(/\r\n/)[0];var match=firstLine.match(/^(HTTP\/\d+\.\d+)/);return match?match[1]:"HTTP/0.9";},_parseParameters:function(queryString)
{function parseNameValue(pair)
{var position=pair.indexOf("=");if(position===-1)
return{name:pair,value:""};else
return{name:pair.substring(0,position),value:pair.substring(position+1)};}
return queryString.split("&").map(parseNameValue);},_headerValue:function(headers,headerName)
{headerName=headerName.toLowerCase();var values=[];for(var i=0;i<headers.length;++i){if(headers[i].name.toLowerCase()===headerName)
values.push(headers[i].value);}
if(!values.length)
return undefined;if(headerName==="set-cookie")
return values.join("\n");return values.join(", ");},get content()
{return this._content;},contentError:function()
{return this._contentError;},get contentEncoded()
{return this._contentEncoded;},contentURL:function()
{return this._url;},contentType:function()
{return this._resourceType;},requestContent:function()
{if(this._resourceType===WebInspector.resourceTypes.WebSocket)
return Promise.resolve((null));if(typeof this._content!=="undefined")
return Promise.resolve((this.content||null));var callback;var promise=new Promise(fulfill=>callback=fulfill);this._pendingContentCallbacks.push(callback);if(this.finished)
this._innerRequestContent();return promise;},searchInContent:function(query,caseSensitive,isRegex,callback)
{callback([]);},isHttpFamily:function()
{return!!this.url.match(/^https?:/i);},requestContentType:function()
{return this.requestHeaderValue("Content-Type");},hasErrorStatusCode:function()
{return this.statusCode>=400;},setInitialPriority:function(priority)
{this._initialPriority=priority;},initialPriority:function()
{return this._initialPriority;},setPriority:function(priority)
{this._currentPriority=priority;},priority:function()
{return this._currentPriority||this._initialPriority||null;},populateImageSource:function(image)
{function onResourceContent(content)
{var imageSrc=WebInspector.ContentProvider.contentAsDataURL(content,this._mimeType,true);if(imageSrc===null)
imageSrc=this._url;image.src=imageSrc;}
this.requestContent().then(onResourceContent.bind(this));},asDataURL:function()
{var content=this._content;var charset=null;if(!this._contentEncoded){content=content.toBase64();charset="utf-8";}
return WebInspector.ContentProvider.contentAsDataURL(content,this.mimeType,true,charset);},_innerRequestContent:function()
{if(this._contentRequested)
return;this._contentRequested=true;function onResourceContent(error,content,contentEncoded)
{this._content=error?null:content;this._contentError=error;this._contentEncoded=contentEncoded;var callbacks=this._pendingContentCallbacks.slice();for(var i=0;i<callbacks.length;++i)
callbacks[i](this._content);this._pendingContentCallbacks.length=0;delete this._contentRequested;}
this.target().networkAgent().getResponseBody(this._requestId,onResourceContent.bind(this));},initiator:function()
{return this._initiator;},initiatorInfo:function()
{if(this._initiatorInfo)
return this._initiatorInfo;var type=WebInspector.NetworkRequest.InitiatorType.Other;var url="";var lineNumber=-Infinity;var columnNumber=-Infinity;var scriptId=null;var initiator=this._initiator;if(this.redirectSource){type=WebInspector.NetworkRequest.InitiatorType.Redirect;url=this.redirectSource.url;}else if(initiator){if(initiator.type===NetworkAgent.InitiatorType.Parser){type=WebInspector.NetworkRequest.InitiatorType.Parser;url=initiator.url?initiator.url:url;lineNumber=initiator.lineNumber?initiator.lineNumber:lineNumber;}else if(initiator.type===NetworkAgent.InitiatorType.Script){for(var stack=initiator.stack;stack;stack=stack.parent){var topFrame=stack.callFrames.length?stack.callFrames[0]:null;if(!topFrame)
continue;type=WebInspector.NetworkRequest.InitiatorType.Script;url=topFrame.url||WebInspector.UIString("<anonymous>");lineNumber=topFrame.lineNumber;columnNumber=topFrame.columnNumber;scriptId=topFrame.scriptId;break;}}}
this._initiatorInfo={type:type,url:url,lineNumber:lineNumber,columnNumber:columnNumber,scriptId:scriptId};return this._initiatorInfo;},initiatorRequest:function()
{if(this._initiatorRequest===undefined)
this._initiatorRequest=this._networkLog.requestForURL(this.initiatorInfo().url);return this._initiatorRequest;},initiatorChain:function()
{if(this._initiatorChain)
return this._initiatorChain;this._initiatorChain=new Set();var request=this;while(request){this._initiatorChain.add(request);request=request.initiatorRequest();}
return this._initiatorChain;},frames:function()
{return this._frames;},addFrameError:function(errorMessage,time)
{this._addFrame({type:WebInspector.NetworkRequest.WebSocketFrameType.Error,text:errorMessage,time:this.pseudoWallTime(time),opCode:-1,mask:false});},addFrame:function(response,time,sent)
{var type=sent?WebInspector.NetworkRequest.WebSocketFrameType.Send:WebInspector.NetworkRequest.WebSocketFrameType.Receive;this._addFrame({type:type,text:response.payloadData,time:this.pseudoWallTime(time),opCode:response.opcode,mask:response.mask});},_addFrame:function(frame)
{this._frames.push(frame);this.dispatchEventToListeners(WebInspector.NetworkRequest.Events.WebsocketFrameAdded,frame);},eventSourceMessages:function()
{return this._eventSourceMessages;},addEventSourceMessage:function(time,eventName,eventId,data)
{var message={time:this.pseudoWallTime(time),eventName:eventName,eventId:eventId,data:data};this._eventSourceMessages.push(message);this.dispatchEventToListeners(WebInspector.NetworkRequest.Events.EventSourceMessageAdded,message);},replayXHR:function()
{this.target().networkAgent().replayXHR(this.requestId);},networkLog:function()
{return this._networkLog;},networkManager:function()
{return this._networkManager;},__proto__:WebInspector.SDKObject.prototype}},{}],221:[function(require,module,exports){WebInspector.ProfileNode=function(callFrame)
{this.callFrame=callFrame;this.callUID=`${this.callFrame.functionName}@${this.callFrame.scriptId}:${this.callFrame.lineNumber}`;this.self=0;this.total=0;this.id=0;this.parent=null;this.children=[];}
WebInspector.ProfileNode.prototype={get functionName()
{return this.callFrame.functionName;},get scriptId()
{return this.callFrame.scriptId;},get url()
{return this.callFrame.url;},get lineNumber()
{return this.callFrame.lineNumber;},get columnNumber()
{return this.callFrame.columnNumber;}}
WebInspector.ProfileTreeModel=function(root)
{this.root=root;this._assignDepthsAndParents();this.total=this._calculateTotals(this.root);}
WebInspector.ProfileTreeModel.prototype={_assignDepthsAndParents:function()
{var root=this.root;root.depth=-1;root.parent=null;this.maxDepth=0;var nodesToTraverse=[root];while(nodesToTraverse.length){var parent=nodesToTraverse.pop();var depth=parent.depth+1;if(depth>this.maxDepth)
this.maxDepth=depth;var children=parent.children;var length=children.length;for(var i=0;i<length;++i){var child=children[i];child.depth=depth;child.parent=parent;if(child.children.length)
nodesToTraverse.push(child);}}},_calculateTotals:function(root)
{var nodesToTraverse=[root];var dfsList=[];while(nodesToTraverse.length){var node=nodesToTraverse.pop();node.total=node.self;dfsList.push(node);nodesToTraverse.push(...node.children);}
while(dfsList.length>1){var node=dfsList.pop();node.parent.total+=node.total;}
return root.total;}}},{}],222:[function(require,module,exports){WebInspector.Target=function(targetManager,name,capabilitiesMask,connection,parentTarget)
{Protocol.Agents.call(this,connection.agentsMap());this._targetManager=targetManager;this._name=name;this._inspectedURL="";this._capabilitiesMask=capabilitiesMask;this._connection=connection;this._parentTarget=parentTarget;connection.addEventListener(InspectorBackendClass.Connection.Events.Disconnected,this._onDisconnect,this);this._id=WebInspector.Target._nextId++;this._modelByConstructor=new Map();}
WebInspector.Target.Capability={Browser:1,DOM:2,JS:4,Log:8,Network:16,Worker:32};WebInspector.Target._nextId=1;WebInspector.Target.prototype={id:function()
{return this._id;},name:function()
{return this._name;},targetManager:function()
{return this._targetManager;},hasAllCapabilities:function(capabilitiesMask)
{return(this._capabilitiesMask&capabilitiesMask)===capabilitiesMask;},connection:function()
{return this._connection;},decorateLabel:function(label)
{return!this.hasBrowserCapability()?"\u2699 "+label:label;},registerDispatcher:function(domain,dispatcher)
{this._connection.registerDispatcher(domain,dispatcher);},hasBrowserCapability:function()
{return this.hasAllCapabilities(WebInspector.Target.Capability.Browser);},hasJSCapability:function()
{return this.hasAllCapabilities(WebInspector.Target.Capability.JS);},hasLogCapability:function()
{return this.hasAllCapabilities(WebInspector.Target.Capability.Log);},hasNetworkCapability:function()
{return this.hasAllCapabilities(WebInspector.Target.Capability.Network);},hasWorkerCapability:function()
{return this.hasAllCapabilities(WebInspector.Target.Capability.Worker);},hasDOMCapability:function()
{return this.hasAllCapabilities(WebInspector.Target.Capability.DOM);},parentTarget:function()
{return this._parentTarget;},_onDisconnect:function()
{this._targetManager.removeTarget(this);this._dispose();},_dispose:function()
{this._targetManager.dispatchEventToListeners(WebInspector.TargetManager.Events.TargetDisposed,this);if(this.workerManager)
this.workerManager.dispose();},isDetached:function()
{return this._connection.isClosed();},model:function(modelClass)
{return this._modelByConstructor.get(modelClass)||null;},models:function()
{return this._modelByConstructor.valuesArray();},inspectedURL:function()
{return this._inspectedURL;},setInspectedURL:function(inspectedURL)
{this._inspectedURL=inspectedURL;InspectorFrontendHost.inspectedURLChanged(inspectedURL||"");this._targetManager.dispatchEventToListeners(WebInspector.TargetManager.Events.InspectedURLChanged,this);},__proto__:Protocol.Agents.prototype}
WebInspector.SDKObject=function(target)
{WebInspector.Object.call(this);this._target=target;}
WebInspector.SDKObject.prototype={target:function()
{return this._target;},__proto__:WebInspector.Object.prototype}
WebInspector.SDKModel=function(modelClass,target)
{WebInspector.SDKObject.call(this,target);target._modelByConstructor.set(modelClass,this);WebInspector.targetManager.addEventListener(WebInspector.TargetManager.Events.TargetDisposed,this._targetDisposed,this);}
WebInspector.SDKModel.prototype={suspendModel:function()
{return Promise.resolve();},resumeModel:function()
{return Promise.resolve();},dispose:function(){},_targetDisposed:function(event)
{var target=(event.data);if(target!==this._target)
return;this.dispose();WebInspector.targetManager.removeEventListener(WebInspector.TargetManager.Events.TargetDisposed,this._targetDisposed,this);},__proto__:WebInspector.SDKObject.prototype}},{}],223:[function(require,module,exports){WebInspector.TargetManager=function()
{WebInspector.Object.call(this);this._targets=[];this._observers=[];this._observerCapabiliesMaskSymbol=Symbol("observerCapabilitiesMask");this._modelListeners=new Map();this._isSuspended=false;}
WebInspector.TargetManager.Events={InspectedURLChanged:Symbol("InspectedURLChanged"),MainFrameNavigated:Symbol("MainFrameNavigated"),Load:Symbol("Load"),PageReloadRequested:Symbol("PageReloadRequested"),WillReloadPage:Symbol("WillReloadPage"),TargetDisposed:Symbol("TargetDisposed"),SuspendStateChanged:Symbol("SuspendStateChanged")}
WebInspector.TargetManager._listenersSymbol=Symbol("WebInspector.TargetManager.Listeners");WebInspector.TargetManager.prototype={suspendAllTargets:function()
{if(this._isSuspended)
return;this._isSuspended=true;this.dispatchEventToListeners(WebInspector.TargetManager.Events.SuspendStateChanged);for(var i=0;i<this._targets.length;++i){for(var model of this._targets[i].models())
model.suspendModel();}},resumeAllTargets:function()
{if(!this._isSuspended)
throw new Error("Not suspended");this._isSuspended=false;this.dispatchEventToListeners(WebInspector.TargetManager.Events.SuspendStateChanged);var promises=[];for(var i=0;i<this._targets.length;++i){for(var model of this._targets[i].models())
promises.push(model.resumeModel());}
return Promise.all(promises);},suspendAndResumeAllTargets:function()
{this.suspendAllTargets();this.resumeAllTargets();},allTargetsSuspended:function()
{return this._isSuspended;},inspectedURL:function()
{return this._targets[0]?this._targets[0].inspectedURL():"";},_redispatchEvent:function(eventName,event)
{this.dispatchEventToListeners(eventName,event.data);},reloadPage:function(bypassCache,injectedScript)
{if(!this._targets.length)
return;var resourceTreeModel=WebInspector.ResourceTreeModel.fromTarget(this._targets[0]);if(!resourceTreeModel)
return;resourceTreeModel.reloadPage(bypassCache,injectedScript);},addModelListener:function(modelClass,eventType,listener,thisObject)
{for(var i=0;i<this._targets.length;++i){var model=this._targets[i].model(modelClass);if(model)
model.addEventListener(eventType,listener,thisObject);}
if(!this._modelListeners.has(eventType))
this._modelListeners.set(eventType,[]);this._modelListeners.get(eventType).push({modelClass:modelClass,thisObject:thisObject,listener:listener});},removeModelListener:function(modelClass,eventType,listener,thisObject)
{if(!this._modelListeners.has(eventType))
return;for(var i=0;i<this._targets.length;++i){var model=this._targets[i].model(modelClass);if(model)
model.removeEventListener(eventType,listener,thisObject);}
var listeners=this._modelListeners.get(eventType);for(var i=0;i<listeners.length;++i){if(listeners[i].modelClass===modelClass&&listeners[i].listener===listener&&listeners[i].thisObject===thisObject)
listeners.splice(i--,1);}
if(!listeners.length)
this._modelListeners.delete(eventType);},observeTargets:function(targetObserver,capabilitiesMask)
{if(this._observerCapabiliesMaskSymbol in targetObserver)
throw new Error("Observer can only be registered once");targetObserver[this._observerCapabiliesMaskSymbol]=capabilitiesMask||0;this.targets(capabilitiesMask).forEach(targetObserver.targetAdded.bind(targetObserver));this._observers.push(targetObserver);},unobserveTargets:function(targetObserver)
{delete targetObserver[this._observerCapabiliesMaskSymbol];this._observers.remove(targetObserver);},createTarget:function(name,capabilitiesMask,connection,parentTarget)
{var target=new WebInspector.Target(this,name,capabilitiesMask,connection,parentTarget);var logAgent=target.hasLogCapability()?target.logAgent():null;target.consoleModel=new WebInspector.ConsoleModel(target,logAgent);target.runtimeModel=new WebInspector.RuntimeModel(target);var networkManager=null;var resourceTreeModel=null;if(target.hasNetworkCapability())
networkManager=new WebInspector.NetworkManager(target);if(networkManager&&target.hasDOMCapability()){resourceTreeModel=new WebInspector.ResourceTreeModel(target,networkManager,WebInspector.SecurityOriginManager.fromTarget(target));new WebInspector.NetworkLog(target,resourceTreeModel,networkManager);}
if(target.hasJSCapability())
new WebInspector.DebuggerModel(target);if(resourceTreeModel){var domModel=new WebInspector.DOMModel(target);new WebInspector.CSSModel(target,domModel);}
target.workerManager=target.hasWorkerCapability()?new WebInspector.WorkerManager(target):null;target.cpuProfilerModel=new WebInspector.CPUProfilerModel(target);target.heapProfilerModel=new WebInspector.HeapProfilerModel(target);target.tracingManager=new WebInspector.TracingManager(target);if(target.hasBrowserCapability()){target.subTargetsManager=new WebInspector.SubTargetsManager(target);target.serviceWorkerManager=new WebInspector.ServiceWorkerManager(target,target.subTargetsManager);}
this.addTarget(target);return target;},_observersForTarget:function(target)
{return this._observers.filter((observer)=>target.hasAllCapabilities(observer[this._observerCapabiliesMaskSymbol]||0));},addTarget:function(target)
{this._targets.push(target);var resourceTreeModel=WebInspector.ResourceTreeModel.fromTarget(target);if(this._targets.length===1&&resourceTreeModel){resourceTreeModel[WebInspector.TargetManager._listenersSymbol]=[setupRedispatch.call(this,WebInspector.ResourceTreeModel.Events.MainFrameNavigated,WebInspector.TargetManager.Events.MainFrameNavigated),setupRedispatch.call(this,WebInspector.ResourceTreeModel.Events.Load,WebInspector.TargetManager.Events.Load),setupRedispatch.call(this,WebInspector.ResourceTreeModel.Events.PageReloadRequested,WebInspector.TargetManager.Events.PageReloadRequested),setupRedispatch.call(this,WebInspector.ResourceTreeModel.Events.WillReloadPage,WebInspector.TargetManager.Events.WillReloadPage)];}
var copy=this._observersForTarget(target);for(var i=0;i<copy.length;++i)
copy[i].targetAdded(target);for(var pair of this._modelListeners){var listeners=pair[1];for(var i=0;i<listeners.length;++i){var model=target.model(listeners[i].modelClass);if(model)
model.addEventListener((pair[0]),listeners[i].listener,listeners[i].thisObject);}}
function setupRedispatch(sourceEvent,targetEvent)
{return resourceTreeModel.addEventListener(sourceEvent,this._redispatchEvent.bind(this,targetEvent));}},removeTarget:function(target)
{this._targets.remove(target);var resourceTreeModel=WebInspector.ResourceTreeModel.fromTarget(target);var treeModelListeners=resourceTreeModel&&resourceTreeModel[WebInspector.TargetManager._listenersSymbol];if(treeModelListeners)
WebInspector.EventTarget.removeEventListeners(treeModelListeners);var copy=this._observersForTarget(target);for(var i=0;i<copy.length;++i)
copy[i].targetRemoved(target);for(var pair of this._modelListeners){var listeners=pair[1];for(var i=0;i<listeners.length;++i){var model=target.model(listeners[i].modelClass);if(model)
model.removeEventListener((pair[0]),listeners[i].listener,listeners[i].thisObject);}}},targets:function(capabilitiesMask)
{if(!capabilitiesMask)
return this._targets.slice();else
return this._targets.filter((target)=>target.hasAllCapabilities(capabilitiesMask||0));},targetById:function(id)
{for(var i=0;i<this._targets.length;++i){if(this._targets[i].id()===id)
return this._targets[i];}
return null;},mainTarget:function()
{return this._targets[0]||null;},suspendReload:function(target)
{var resourceTreeModel=WebInspector.ResourceTreeModel.fromTarget(target);if(resourceTreeModel)
resourceTreeModel.suspendReload();},resumeReload:function(target)
{var resourceTreeModel=WebInspector.ResourceTreeModel.fromTarget(target);if(resourceTreeModel)
setImmediate(resourceTreeModel.resumeReload.bind(resourceTreeModel));},__proto__:WebInspector.Object.prototype}
WebInspector.TargetManager.Observer=function()
{}
WebInspector.TargetManager.Observer.prototype={targetAdded:function(target){},targetRemoved:function(target){},}
WebInspector.targetManager=new WebInspector.TargetManager();},{}],224:[function(require,module,exports){WebInspector.TracingModel=function(backingStorage)
{this._backingStorage=backingStorage;this._firstWritePending=true;this.reset();}
WebInspector.TracingModel.Phase={Begin:"B",End:"E",Complete:"X",Instant:"I",AsyncBegin:"S",AsyncStepInto:"T",AsyncStepPast:"p",AsyncEnd:"F",NestableAsyncBegin:"b",NestableAsyncEnd:"e",NestableAsyncInstant:"n",FlowBegin:"s",FlowStep:"t",FlowEnd:"f",Metadata:"M",Counter:"C",Sample:"P",CreateObject:"N",SnapshotObject:"O",DeleteObject:"D"};WebInspector.TracingModel.MetadataEvent={ProcessSortIndex:"process_sort_index",ProcessName:"process_name",ThreadSortIndex:"thread_sort_index",ThreadName:"thread_name"}
WebInspector.TracingModel.TopLevelEventCategory="toplevel";WebInspector.TracingModel.DevToolsMetadataEventCategory="disabled-by-default-devtools.timeline";WebInspector.TracingModel.DevToolsTimelineEventCategory="disabled-by-default-devtools.timeline";WebInspector.TracingModel.FrameLifecycleEventCategory="cc,devtools";WebInspector.TracingModel.isNestableAsyncPhase=function(phase)
{return phase==="b"||phase==="e"||phase==="n";}
WebInspector.TracingModel.isAsyncBeginPhase=function(phase)
{return phase==="S"||phase==="b";}
WebInspector.TracingModel.isAsyncPhase=function(phase)
{return WebInspector.TracingModel.isNestableAsyncPhase(phase)||phase==="S"||phase==="T"||phase==="F"||phase==="p";}
WebInspector.TracingModel.isFlowPhase=function(phase)
{return phase==="s"||phase==="t"||phase==="f";}
WebInspector.TracingModel.isTopLevelEvent=function(event)
{return event.hasCategory(WebInspector.TracingModel.TopLevelEventCategory)||event.hasCategory(WebInspector.TracingModel.DevToolsMetadataEventCategory)&&event.name==="Program";}
WebInspector.TracingModel._extractId=function(payload)
{var scope=payload.scope||"";if(typeof payload.id2==="undefined")
return scope&&payload.id?`${scope}@${payload.id}`:payload.id;var id2=payload.id2;if(typeof id2==="object"&&("global"in id2)!==("local"in id2))
return typeof id2["global"]!=="undefined"?`:${scope}:${id2["global"]}`:`:${scope}:${payload.pid}:${id2["local"]}`;console.error(`Unexpected id2 field at ${payload.ts / 1000}, one and only one of 'local' and 'global' should be present.`);}
WebInspector.TracingModel.browserMainThread=function(tracingModel)
{var processes=tracingModel.sortedProcesses();var browserProcesses=[];var crRendererMainThreads=[];for(var process of processes){if(process.name().toLowerCase().endsWith("browser"))
browserProcesses.push(process);crRendererMainThreads.push(...process.sortedThreads().filter(t=>t.name()==="CrBrowserMain"));}
if(crRendererMainThreads.length===1)
return crRendererMainThreads[0];if(browserProcesses.length===1)
return browserProcesses[0].threadByName("CrBrowserMain");var tracingStartedInBrowser=tracingModel.devToolsMetadataEvents().filter(e=>e.name==="TracingStartedInBrowser");if(tracingStartedInBrowser.length===1)
return tracingStartedInBrowser[0].thread;WebInspector.console.error("Failed to find browser main thread in trace, some timeline features may be unavailable");return null;}
WebInspector.BackingStorage=function()
{}
WebInspector.BackingStorage.prototype={appendString:function(string){},appendAccessibleString:function(string){},finishWriting:function(){},reset:function(){},}
WebInspector.TracingModel.prototype={devToolsMetadataEvents:function()
{return this._devToolsMetadataEvents;},setEventsForTest:function(events)
{this.reset();this.addEvents(events);this.tracingComplete();},addEvents:function(events)
{for(var i=0;i<events.length;++i)
this._addEvent(events[i]);},tracingComplete:function()
{this._processPendingAsyncEvents();this._backingStorage.appendString(this._firstWritePending?"[]":"]");this._backingStorage.finishWriting();this._firstWritePending=false;for(var process of this._processById.values()){for(var thread of process._threads.values())
thread.tracingComplete();}},reset:function()
{this._processById=new Map();this._processByName=new Map();this._minimumRecordTime=0;this._maximumRecordTime=0;this._devToolsMetadataEvents=[];if(!this._firstWritePending)
this._backingStorage.reset();this._firstWritePending=true;this._asyncEvents=[];this._openAsyncEvents=new Map();this._openNestableAsyncEvents=new Map();this._parsedCategories=new Map();},_addEvent:function(payload)
{var process=this._processById.get(payload.pid);if(!process){process=new WebInspector.TracingModel.Process(this,payload.pid);this._processById.set(payload.pid,process);}
var eventsDelimiter=",\n";this._backingStorage.appendString(this._firstWritePending?"[":eventsDelimiter);this._firstWritePending=false;var stringPayload=JSON.stringify(payload);var isAccessible=payload.ph===WebInspector.TracingModel.Phase.SnapshotObject;var backingStorage=null;var keepStringsLessThan=10000;if(isAccessible&&stringPayload.length>keepStringsLessThan)
backingStorage=this._backingStorage.appendAccessibleString(stringPayload);else
this._backingStorage.appendString(stringPayload);var timestamp=payload.ts/1000;if(timestamp&&(!this._minimumRecordTime||timestamp<this._minimumRecordTime))
this._minimumRecordTime=timestamp;var endTimeStamp=(payload.ts+(payload.dur||0))/1000;this._maximumRecordTime=Math.max(this._maximumRecordTime,endTimeStamp);var event=process._addEvent(payload);if(!event)
return;if(WebInspector.TracingModel.isAsyncPhase(payload.ph))
this._asyncEvents.push(event);event._setBackingStorage(backingStorage);if(event.hasCategory(WebInspector.TracingModel.DevToolsMetadataEventCategory))
this._devToolsMetadataEvents.push(event);if(payload.ph!==WebInspector.TracingModel.Phase.Metadata)
return;switch(payload.name){case WebInspector.TracingModel.MetadataEvent.ProcessSortIndex:process._setSortIndex(payload.args["sort_index"]);break;case WebInspector.TracingModel.MetadataEvent.ProcessName:var processName=payload.args["name"];process._setName(processName);this._processByName.set(processName,process);break;case WebInspector.TracingModel.MetadataEvent.ThreadSortIndex:process.threadById(payload.tid)._setSortIndex(payload.args["sort_index"]);break;case WebInspector.TracingModel.MetadataEvent.ThreadName:process.threadById(payload.tid)._setName(payload.args["name"]);break;}},minimumRecordTime:function()
{return this._minimumRecordTime;},maximumRecordTime:function()
{return this._maximumRecordTime;},sortedProcesses:function()
{return WebInspector.TracingModel.NamedObject._sort(this._processById.valuesArray());},processByName:function(name)
{return this._processByName.get(name);},threadByName:function(processName,threadName)
{var process=this.processByName(processName);return process&&process.threadByName(threadName);},_processPendingAsyncEvents:function()
{this._asyncEvents.stableSort(WebInspector.TracingModel.Event.compareStartTime);for(var i=0;i<this._asyncEvents.length;++i){var event=this._asyncEvents[i];if(WebInspector.TracingModel.isNestableAsyncPhase(event.phase))
this._addNestableAsyncEvent(event);else
this._addAsyncEvent(event);}
this._asyncEvents=[];this._closeOpenAsyncEvents();},_closeOpenAsyncEvents:function()
{for(var event of this._openAsyncEvents.values()){event.setEndTime(this._maximumRecordTime);event.steps[0].setEndTime(this._maximumRecordTime);}
this._openAsyncEvents.clear();for(var eventStack of this._openNestableAsyncEvents.values()){while(eventStack.length)
eventStack.pop().setEndTime(this._maximumRecordTime);}
this._openNestableAsyncEvents.clear();},_addNestableAsyncEvent:function(event)
{var phase=WebInspector.TracingModel.Phase;var key=event.categoriesString+"."+event.id;var openEventsStack=this._openNestableAsyncEvents.get(key);switch(event.phase){case phase.NestableAsyncBegin:if(!openEventsStack){openEventsStack=[];this._openNestableAsyncEvents.set(key,openEventsStack);}
var asyncEvent=new WebInspector.TracingModel.AsyncEvent(event);openEventsStack.push(asyncEvent);event.thread._addAsyncEvent(asyncEvent);break;case phase.NestableAsyncInstant:if(openEventsStack&&openEventsStack.length)
openEventsStack.peekLast()._addStep(event);break;case phase.NestableAsyncEnd:if(!openEventsStack||!openEventsStack.length)
break;var top=openEventsStack.pop();if(top.name!==event.name){console.error(`Begin/end event mismatch for nestable async event, ${top.name} vs. ${event.name}, key: ${key}`);break;}
top._addStep(event);}},_addAsyncEvent:function(event)
{var phase=WebInspector.TracingModel.Phase;var key=event.categoriesString+"."+event.name+"."+event.id;var asyncEvent=this._openAsyncEvents.get(key);if(event.phase===phase.AsyncBegin){if(asyncEvent){console.error(`Event ${event.name} has already been started`);return;}
asyncEvent=new WebInspector.TracingModel.AsyncEvent(event);this._openAsyncEvents.set(key,asyncEvent);event.thread._addAsyncEvent(asyncEvent);return;}
if(!asyncEvent){return;}
if(event.phase===phase.AsyncEnd){asyncEvent._addStep(event);this._openAsyncEvents.delete(key);return;}
if(event.phase===phase.AsyncStepInto||event.phase===phase.AsyncStepPast){var lastStep=asyncEvent.steps.peekLast();if(lastStep.phase!==phase.AsyncBegin&&lastStep.phase!==event.phase){console.assert(false,"Async event step phase mismatch: "+lastStep.phase+" at "+lastStep.startTime+" vs. "+event.phase+" at "+event.startTime);return;}
asyncEvent._addStep(event);return;}
console.assert(false,"Invalid async event phase");},_parsedCategoriesForString:function(str)
{var parsedCategories=this._parsedCategories.get(str);if(!parsedCategories){parsedCategories=new Set(str.split(","));this._parsedCategories.set(str,parsedCategories);}
return parsedCategories;}}
WebInspector.TracingModel.Event=function(categories,name,phase,startTime,thread)
{this.categoriesString=categories;this._parsedCategories=thread._model._parsedCategoriesForString(categories);this.name=name;this.phase=phase;this.startTime=startTime;this.thread=thread;this.args={};this.warning=null;this.initiator=null;this.stackTrace=null;this.previewElement=null;this.url=null;this.backendNodeId=0;this.selfTime=0;}
WebInspector.TracingModel.Event.fromPayload=function(payload,thread)
{var event=new WebInspector.TracingModel.Event(payload.cat,payload.name,(payload.ph),payload.ts/1000,thread);if(payload.args)
event.addArgs(payload.args);else
console.error("Missing mandatory event argument 'args' at "+payload.ts/1000);if(typeof payload.dur==="number")
event.setEndTime((payload.ts+payload.dur)/1000);var id=WebInspector.TracingModel._extractId(payload);if(typeof id!=="undefined")
event.id=id;if(payload.bind_id)
event.bind_id=payload.bind_id;return event;}
WebInspector.TracingModel.Event.prototype={hasCategory:function(categoryName)
{return this._parsedCategories.has(categoryName);},setEndTime:function(endTime)
{if(endTime<this.startTime){console.assert(false,"Event out of order: "+this.name);return;}
this.endTime=endTime;this.duration=endTime-this.startTime;},addArgs:function(args)
{for(var name in args){if(name in this.args)
console.error("Same argument name ("+name+") is used for begin and end phases of "+this.name);this.args[name]=args[name];}},_complete:function(endEvent)
{if(endEvent.args)
this.addArgs(endEvent.args);else
console.error("Missing mandatory event argument 'args' at "+endEvent.startTime);this.setEndTime(endEvent.startTime);},_setBackingStorage:function(backingStorage)
{}}
WebInspector.TracingModel.Event.compareStartTime=function(a,b)
{return a.startTime-b.startTime;}
WebInspector.TracingModel.Event.compareStartAndEndTime=function(a,b)
{return a.startTime-b.startTime||(b.endTime!==undefined&&a.endTime!==undefined&&b.endTime-a.endTime)||0;}
WebInspector.TracingModel.Event.orderedCompareStartTime=function(a,b)
{return a.startTime-b.startTime||a.ordinal-b.ordinal||-1;}
WebInspector.TracingModel.ObjectSnapshot=function(category,name,startTime,thread)
{WebInspector.TracingModel.Event.call(this,category,name,WebInspector.TracingModel.Phase.SnapshotObject,startTime,thread);}
WebInspector.TracingModel.ObjectSnapshot.fromPayload=function(payload,thread)
{var snapshot=new WebInspector.TracingModel.ObjectSnapshot(payload.cat,payload.name,payload.ts/1000,thread);var id=WebInspector.TracingModel._extractId(payload);if(typeof id!=="undefined")
snapshot.id=id;if(!payload.args||!payload.args["snapshot"]){console.error("Missing mandatory 'snapshot' argument at "+payload.ts/1000);return snapshot;}
if(payload.args)
snapshot.addArgs(payload.args);return snapshot;}
WebInspector.TracingModel.ObjectSnapshot.prototype={requestObject:function(callback)
{var snapshot=this.args["snapshot"];if(snapshot){callback(snapshot);return;}
this._backingStorage().then(onRead,callback.bind(null,null));function onRead(result)
{if(!result){callback(null);return;}
try{var payload=JSON.parse(result);callback(payload["args"]["snapshot"]);}catch(e){WebInspector.console.error("Malformed event data in backing storage");callback(null);}}},objectPromise:function()
{if(!this._objectPromise)
this._objectPromise=new Promise(this.requestObject.bind(this));return this._objectPromise;},_setBackingStorage:function(backingStorage)
{if(!backingStorage)
return;this._backingStorage=backingStorage;this.args={};},__proto__:WebInspector.TracingModel.Event.prototype}
WebInspector.TracingModel.AsyncEvent=function(startEvent)
{WebInspector.TracingModel.Event.call(this,startEvent.categoriesString,startEvent.name,startEvent.phase,startEvent.startTime,startEvent.thread)
this.addArgs(startEvent.args);this.steps=[startEvent];}
WebInspector.TracingModel.AsyncEvent.prototype={_addStep:function(event)
{this.steps.push(event);if(event.phase===WebInspector.TracingModel.Phase.AsyncEnd||event.phase===WebInspector.TracingModel.Phase.NestableAsyncEnd){this.setEndTime(event.startTime);this.steps[0].setEndTime(event.startTime);}},__proto__:WebInspector.TracingModel.Event.prototype}
WebInspector.TracingModel.NamedObject=function()
{}
WebInspector.TracingModel.NamedObject.prototype={_setName:function(name)
{this._name=name;},name:function()
{return this._name;},_setSortIndex:function(sortIndex)
{this._sortIndex=sortIndex;},}
WebInspector.TracingModel.NamedObject._sort=function(array)
{function comparator(a,b)
{return a._sortIndex!==b._sortIndex?a._sortIndex-b._sortIndex:a.name().localeCompare(b.name());}
return array.sort(comparator);}
WebInspector.TracingModel.Process=function(model,id)
{WebInspector.TracingModel.NamedObject.call(this);this._setName("Process "+id);this._id=id;this._threads=new Map();this._threadByName=new Map();this._model=model;}
WebInspector.TracingModel.Process.prototype={id:function()
{return this._id;},threadById:function(id)
{var thread=this._threads.get(id);if(!thread){thread=new WebInspector.TracingModel.Thread(this,id);this._threads.set(id,thread);}
return thread;},threadByName:function(name)
{return this._threadByName.get(name)||null;},_setThreadByName:function(name,thread)
{this._threadByName.set(name,thread);},_addEvent:function(payload)
{return this.threadById(payload.tid)._addEvent(payload);},sortedThreads:function()
{return WebInspector.TracingModel.NamedObject._sort(this._threads.valuesArray());},__proto__:WebInspector.TracingModel.NamedObject.prototype}
WebInspector.TracingModel.Thread=function(process,id)
{WebInspector.TracingModel.NamedObject.call(this);this._process=process;this._setName("Thread "+id);this._events=[];this._asyncEvents=[];this._id=id;this._model=process._model;}
WebInspector.TracingModel.Thread.prototype={tracingComplete:function()
{this._asyncEvents.stableSort(WebInspector.TracingModel.Event.compareStartAndEndTime);this._events.stableSort(WebInspector.TracingModel.Event.compareStartTime);var phases=WebInspector.TracingModel.Phase;var stack=[];for(var i=0;i<this._events.length;++i){var e=this._events[i];e.ordinal=i;switch(e.phase){case phases.End:this._events[i]=null;if(!stack.length)
continue;var top=stack.pop();if(top.name!==e.name||top.categoriesString!==e.categoriesString)
console.error("B/E events mismatch at "+top.startTime+" ("+top.name+") vs. "+e.startTime+" ("+e.name+")");else
top._complete(e);break;case phases.Begin:stack.push(e);break;}}
while(stack.length)
stack.pop().setEndTime(this._model.maximumRecordTime());this._events.remove(null,false);},_addEvent:function(payload)
{var event=payload.ph===WebInspector.TracingModel.Phase.SnapshotObject?WebInspector.TracingModel.ObjectSnapshot.fromPayload(payload,this):WebInspector.TracingModel.Event.fromPayload(payload,this);if(WebInspector.TracingModel.isTopLevelEvent(event)){if(this._lastTopLevelEvent&&this._lastTopLevelEvent.endTime>event.startTime)
return null;this._lastTopLevelEvent=event;}
this._events.push(event);return event;},_addAsyncEvent:function(asyncEvent)
{this._asyncEvents.push(asyncEvent);},_setName:function(name)
{WebInspector.TracingModel.NamedObject.prototype._setName.call(this,name);this._process._setThreadByName(name,this);},id:function()
{return this._id;},process:function()
{return this._process;},events:function()
{return this._events;},asyncEvents:function()
{return this._asyncEvents;},__proto__:WebInspector.TracingModel.NamedObject.prototype}},{}],225:[function(require,module,exports){WebInspector.TimelineTreeView=function(model,filters)
{WebInspector.VBox.call(this);this.element.classList.add("timeline-tree-view");this._model=model;this._linkifier=new WebInspector.Linkifier();this._filters=filters.slice();var columns=[];this._populateColumns(columns);var mainView=new WebInspector.VBox();this._populateToolbar(mainView.element);this._dataGrid=new WebInspector.SortableDataGrid(columns);this._dataGrid.addEventListener(WebInspector.DataGrid.Events.SortingChanged,this._sortingChanged,this);this._dataGrid.element.addEventListener("mousemove",this._onMouseMove.bind(this),true)
this._dataGrid.setResizeMethod(WebInspector.DataGrid.ResizeMethod.Last);this._dataGrid.asWidget().show(mainView.element);this._splitWidget=new WebInspector.SplitWidget(true,true,"timelineTreeViewDetailsSplitWidget");this._splitWidget.show(this.element);this._splitWidget.setMainWidget(mainView);this._detailsView=new WebInspector.VBox();this._detailsView.element.classList.add("timeline-details-view","timeline-details-view-body");this._splitWidget.setSidebarWidget(this._detailsView);this._dataGrid.addEventListener(WebInspector.DataGrid.Events.SelectedNode,this._updateDetailsForSelection,this);this._lastSelectedNode;}
WebInspector.TimelineTreeView.prototype={updateContents:function(selection)
{this.setRange(selection.startTime(),selection.endTime());},setRange:function(startTime,endTime)
{this._startTime=startTime;this._endTime=endTime;this._refreshTree();},_exposePercentages:function()
{return false;},_populateToolbar:function(parent){},_onHover:function(node){},_linkifyLocation:function(event)
{var target=this._model.targetByEvent(event);if(!target)
return null;var frame=WebInspector.TimelineProfileTree.eventStackFrame(event);if(!frame)
return null;return this._linkifier.maybeLinkifyConsoleCallFrame(target,frame);},selectProfileNode:function(treeNode,suppressSelectedEvent)
{var pathToRoot=[];for(var node=treeNode;node;node=node.parent)
pathToRoot.push(node);for(var i=pathToRoot.length-1;i>0;--i){var gridNode=this._dataGridNodeForTreeNode(pathToRoot[i]);if(gridNode&&gridNode.dataGrid)
gridNode.expand();}
var gridNode=this._dataGridNodeForTreeNode(treeNode);if(gridNode.dataGrid){gridNode.reveal();gridNode.select(suppressSelectedEvent);}},_refreshTree:function()
{this._linkifier.reset();this._dataGrid.rootNode().removeChildren();var tree=this._buildTree();if(!tree.children)
return;var maxSelfTime=0;var maxTotalTime=0;for(var child of tree.children.values()){maxSelfTime=Math.max(maxSelfTime,child.selfTime);maxTotalTime=Math.max(maxTotalTime,child.totalTime);}
for(var child of tree.children.values()){var gridNode=new WebInspector.TimelineTreeView.TreeGridNode(child,tree.totalTime,maxSelfTime,maxTotalTime,this);this._dataGrid.insertChild(gridNode);}
this._sortingChanged();this._updateDetailsForSelection();},_buildTree:function()
{throw new Error("Not Implemented");},_buildTopDownTree:function(eventIdCallback)
{return WebInspector.TimelineProfileTree.buildTopDown(this._model.mainThreadEvents(),this._filters,this._startTime,this._endTime,eventIdCallback)},_populateColumns:function(columns)
{columns.push({id:"self",title:WebInspector.UIString("Self Time"),width:"110px",fixedWidth:true,sortable:true});columns.push({id:"total",title:WebInspector.UIString("Total Time"),width:"110px",fixedWidth:true,sortable:true});columns.push({id:"activity",title:WebInspector.UIString("Activity"),disclosure:true,sortable:true});},_sortingChanged:function()
{var columnIdentifier=this._dataGrid.sortColumnIdentifier();if(!columnIdentifier)
return;var sortFunction;switch(columnIdentifier){case"startTime":sortFunction=compareStartTime;break;case"self":sortFunction=compareNumericField.bind(null,"selfTime");break;case"total":sortFunction=compareNumericField.bind(null,"totalTime");break;case"activity":sortFunction=compareName;break;default:console.assert(false,"Unknown sort field: "+columnIdentifier);return;}
this._dataGrid.sortNodes(sortFunction,!this._dataGrid.isSortOrderAscending());function compareNumericField(field,a,b)
{var nodeA=(a);var nodeB=(b);return nodeA._profileNode[field]-nodeB._profileNode[field];}
function compareStartTime(a,b)
{var nodeA=(a);var nodeB=(b);return nodeA._profileNode.event.startTime-nodeB._profileNode.event.startTime;}
function compareName(a,b)
{var nodeA=(a);var nodeB=(b);var nameA=WebInspector.TimelineTreeView.eventNameForSorting(nodeA._profileNode.event);var nameB=WebInspector.TimelineTreeView.eventNameForSorting(nodeB._profileNode.event);return nameA.localeCompare(nameB);}},_updateDetailsForSelection:function()
{var selectedNode=this._dataGrid.selectedNode?(this._dataGrid.selectedNode)._profileNode:null;if(selectedNode===this._lastSelectedNode)
return;this._lastSelectedNode=selectedNode;this._detailsView.detachChildWidgets();this._detailsView.element.removeChildren();if(!selectedNode||!this._showDetailsForNode(selectedNode)){var banner=this._detailsView.element.createChild("div","full-widget-dimmed-banner");banner.createTextChild(WebInspector.UIString("Select item for details."));}},_showDetailsForNode:function(node)
{return false;},_onMouseMove:function(event)
{var gridNode=event.target&&(event.target instanceof Node)?(this._dataGrid.dataGridNodeFromNode((event.target))):null;var profileNode=gridNode&&gridNode._profileNode;if(profileNode===this._lastHoveredProfileNode)
return;this._lastHoveredProfileNode=profileNode;this._onHover(profileNode);},_dataGridNodeForTreeNode:function(treeNode)
{return treeNode[WebInspector.TimelineTreeView.TreeGridNode._gridNodeSymbol]||null;},__proto__:WebInspector.VBox.prototype}
WebInspector.TimelineTreeView.eventNameForSorting=function(event)
{if(event.name===WebInspector.TimelineModel.RecordType.JSFrame){var data=event.args["data"];return data["functionName"]+"@"+(data["scriptId"]||data["url"]||"");}
return event.name+":@"+WebInspector.TimelineProfileTree.eventURL(event);}
WebInspector.TimelineTreeView.GridNode=function(profileNode,grandTotalTime,maxSelfTime,maxTotalTime,treeView)
{this._populated=false;this._profileNode=profileNode;this._treeView=treeView;this._grandTotalTime=grandTotalTime;this._maxSelfTime=maxSelfTime;this._maxTotalTime=maxTotalTime;WebInspector.SortableDataGridNode.call(this,null,false);}
WebInspector.TimelineTreeView.GridNode.prototype={createCell:function(columnIdentifier)
{if(columnIdentifier==="activity")
return this._createNameCell(columnIdentifier);return this._createValueCell(columnIdentifier)||WebInspector.DataGridNode.prototype.createCell.call(this,columnIdentifier);},_createNameCell:function(columnIdentifier)
{var cell=this.createTD(columnIdentifier);var container=cell.createChild("div","name-container");var icon=container.createChild("div","activity-icon");var name=container.createChild("div","activity-name");var event=this._profileNode.event;if(this._profileNode.isGroupNode()){var treeView=(this._treeView);var info=treeView._displayInfoForGroupNode(this._profileNode);name.textContent=info.name;icon.style.backgroundColor=info.color;}else if(event){var data=event.args["data"];var deoptReason=data&&data["deoptReason"];if(deoptReason)
container.createChild("div","activity-warning").title=WebInspector.UIString("Not optimized: %s",deoptReason);name.textContent=event.name===WebInspector.TimelineModel.RecordType.JSFrame?WebInspector.beautifyFunctionName(event.args["data"]["functionName"]):WebInspector.TimelineUIUtils.eventTitle(event);var link=this._treeView._linkifyLocation(event);if(link)
container.createChild("div","activity-link").appendChild(link);icon.style.backgroundColor=WebInspector.TimelineUIUtils.eventColor(event);}
return cell;},_createValueCell:function(columnIdentifier)
{if(columnIdentifier!=="self"&&columnIdentifier!=="total"&&columnIdentifier!=="startTime")
return null;var showPercents=false;var value;var maxTime;switch(columnIdentifier){case"startTime":value=this._profileNode.event.startTime-this._treeView._model.minimumRecordTime();break;case"self":value=this._profileNode.selfTime;maxTime=this._maxSelfTime;showPercents=true;break;case"total":value=this._profileNode.totalTime;maxTime=this._maxTotalTime;showPercents=true;break;default:return null;}
var cell=this.createTD(columnIdentifier);cell.className="numeric-column";var textDiv=cell.createChild("div");textDiv.createChild("span").textContent=WebInspector.UIString("%.1f\u2009ms",value);if(showPercents&&this._treeView._exposePercentages())
textDiv.createChild("span","percent-column").textContent=WebInspector.UIString("%.1f\u2009%%",value/this._grandTotalTime*100);if(maxTime){textDiv.classList.add("background-percent-bar");cell.createChild("div","background-bar-container").createChild("div","background-bar").style.width=(value*100/maxTime).toFixed(1)+"%";}
return cell;},__proto__:WebInspector.SortableDataGridNode.prototype}
WebInspector.TimelineTreeView.TreeGridNode=function(profileNode,grandTotalTime,maxSelfTime,maxTotalTime,treeView)
{WebInspector.TimelineTreeView.GridNode.call(this,profileNode,grandTotalTime,maxSelfTime,maxTotalTime,treeView);this.hasChildren=this._profileNode.children?this._profileNode.children.size>0:false;profileNode[WebInspector.TimelineTreeView.TreeGridNode._gridNodeSymbol]=this;}
WebInspector.TimelineTreeView.TreeGridNode._gridNodeSymbol=Symbol("treeGridNode");WebInspector.TimelineTreeView.TreeGridNode.prototype={populate:function()
{if(this._populated)
return;this._populated=true;if(!this._profileNode.children)
return;for(var node of this._profileNode.children.values()){var gridNode=new WebInspector.TimelineTreeView.TreeGridNode(node,this._grandTotalTime,this._maxSelfTime,this._maxTotalTime,this._treeView);this.insertChildOrdered(gridNode);}},__proto__:WebInspector.TimelineTreeView.GridNode.prototype};WebInspector.AggregatedTimelineTreeView=function(model,filters)
{this._groupBySetting=WebInspector.settings.createSetting("timelineTreeGroupBy",WebInspector.TimelineAggregator.GroupBy.Category);WebInspector.TimelineTreeView.call(this,model,filters);var nonessentialEvents=[WebInspector.TimelineModel.RecordType.EventDispatch,WebInspector.TimelineModel.RecordType.FunctionCall,WebInspector.TimelineModel.RecordType.TimerFire];this._filters.push(new WebInspector.ExclusiveNameFilter(nonessentialEvents));this._stackView=new WebInspector.TimelineStackView(this);this._stackView.addEventListener(WebInspector.TimelineStackView.Events.SelectionChanged,this._onStackViewSelectionChanged,this);}
WebInspector.AggregatedTimelineTreeView.prototype={updateContents:function(selection)
{this._updateExtensionResolver();WebInspector.TimelineTreeView.prototype.updateContents.call(this,selection);var rootNode=this._dataGrid.rootNode();if(rootNode.children.length)
rootNode.children[0].revealAndSelect();},_updateExtensionResolver:function()
{this._executionContextNamesByOrigin=new Map();for(var target of WebInspector.targetManager.targets()){for(var context of target.runtimeModel.executionContexts())
this._executionContextNamesByOrigin.set(context.origin,context.name);}},_displayInfoForGroupNode:function(node)
{var categories=WebInspector.TimelineUIUtils.categories();var color=node.id?WebInspector.TimelineUIUtils.eventColor(node.event):categories["other"].color;switch(this._groupBySetting.get()){case WebInspector.TimelineAggregator.GroupBy.Category:var category=categories[node.id]||categories["other"];return{name:category.title,color:category.color};case WebInspector.TimelineAggregator.GroupBy.Domain:case WebInspector.TimelineAggregator.GroupBy.Subdomain:var name=node.id;if(WebInspector.TimelineAggregator.isExtensionInternalURL(name))
name=WebInspector.UIString("[Chrome extensions overhead]");else if(name.startsWith("chrome-extension"))
name=this._executionContextNamesByOrigin.get(name)||name;return{name:name||WebInspector.UIString("unattributed"),color:color};case WebInspector.TimelineAggregator.GroupBy.EventName:var name=node.event.name===WebInspector.TimelineModel.RecordType.JSFrame?WebInspector.UIString("JavaScript"):WebInspector.TimelineUIUtils.eventTitle(node.event);return{name:name,color:node.event.name===WebInspector.TimelineModel.RecordType.JSFrame?WebInspector.TimelineUIUtils.eventStyle(node.event).category.color:color};case WebInspector.TimelineAggregator.GroupBy.URL:break;default:console.assert(false,"Unexpected aggregation type");}
return{name:node.id||WebInspector.UIString("unattributed"),color:color};},_populateToolbar:function(parent)
{var panelToolbar=new WebInspector.Toolbar("",parent);this._groupByCombobox=new WebInspector.ToolbarComboBox(this._onGroupByChanged.bind(this));function addGroupingOption(name,id)
{var option=this._groupByCombobox.createOption(name,"",id);this._groupByCombobox.addOption(option);if(id===this._groupBySetting.get())
this._groupByCombobox.select(option);}
addGroupingOption.call(this,WebInspector.UIString("No Grouping"),WebInspector.TimelineAggregator.GroupBy.None);addGroupingOption.call(this,WebInspector.UIString("Group by Activity"),WebInspector.TimelineAggregator.GroupBy.EventName);addGroupingOption.call(this,WebInspector.UIString("Group by Category"),WebInspector.TimelineAggregator.GroupBy.Category);addGroupingOption.call(this,WebInspector.UIString("Group by Domain"),WebInspector.TimelineAggregator.GroupBy.Domain);addGroupingOption.call(this,WebInspector.UIString("Group by Subdomain"),WebInspector.TimelineAggregator.GroupBy.Subdomain);addGroupingOption.call(this,WebInspector.UIString("Group by URL"),WebInspector.TimelineAggregator.GroupBy.URL);panelToolbar.appendToolbarItem(this._groupByCombobox);},_buildHeaviestStack:function(treeNode)
{console.assert(!!treeNode.parent,"Attempt to build stack for tree root");var result=[];for(var node=treeNode;node&&node.parent;node=node.parent)
result.push(node);result=result.reverse();for(node=treeNode;node&&node.children&&node.children.size;){var children=Array.from(node.children.values());node=children.reduce((a,b)=>a.totalTime>b.totalTime?a:b);result.push(node);}
return result;},_exposePercentages:function()
{return true;},_onGroupByChanged:function()
{this._groupBySetting.set(this._groupByCombobox.selectedOption().value);this._refreshTree();},_onStackViewSelectionChanged:function()
{var treeNode=this._stackView.selectedTreeNode();if(treeNode)
this.selectProfileNode(treeNode,true);},_showDetailsForNode:function(node)
{var stack=this._buildHeaviestStack(node);this._stackView.setStack(stack,node);this._stackView.show(this._detailsView.element);return true;},_createAggregator:function()
{return new WebInspector.TimelineAggregator(event=>WebInspector.TimelineUIUtils.eventStyle(event).title,event=>WebInspector.TimelineUIUtils.eventStyle(event).category.name);},__proto__:WebInspector.TimelineTreeView.prototype,};WebInspector.CallTreeTimelineTreeView=function(model,filters)
{WebInspector.AggregatedTimelineTreeView.call(this,model,filters);this._dataGrid.markColumnAsSortedBy("total",WebInspector.DataGrid.Order.Descending);}
WebInspector.CallTreeTimelineTreeView.prototype={_buildTree:function()
{var topDown=this._buildTopDownTree(WebInspector.TimelineAggregator.eventId);return this._createAggregator().performGrouping(topDown,this._groupBySetting.get());},__proto__:WebInspector.AggregatedTimelineTreeView.prototype,};WebInspector.BottomUpTimelineTreeView=function(model,filters)
{WebInspector.AggregatedTimelineTreeView.call(this,model,filters);this._dataGrid.markColumnAsSortedBy("self",WebInspector.DataGrid.Order.Descending);}
WebInspector.BottomUpTimelineTreeView.prototype={_buildTree:function()
{var topDown=this._buildTopDownTree(WebInspector.TimelineAggregator.eventId);return WebInspector.TimelineProfileTree.buildBottomUp(topDown,this._createAggregator().groupFunction(this._groupBySetting.get()));},__proto__:WebInspector.AggregatedTimelineTreeView.prototype};WebInspector.EventsTimelineTreeView=function(model,filters,delegate)
{this._filtersControl=new WebInspector.TimelineFilters();this._filtersControl.addEventListener(WebInspector.TimelineFilters.Events.FilterChanged,this._onFilterChanged,this);WebInspector.TimelineTreeView.call(this,model,filters);this._delegate=delegate;this._filters.push.apply(this._filters,this._filtersControl.filters());this._dataGrid.markColumnAsSortedBy("startTime",WebInspector.DataGrid.Order.Ascending);}
WebInspector.EventsTimelineTreeView.prototype={updateContents:function(selection)
{WebInspector.TimelineTreeView.prototype.updateContents.call(this,selection);if(selection.type()===WebInspector.TimelineSelection.Type.TraceEvent){var event=(selection.object());this._selectEvent(event,true);}},_buildTree:function()
{this._currentTree=this._buildTopDownTree();return this._currentTree;},_onFilterChanged:function()
{var selectedEvent=this._lastSelectedNode&&this._lastSelectedNode.event;this._refreshTree();if(selectedEvent)
this._selectEvent(selectedEvent,false);},_findNodeWithEvent:function(event)
{var iterators=[this._currentTree.children.values()];while(iterators.length){var iterator=iterators.peekLast().next();if(iterator.done){iterators.pop();continue;}
var child=(iterator.value);if(child.event===event)
return child;if(child.children)
iterators.push(child.children.values());}
return null;},_selectEvent:function(event,expand)
{var node=this._findNodeWithEvent(event);if(!node)
return;this.selectProfileNode(node,false);if(expand)
this._dataGridNodeForTreeNode(node).expand();},_populateColumns:function(columns)
{columns.push({id:"startTime",title:WebInspector.UIString("Start Time"),width:"110px",fixedWidth:true,sortable:true});WebInspector.TimelineTreeView.prototype._populateColumns.call(this,columns);},_populateToolbar:function(parent)
{var filtersWidget=this._filtersControl.filtersWidget();filtersWidget.forceShowFilterBar();filtersWidget.show(parent);},_showDetailsForNode:function(node)
{var traceEvent=node.event;if(!traceEvent)
return false;WebInspector.TimelineUIUtils.buildTraceEventDetails(traceEvent,this._model,this._linkifier,false,showDetails.bind(this));return true;function showDetails(fragment)
{this._detailsView.element.appendChild(fragment);}},_onHover:function(node)
{this._delegate.highlightEvent(node&&node.event);},__proto__:WebInspector.TimelineTreeView.prototype}
WebInspector.TimelineStackView=function(treeView)
{WebInspector.VBox.call(this);var header=this.element.createChild("div","timeline-stack-view-header");header.textContent=WebInspector.UIString("Heaviest stack");this._treeView=treeView;var columns=[{id:"total",title:WebInspector.UIString("Total Time"),fixedWidth:true,width:"110px"},{id:"activity",title:WebInspector.UIString("Activity")}];this._dataGrid=new WebInspector.ViewportDataGrid(columns);this._dataGrid.setResizeMethod(WebInspector.DataGrid.ResizeMethod.Last);this._dataGrid.addEventListener(WebInspector.DataGrid.Events.SelectedNode,this._onSelectionChanged,this);this._dataGrid.asWidget().show(this.element);}
WebInspector.TimelineStackView.Events={SelectionChanged:Symbol("SelectionChanged")}
WebInspector.TimelineStackView.prototype={setStack:function(stack,selectedNode)
{var rootNode=this._dataGrid.rootNode();rootNode.removeChildren();var nodeToReveal=null;var totalTime=Math.max.apply(Math,stack.map(node=>node.totalTime));for(var node of stack){var gridNode=new WebInspector.TimelineTreeView.GridNode(node,totalTime,totalTime,totalTime,this._treeView);rootNode.appendChild(gridNode);if(node===selectedNode)
nodeToReveal=gridNode;}
nodeToReveal.revealAndSelect();},selectedTreeNode:function()
{var selectedNode=this._dataGrid.selectedNode;return selectedNode&&(selectedNode)._profileNode;},_onSelectionChanged:function()
{this.dispatchEventToListeners(WebInspector.TimelineStackView.Events.SelectionChanged);},__proto__:WebInspector.VBox.prototype}},{}],226:[function(require,module,exports){WebInspector.TimelineUIUtils=function(){}
WebInspector.TimelineRecordStyle=function(title,category,hidden)
{this.title=title;this.category=category;this.hidden=!!hidden;}
WebInspector.TimelineUIUtils._initEventStyles=function()
{if(WebInspector.TimelineUIUtils._eventStylesMap)
return WebInspector.TimelineUIUtils._eventStylesMap;var recordTypes=WebInspector.TimelineModel.RecordType;var categories=WebInspector.TimelineUIUtils.categories();var eventStyles={};eventStyles[recordTypes.Task]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Task"),categories["other"]);eventStyles[recordTypes.Program]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Other"),categories["other"]);eventStyles[recordTypes.Animation]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Animation"),categories["rendering"]);eventStyles[recordTypes.EventDispatch]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Event"),categories["scripting"]);eventStyles[recordTypes.RequestMainThreadFrame]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Request Main Thread Frame"),categories["rendering"],true);eventStyles[recordTypes.BeginFrame]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Frame Start"),categories["rendering"],true);eventStyles[recordTypes.BeginMainThreadFrame]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Frame Start (main thread)"),categories["rendering"],true);eventStyles[recordTypes.DrawFrame]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Draw Frame"),categories["rendering"],true);eventStyles[recordTypes.HitTest]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Hit Test"),categories["rendering"]);eventStyles[recordTypes.ScheduleStyleRecalculation]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Schedule Style Recalculation"),categories["rendering"],true);eventStyles[recordTypes.RecalculateStyles]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Recalculate Style"),categories["rendering"]);eventStyles[recordTypes.UpdateLayoutTree]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Recalculate Style"),categories["rendering"]);eventStyles[recordTypes.InvalidateLayout]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Invalidate Layout"),categories["rendering"],true);eventStyles[recordTypes.Layout]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Layout"),categories["rendering"]);eventStyles[recordTypes.PaintSetup]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Paint Setup"),categories["painting"]);eventStyles[recordTypes.PaintImage]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Paint Image"),categories["painting"],true);eventStyles[recordTypes.UpdateLayer]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Update Layer"),categories["painting"],true);eventStyles[recordTypes.UpdateLayerTree]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Update Layer Tree"),categories["rendering"]);eventStyles[recordTypes.Paint]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Paint"),categories["painting"]);eventStyles[recordTypes.RasterTask]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Rasterize Paint"),categories["painting"]);eventStyles[recordTypes.ScrollLayer]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Scroll"),categories["rendering"]);eventStyles[recordTypes.CompositeLayers]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Composite Layers"),categories["painting"]);eventStyles[recordTypes.ParseHTML]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Parse HTML"),categories["loading"]);eventStyles[recordTypes.ParseAuthorStyleSheet]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Parse Stylesheet"),categories["loading"]);eventStyles[recordTypes.TimerInstall]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Install Timer"),categories["scripting"]);eventStyles[recordTypes.TimerRemove]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Remove Timer"),categories["scripting"]);eventStyles[recordTypes.TimerFire]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Timer Fired"),categories["scripting"]);eventStyles[recordTypes.XHRReadyStateChange]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("XHR Ready State Change"),categories["scripting"]);eventStyles[recordTypes.XHRLoad]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("XHR Load"),categories["scripting"]);eventStyles[recordTypes.CompileScript]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Compile Script"),categories["scripting"]);eventStyles[recordTypes.EvaluateScript]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Evaluate Script"),categories["scripting"]);eventStyles[recordTypes.ParseScriptOnBackground]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Parse Script"),categories["scripting"]);eventStyles[recordTypes.MarkLoad]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Load event"),categories["scripting"],true);eventStyles[recordTypes.MarkDOMContent]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("DOMContentLoaded event"),categories["scripting"],true);eventStyles[recordTypes.MarkFirstPaint]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("First paint"),categories["painting"],true);eventStyles[recordTypes.TimeStamp]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Timestamp"),categories["scripting"]);eventStyles[recordTypes.ConsoleTime]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Console Time"),categories["scripting"]);eventStyles[recordTypes.UserTiming]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("User Timing"),categories["scripting"]);eventStyles[recordTypes.ResourceSendRequest]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Send Request"),categories["loading"]);eventStyles[recordTypes.ResourceReceiveResponse]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Receive Response"),categories["loading"]);eventStyles[recordTypes.ResourceFinish]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Finish Loading"),categories["loading"]);eventStyles[recordTypes.ResourceReceivedData]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Receive Data"),categories["loading"]);eventStyles[recordTypes.RunMicrotasks]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Run Microtasks"),categories["scripting"]);eventStyles[recordTypes.FunctionCall]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Function Call"),categories["scripting"]);eventStyles[recordTypes.GCEvent]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("GC Event"),categories["scripting"]);eventStyles[recordTypes.MajorGC]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Major GC"),categories["scripting"]);eventStyles[recordTypes.MinorGC]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Minor GC"),categories["scripting"]);eventStyles[recordTypes.JSFrame]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("JS Frame"),categories["scripting"]);eventStyles[recordTypes.RequestAnimationFrame]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Request Animation Frame"),categories["scripting"]);eventStyles[recordTypes.CancelAnimationFrame]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Cancel Animation Frame"),categories["scripting"]);eventStyles[recordTypes.FireAnimationFrame]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Animation Frame Fired"),categories["scripting"]);eventStyles[recordTypes.RequestIdleCallback]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Request Idle Callback"),categories["scripting"]);eventStyles[recordTypes.CancelIdleCallback]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Cancel Idle Callback"),categories["scripting"]);eventStyles[recordTypes.FireIdleCallback]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Fire Idle Callback"),categories["scripting"]);eventStyles[recordTypes.WebSocketCreate]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Create WebSocket"),categories["scripting"]);eventStyles[recordTypes.WebSocketSendHandshakeRequest]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Send WebSocket Handshake"),categories["scripting"]);eventStyles[recordTypes.WebSocketReceiveHandshakeResponse]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Receive WebSocket Handshake"),categories["scripting"]);eventStyles[recordTypes.WebSocketDestroy]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Destroy WebSocket"),categories["scripting"]);eventStyles[recordTypes.EmbedderCallback]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Embedder Callback"),categories["scripting"]);eventStyles[recordTypes.DecodeImage]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Image Decode"),categories["painting"]);eventStyles[recordTypes.ResizeImage]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Image Resize"),categories["painting"]);eventStyles[recordTypes.GPUTask]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("GPU"),categories["gpu"]);eventStyles[recordTypes.LatencyInfo]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("Input Latency"),categories["scripting"]);eventStyles[recordTypes.GCIdleLazySweep]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("DOM GC"),categories["scripting"]);eventStyles[recordTypes.GCCompleteSweep]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("DOM GC"),categories["scripting"]);eventStyles[recordTypes.GCCollectGarbage]=new WebInspector.TimelineRecordStyle(WebInspector.UIString("DOM GC"),categories["scripting"]);WebInspector.TimelineUIUtils._eventStylesMap=eventStyles;return eventStyles;}
WebInspector.TimelineUIUtils.inputEventDisplayName=function(inputEventType)
{if(!WebInspector.TimelineUIUtils._inputEventToDisplayName){var inputEvent=WebInspector.TimelineIRModel.InputEvents;WebInspector.TimelineUIUtils._inputEventToDisplayName=new Map([[inputEvent.Char,WebInspector.UIString("Key Character")],[inputEvent.KeyDown,WebInspector.UIString("Key Down")],[inputEvent.KeyDownRaw,WebInspector.UIString("Key Down")],[inputEvent.KeyUp,WebInspector.UIString("Key Up")],[inputEvent.Click,WebInspector.UIString("Click")],[inputEvent.ContextMenu,WebInspector.UIString("Context Menu")],[inputEvent.MouseDown,WebInspector.UIString("Mouse Down")],[inputEvent.MouseMove,WebInspector.UIString("Mouse Move")],[inputEvent.MouseUp,WebInspector.UIString("Mouse Up")],[inputEvent.MouseWheel,WebInspector.UIString("Mouse Wheel")],[inputEvent.ScrollBegin,WebInspector.UIString("Scroll Begin")],[inputEvent.ScrollEnd,WebInspector.UIString("Scroll End")],[inputEvent.ScrollUpdate,WebInspector.UIString("Scroll Update")],[inputEvent.FlingStart,WebInspector.UIString("Fling Start")],[inputEvent.FlingCancel,WebInspector.UIString("Fling Halt")],[inputEvent.Tap,WebInspector.UIString("Tap")],[inputEvent.TapCancel,WebInspector.UIString("Tap Halt")],[inputEvent.ShowPress,WebInspector.UIString("Tap Begin")],[inputEvent.TapDown,WebInspector.UIString("Tap Down")],[inputEvent.TouchCancel,WebInspector.UIString("Touch Cancel")],[inputEvent.TouchEnd,WebInspector.UIString("Touch End")],[inputEvent.TouchMove,WebInspector.UIString("Touch Move")],[inputEvent.TouchStart,WebInspector.UIString("Touch Start")],[inputEvent.PinchBegin,WebInspector.UIString("Pinch Begin")],[inputEvent.PinchEnd,WebInspector.UIString("Pinch End")],[inputEvent.PinchUpdate,WebInspector.UIString("Pinch Update")]]);}
return WebInspector.TimelineUIUtils._inputEventToDisplayName.get(inputEventType)||null;}
WebInspector.TimelineUIUtils.testContentMatching=function(traceEvent,regExp)
{var title=WebInspector.TimelineUIUtils.eventStyle(traceEvent).title;var tokens=[title];if(traceEvent.url)
tokens.push(traceEvent.url);for(var argName in traceEvent.args){var argValue=traceEvent.args[argName];for(var key in argValue)
tokens.push(argValue[key]);}
return regExp.test(tokens.join("|"));}
WebInspector.TimelineUIUtils.categoryForRecord=function(record)
{return WebInspector.TimelineUIUtils.eventStyle(record.traceEvent()).category;}
WebInspector.TimelineUIUtils.eventStyle=function(event)
{var eventStyles=WebInspector.TimelineUIUtils._initEventStyles();if(event.hasCategory(WebInspector.TimelineModel.Category.Console)||event.hasCategory(WebInspector.TimelineModel.Category.UserTiming))
return{title:event.name,category:WebInspector.TimelineUIUtils.categories()["scripting"]};if(event.hasCategory(WebInspector.TimelineModel.Category.LatencyInfo)){var prefix="InputLatency::";var inputEventType=event.name.startsWith(prefix)?event.name.substr(prefix.length):event.name;var displayName=WebInspector.TimelineUIUtils.inputEventDisplayName((inputEventType));return{title:displayName||inputEventType,category:WebInspector.TimelineUIUtils.categories()["scripting"]};}
var result=eventStyles[event.name];if(!result){result=new WebInspector.TimelineRecordStyle(event.name,WebInspector.TimelineUIUtils.categories()["other"],true);eventStyles[event.name]=result;}
return result;}
WebInspector.TimelineUIUtils.eventColor=function(event)
{if(event.name===WebInspector.TimelineModel.RecordType.JSFrame){var frame=event.args["data"];if(WebInspector.TimelineUIUtils.isUserFrame(frame))
return WebInspector.TimelineUIUtils.colorForURL(frame.url);}
return WebInspector.TimelineUIUtils.eventStyle(event).category.color;}
WebInspector.TimelineUIUtils.eventTitle=function(event)
{var title=WebInspector.TimelineUIUtils.eventStyle(event).title;if(event.hasCategory(WebInspector.TimelineModel.Category.Console))
return title;if(event.name===WebInspector.TimelineModel.RecordType.TimeStamp)
return WebInspector.UIString("%s: %s",title,event.args["data"]["message"]);if(event.name===WebInspector.TimelineModel.RecordType.Animation&&event.args["data"]&&event.args["data"]["name"])
return WebInspector.UIString("%s: %s",title,event.args["data"]["name"]);return title;}
WebInspector.TimelineUIUtils.eventURL=function(event)
{if(event.url)
return event.url;var data=event.args["data"]||event.args["beginData"];return data&&data.url||null;}
WebInspector.TimelineUIUtils._interactionPhaseStyles=function()
{var map=WebInspector.TimelineUIUtils._interactionPhaseStylesMap;if(!map){map=new Map([[WebInspector.TimelineIRModel.Phases.Idle,{color:"white",label:"Idle"}],[WebInspector.TimelineIRModel.Phases.Response,{color:"hsl(43, 83%, 64%)",label:WebInspector.UIString("Response")}],[WebInspector.TimelineIRModel.Phases.Scroll,{color:"hsl(256, 67%, 70%)",label:WebInspector.UIString("Scroll")}],[WebInspector.TimelineIRModel.Phases.Fling,{color:"hsl(256, 67%, 70%)",label:WebInspector.UIString("Fling")}],[WebInspector.TimelineIRModel.Phases.Drag,{color:"hsl(256, 67%, 70%)",label:WebInspector.UIString("Drag")}],[WebInspector.TimelineIRModel.Phases.Animation,{color:"hsl(256, 67%, 70%)",label:WebInspector.UIString("Animation")}],[WebInspector.TimelineIRModel.Phases.Uncategorized,{color:"hsl(0, 0%, 87%)",label:WebInspector.UIString("Uncategorized")}]]);WebInspector.TimelineUIUtils._interactionPhaseStylesMap=map;}
return map;}
WebInspector.TimelineUIUtils.interactionPhaseColor=function(phase)
{return WebInspector.TimelineUIUtils._interactionPhaseStyles().get(phase).color;}
WebInspector.TimelineUIUtils.interactionPhaseLabel=function(phase)
{return WebInspector.TimelineUIUtils._interactionPhaseStyles().get(phase).label;}
WebInspector.TimelineUIUtils.isUserFrame=function(frame)
{return frame.scriptId!=="0"&&!(frame.url&&frame.url.startsWith("native "));}
WebInspector.TimelineUIUtils.topStackFrame=function(event)
{var stackTrace=event.stackTrace||event.initiator&&event.initiator.stackTrace;return stackTrace&&stackTrace.length?stackTrace[0]:null;}
WebInspector.TimelineUIUtils.NetworkCategory={HTML:Symbol("HTML"),Script:Symbol("Script"),Style:Symbol("Style"),Media:Symbol("Media"),Other:Symbol("Other")}
WebInspector.TimelineUIUtils.networkRequestCategory=function(request)
{var categories=WebInspector.TimelineUIUtils.NetworkCategory;switch(request.mimeType){case"text/html":return categories.HTML;case"application/javascript":case"application/x-javascript":case"text/javascript":return categories.Script;case"text/css":return categories.Style;case"audio/ogg":case"image/gif":case"image/jpeg":case"image/png":case"image/svg+xml":case"image/webp":case"image/x-icon":case"font/opentype":case"font/woff2":case"application/font-woff":return categories.Media;default:return categories.Other;}}
WebInspector.TimelineUIUtils.networkCategoryColor=function(category)
{var categories=WebInspector.TimelineUIUtils.NetworkCategory;switch(category){case categories.HTML:return"hsl(214, 67%, 66%)";case categories.Script:return"hsl(43, 83%, 64%)";case categories.Style:return"hsl(256, 67%, 70%)";case categories.Media:return"hsl(109, 33%, 55%)";default:return"hsl(0, 0%, 70%)";}}
WebInspector.TimelineUIUtils.buildDetailsTextForTraceEvent=function(event,target)
{var recordType=WebInspector.TimelineModel.RecordType;var detailsText;var eventData=event.args["data"];switch(event.name){case recordType.GCEvent:case recordType.MajorGC:case recordType.MinorGC:var delta=event.args["usedHeapSizeBefore"]-event.args["usedHeapSizeAfter"];detailsText=WebInspector.UIString("%s collected",Number.bytesToString(delta));break;case recordType.FunctionCall:if(eventData)
detailsText=linkifyLocationAsText(eventData["scriptId"],eventData["lineNumber"],0);break;case recordType.JSFrame:detailsText=WebInspector.beautifyFunctionName(eventData["functionName"]);break;case recordType.EventDispatch:detailsText=eventData?eventData["type"]:null;break;case recordType.Paint:var width=WebInspector.TimelineUIUtils.quadWidth(eventData.clip);var height=WebInspector.TimelineUIUtils.quadHeight(eventData.clip);if(width&&height)
detailsText=WebInspector.UIString("%d\u2009\u00d7\u2009%d",width,height);break;case recordType.ParseHTML:var endLine=event.args["endData"]&&event.args["endData"]["endLine"];var url=WebInspector.displayNameForURL(event.args["beginData"]["url"]);detailsText=WebInspector.UIString("%s [%s\u2026%s]",url,event.args["beginData"]["startLine"]+1,endLine>=0?endLine+1:"");break;case recordType.CompileScript:case recordType.EvaluateScript:var url=eventData["url"];if(url)
detailsText=WebInspector.displayNameForURL(url)+":"+(eventData["lineNumber"]+1);break;case recordType.ParseScriptOnBackground:case recordType.XHRReadyStateChange:case recordType.XHRLoad:var url=eventData["url"];if(url)
detailsText=WebInspector.displayNameForURL(url);break;case recordType.TimeStamp:detailsText=eventData["message"];break;case recordType.WebSocketCreate:case recordType.WebSocketSendHandshakeRequest:case recordType.WebSocketReceiveHandshakeResponse:case recordType.WebSocketDestroy:case recordType.ResourceSendRequest:case recordType.ResourceReceivedData:case recordType.ResourceReceiveResponse:case recordType.ResourceFinish:case recordType.PaintImage:case recordType.DecodeImage:case recordType.ResizeImage:case recordType.DecodeLazyPixelRef:if(event.url)
detailsText=WebInspector.displayNameForURL(event.url);break;case recordType.EmbedderCallback:detailsText=eventData["callbackName"];break;case recordType.Animation:detailsText=eventData&&eventData["name"];break;case recordType.GCIdleLazySweep:detailsText=WebInspector.UIString("idle sweep");break;case recordType.GCCompleteSweep:detailsText=WebInspector.UIString("complete sweep");break;case recordType.GCCollectGarbage:detailsText=WebInspector.UIString("collect");break;default:if(event.hasCategory(WebInspector.TimelineModel.Category.Console))
detailsText=null;else
detailsText=linkifyTopCallFrameAsText();break;}
return detailsText;function linkifyLocationAsText(scriptId,lineNumber,columnNumber)
{var debuggerModel=WebInspector.DebuggerModel.fromTarget(target);if(!target||target.isDetached()||!scriptId||!debuggerModel)
return null;var rawLocation=debuggerModel.createRawLocationByScriptId(scriptId,lineNumber,columnNumber);if(!rawLocation)
return null;var uiLocation=WebInspector.debuggerWorkspaceBinding.rawLocationToUILocation(rawLocation);return uiLocation.linkText();}
function linkifyTopCallFrameAsText()
{var frame=WebInspector.TimelineUIUtils.topStackFrame(event);if(!frame)
return null;var text=linkifyLocationAsText(frame.scriptId,frame.lineNumber,frame.columnNumber);if(!text){text=frame.url;if(typeof frame.lineNumber==="number")
text+=":"+(frame.lineNumber+1);}
return text;}}
WebInspector.TimelineUIUtils.buildDetailsNodeForTraceEvent=function(event,target,linkifier)
{var recordType=WebInspector.TimelineModel.RecordType;var details=null;var detailsText;var eventData=event.args["data"];switch(event.name){case recordType.GCEvent:case recordType.MajorGC:case recordType.MinorGC:case recordType.EventDispatch:case recordType.Paint:case recordType.Animation:case recordType.EmbedderCallback:case recordType.ParseHTML:case recordType.WebSocketCreate:case recordType.WebSocketSendHandshakeRequest:case recordType.WebSocketReceiveHandshakeResponse:case recordType.WebSocketDestroy:case recordType.GCIdleLazySweep:case recordType.GCCompleteSweep:case recordType.GCCollectGarbage:detailsText=WebInspector.TimelineUIUtils.buildDetailsTextForTraceEvent(event,target);break;case recordType.PaintImage:case recordType.DecodeImage:case recordType.ResizeImage:case recordType.DecodeLazyPixelRef:case recordType.XHRReadyStateChange:case recordType.XHRLoad:case recordType.ResourceSendRequest:case recordType.ResourceReceivedData:case recordType.ResourceReceiveResponse:case recordType.ResourceFinish:if(event.url)
details=WebInspector.linkifyResourceAsNode(event.url);break;case recordType.FunctionCall:case recordType.JSFrame:details=createElement("span");details.createTextChild(WebInspector.beautifyFunctionName(eventData["functionName"]));var location=linkifyLocation(eventData["scriptId"],eventData["url"],eventData["lineNumber"],eventData["columnNumber"]);if(location){details.createTextChild(" @ ");details.appendChild(location);}
break;case recordType.CompileScript:case recordType.EvaluateScript:var url=eventData["url"];if(url)
details=linkifyLocation("",url,eventData["lineNumber"],0);break;case recordType.ParseScriptOnBackground:var url=eventData["url"];if(url)
details=linkifyLocation("",url,0,0);break;default:if(event.hasCategory(WebInspector.TimelineModel.Category.Console))
detailsText=null;else
details=linkifyTopCallFrame();break;}
if(!details&&detailsText)
details=createTextNode(detailsText);return details;function linkifyLocation(scriptId,url,lineNumber,columnNumber)
{return linkifier.linkifyScriptLocation(target,scriptId,url,lineNumber,columnNumber,"timeline-details");}
function linkifyTopCallFrame()
{var frame=WebInspector.TimelineUIUtils.topStackFrame(event);return frame?linkifier.maybeLinkifyConsoleCallFrame(target,frame,"timeline-details"):null;}}
WebInspector.TimelineUIUtils.buildTraceEventDetails=function(event,model,linkifier,detailed,callback)
{var target=model.targetByEvent(event);if(!target){callbackWrapper();return;}
var relatedNodes=null;var barrier=new CallbackBarrier();if(!event.previewElement){if(event.url)
WebInspector.DOMPresentationUtils.buildImagePreviewContents(target,event.url,false,barrier.createCallback(saveImage));else if(event.picture)
WebInspector.TimelineUIUtils.buildPicturePreviewContent(event,target,barrier.createCallback(saveImage));}
var nodeIdsToResolve=new Set();if(event.backendNodeId)
nodeIdsToResolve.add(event.backendNodeId);if(event.invalidationTrackingEvents)
WebInspector.TimelineUIUtils._collectInvalidationNodeIds(nodeIdsToResolve,event.invalidationTrackingEvents);if(nodeIdsToResolve.size){var domModel=WebInspector.DOMModel.fromTarget(target);if(domModel)
domModel.pushNodesByBackendIdsToFrontend(nodeIdsToResolve,barrier.createCallback(setRelatedNodeMap));}
barrier.callWhenDone(callbackWrapper);function saveImage(element)
{event.previewElement=element||null;}
function setRelatedNodeMap(nodeMap)
{relatedNodes=nodeMap;}
function callbackWrapper()
{callback(WebInspector.TimelineUIUtils._buildTraceEventDetailsSynchronously(event,model,linkifier,detailed,relatedNodes));}}
WebInspector.TimelineUIUtils._buildTraceEventDetailsSynchronously=function(event,model,linkifier,detailed,relatedNodesMap)
{var stats={};var recordTypes=WebInspector.TimelineModel.RecordType;var relatedNodeLabel;var contentHelper=new WebInspector.TimelineDetailsContentHelper(model.targetByEvent(event),linkifier);contentHelper.addSection(WebInspector.TimelineUIUtils.eventTitle(event),WebInspector.TimelineUIUtils.eventStyle(event).category);var eventData=event.args["data"];var initiator=event.initiator;if(event.warning)
contentHelper.appendWarningRow(event);if(event.name===recordTypes.JSFrame&&eventData["deoptReason"])
contentHelper.appendWarningRow(event,WebInspector.TimelineModel.WarningType.V8Deopt);if(detailed){contentHelper.appendTextRow(WebInspector.UIString("Self Time"),Number.millisToString(event.selfTime,true));contentHelper.appendTextRow(WebInspector.UIString("Total Time"),Number.millisToString(event.duration||0,true));}
switch(event.name){case recordTypes.GCEvent:case recordTypes.MajorGC:case recordTypes.MinorGC:var delta=event.args["usedHeapSizeBefore"]-event.args["usedHeapSizeAfter"];contentHelper.appendTextRow(WebInspector.UIString("Collected"),Number.bytesToString(delta));break;case recordTypes.JSFrame:case recordTypes.FunctionCall:var detailsNode=WebInspector.TimelineUIUtils.buildDetailsNodeForTraceEvent(event,model.targetByEvent(event),linkifier);if(detailsNode)
contentHelper.appendElementRow(WebInspector.UIString("Function"),detailsNode);break;case recordTypes.TimerFire:case recordTypes.TimerInstall:case recordTypes.TimerRemove:contentHelper.appendTextRow(WebInspector.UIString("Timer ID"),eventData["timerId"]);if(event.name===recordTypes.TimerInstall){contentHelper.appendTextRow(WebInspector.UIString("Timeout"),Number.millisToString(eventData["timeout"]));contentHelper.appendTextRow(WebInspector.UIString("Repeats"),!eventData["singleShot"]);}
break;case recordTypes.FireAnimationFrame:contentHelper.appendTextRow(WebInspector.UIString("Callback ID"),eventData["id"]);break;case recordTypes.ResourceSendRequest:case recordTypes.ResourceReceiveResponse:case recordTypes.ResourceReceivedData:case recordTypes.ResourceFinish:var url=(event.name===recordTypes.ResourceSendRequest)?eventData["url"]:initiator&&initiator.args["data"]["url"];if(url)
contentHelper.appendElementRow(WebInspector.UIString("Resource"),WebInspector.linkifyResourceAsNode(url));if(eventData["requestMethod"])
contentHelper.appendTextRow(WebInspector.UIString("Request Method"),eventData["requestMethod"]);if(typeof eventData["statusCode"]==="number")
contentHelper.appendTextRow(WebInspector.UIString("Status Code"),eventData["statusCode"]);if(eventData["mimeType"])
contentHelper.appendTextRow(WebInspector.UIString("MIME Type"),eventData["mimeType"]);if("priority"in eventData){var priority=WebInspector.uiLabelForPriority(eventData["priority"]);contentHelper.appendTextRow(WebInspector.UIString("Priority"),priority);}
if(eventData["encodedDataLength"])
contentHelper.appendTextRow(WebInspector.UIString("Encoded Data Length"),WebInspector.UIString("%d Bytes",eventData["encodedDataLength"]));break;case recordTypes.CompileScript:case recordTypes.EvaluateScript:var url=eventData["url"];if(url)
contentHelper.appendLocationRow(WebInspector.UIString("Script"),url,eventData["lineNumber"],eventData["columnNumber"]);break;case recordTypes.Paint:var clip=eventData["clip"];contentHelper.appendTextRow(WebInspector.UIString("Location"),WebInspector.UIString("(%d, %d)",clip[0],clip[1]));var clipWidth=WebInspector.TimelineUIUtils.quadWidth(clip);var clipHeight=WebInspector.TimelineUIUtils.quadHeight(clip);contentHelper.appendTextRow(WebInspector.UIString("Dimensions"),WebInspector.UIString("%d × %d",clipWidth,clipHeight));case recordTypes.PaintSetup:case recordTypes.Rasterize:case recordTypes.ScrollLayer:relatedNodeLabel=WebInspector.UIString("Layer Root");break;case recordTypes.PaintImage:case recordTypes.DecodeLazyPixelRef:case recordTypes.DecodeImage:case recordTypes.ResizeImage:case recordTypes.DrawLazyPixelRef:relatedNodeLabel=WebInspector.UIString("Owner Element");if(event.url)
contentHelper.appendElementRow(WebInspector.UIString("Image URL"),WebInspector.linkifyResourceAsNode(event.url));break;case recordTypes.ParseAuthorStyleSheet:var url=eventData["styleSheetUrl"];if(url)
contentHelper.appendElementRow(WebInspector.UIString("Stylesheet URL"),WebInspector.linkifyResourceAsNode(url));break;case recordTypes.UpdateLayoutTree:case recordTypes.RecalculateStyles:contentHelper.appendTextRow(WebInspector.UIString("Elements Affected"),event.args["elementCount"]);break;case recordTypes.Layout:var beginData=event.args["beginData"];contentHelper.appendTextRow(WebInspector.UIString("Nodes That Need Layout"),WebInspector.UIString("%s of %s",beginData["dirtyObjects"],beginData["totalObjects"]));relatedNodeLabel=WebInspector.UIString("Layout root");break;case recordTypes.ConsoleTime:contentHelper.appendTextRow(WebInspector.UIString("Message"),event.name);break;case recordTypes.WebSocketCreate:case recordTypes.WebSocketSendHandshakeRequest:case recordTypes.WebSocketReceiveHandshakeResponse:case recordTypes.WebSocketDestroy:var initiatorData=initiator?initiator.args["data"]:eventData;if(typeof initiatorData["webSocketURL"]!=="undefined")
contentHelper.appendTextRow(WebInspector.UIString("URL"),initiatorData["webSocketURL"]);if(typeof initiatorData["webSocketProtocol"]!=="undefined")
contentHelper.appendTextRow(WebInspector.UIString("WebSocket Protocol"),initiatorData["webSocketProtocol"]);if(typeof eventData["message"]!=="undefined")
contentHelper.appendTextRow(WebInspector.UIString("Message"),eventData["message"]);break;case recordTypes.EmbedderCallback:contentHelper.appendTextRow(WebInspector.UIString("Callback Function"),eventData["callbackName"]);break;case recordTypes.Animation:if(event.phase===WebInspector.TracingModel.Phase.NestableAsyncInstant)
contentHelper.appendTextRow(WebInspector.UIString("State"),eventData["state"]);break;case recordTypes.ParseHTML:var beginData=event.args["beginData"];var url=beginData["url"];var startLine=beginData["startLine"]-1;var endLine=event.args["endData"]?event.args["endData"]["endLine"]-1:undefined;if(url)
contentHelper.appendLocationRange(WebInspector.UIString("Range"),url,startLine,endLine);break;case recordTypes.FireIdleCallback:contentHelper.appendTextRow(WebInspector.UIString("Allotted Time"),Number.millisToString(eventData["allottedMilliseconds"]));contentHelper.appendTextRow(WebInspector.UIString("Invoked by Timeout"),eventData["timedOut"]);case recordTypes.RequestIdleCallback:case recordTypes.CancelIdleCallback:contentHelper.appendTextRow(WebInspector.UIString("Callback ID"),eventData["id"]);break;case recordTypes.EventDispatch:contentHelper.appendTextRow(WebInspector.UIString("Type"),eventData["type"]);break;default:var detailsNode=WebInspector.TimelineUIUtils.buildDetailsNodeForTraceEvent(event,model.targetByEvent(event),linkifier);if(detailsNode)
contentHelper.appendElementRow(WebInspector.UIString("Details"),detailsNode);break;}
if(event.timeWaitingForMainThread)
contentHelper.appendTextRow(WebInspector.UIString("Time Waiting for Main Thread"),Number.millisToString(event.timeWaitingForMainThread,true));var relatedNode=relatedNodesMap&&relatedNodesMap.get(event.backendNodeId);if(relatedNode)
contentHelper.appendElementRow(relatedNodeLabel||WebInspector.UIString("Related Node"),WebInspector.DOMPresentationUtils.linkifyNodeReference(relatedNode));if(event.previewElement){contentHelper.addSection(WebInspector.UIString("Preview"));contentHelper.appendElementRow("",event.previewElement);}
if(event.stackTrace||(event.initiator&&event.initiator.stackTrace)||event.invalidationTrackingEvents)
WebInspector.TimelineUIUtils._generateCauses(event,model.targetByEvent(event),relatedNodesMap,contentHelper);var showPieChart=detailed&&WebInspector.TimelineUIUtils._aggregatedStatsForTraceEvent(stats,model,event);if(showPieChart){contentHelper.addSection(WebInspector.UIString("Aggregated Time"));var pieChart=WebInspector.TimelineUIUtils.generatePieChart(stats,WebInspector.TimelineUIUtils.eventStyle(event).category,event.selfTime);contentHelper.appendElementRow("",pieChart);}
return contentHelper.fragment;}
WebInspector.TimelineUIUtils._aggregatedStatsKey=Symbol("aggregatedStats");WebInspector.TimelineUIUtils.buildRangeStats=function(model,startTime,endTime)
{var aggregatedStats={};function compareEndTime(value,task)
{return value<task.endTime()?-1:1;}
var mainThreadTasks=model.mainThreadTasks();var taskIndex=mainThreadTasks.lowerBound(startTime,compareEndTime);for(;taskIndex<mainThreadTasks.length;++taskIndex){var task=mainThreadTasks[taskIndex];if(task.startTime()>endTime)
break;if(task.startTime()>startTime&&task.endTime()<endTime){var taskStats=task[WebInspector.TimelineUIUtils._aggregatedStatsKey];if(!taskStats){taskStats={};WebInspector.TimelineUIUtils._collectAggregatedStatsForRecord(task,startTime,endTime,taskStats);task[WebInspector.TimelineUIUtils._aggregatedStatsKey]=taskStats;}
for(var key in taskStats)
aggregatedStats[key]=(aggregatedStats[key]||0)+taskStats[key];continue;}
WebInspector.TimelineUIUtils._collectAggregatedStatsForRecord(task,startTime,endTime,aggregatedStats);}
var aggregatedTotal=0;for(var categoryName in aggregatedStats)
aggregatedTotal+=aggregatedStats[categoryName];aggregatedStats["idle"]=Math.max(0,endTime-startTime-aggregatedTotal);var startOffset=startTime-model.minimumRecordTime();var endOffset=endTime-model.minimumRecordTime();var contentHelper=new WebInspector.TimelineDetailsContentHelper(null,null);contentHelper.addSection(WebInspector.UIString("Range:  %s \u2013 %s",Number.millisToString(startOffset),Number.millisToString(endOffset)));var pieChart=WebInspector.TimelineUIUtils.generatePieChart(aggregatedStats);contentHelper.appendElementRow("",pieChart);return contentHelper.fragment;}
WebInspector.TimelineUIUtils._collectAggregatedStatsForRecord=function(record,startTime,endTime,aggregatedStats)
{var records=[];if(!record.endTime()||record.endTime()<startTime||record.startTime()>endTime)
return;var childrenTime=0;var children=record.children()||[];for(var i=0;i<children.length;++i){var child=children[i];if(!child.endTime()||child.endTime()<startTime||child.startTime()>endTime)
continue;childrenTime+=Math.min(endTime,child.endTime())-Math.max(startTime,child.startTime());WebInspector.TimelineUIUtils._collectAggregatedStatsForRecord(child,startTime,endTime,aggregatedStats);}
var categoryName=WebInspector.TimelineUIUtils.categoryForRecord(record).name;var ownTime=Math.min(endTime,record.endTime())-Math.max(startTime,record.startTime())-childrenTime;aggregatedStats[categoryName]=(aggregatedStats[categoryName]||0)+ownTime;}
WebInspector.TimelineUIUtils.buildNetworkRequestDetails=function(request,model,linkifier)
{var target=model.targetByEvent(request.children[0]);var contentHelper=new WebInspector.TimelineDetailsContentHelper(target,linkifier);var duration=request.endTime-(request.startTime||-Infinity);var items=[];if(request.url)
contentHelper.appendElementRow(WebInspector.UIString("URL"),WebInspector.linkifyURLAsNode(request.url));if(isFinite(duration))
contentHelper.appendTextRow(WebInspector.UIString("Duration"),Number.millisToString(duration,true));if(request.requestMethod)
contentHelper.appendTextRow(WebInspector.UIString("Request Method"),request.requestMethod);if(typeof request.priority==="string"){var priority=WebInspector.uiLabelForPriority((request.priority));contentHelper.appendTextRow(WebInspector.UIString("Priority"),priority);}
if(request.mimeType)
contentHelper.appendTextRow(WebInspector.UIString("Mime Type"),request.mimeType);var title=WebInspector.UIString("Initiator");var sendRequest=request.children[0];var topFrame=WebInspector.TimelineUIUtils.topStackFrame(sendRequest);if(topFrame){var link=linkifier.maybeLinkifyConsoleCallFrame(target,topFrame);if(link)
contentHelper.appendElementRow(title,link);}else if(sendRequest.initiator){var initiatorURL=WebInspector.TimelineUIUtils.eventURL(sendRequest.initiator);if(initiatorURL){var link=linkifier.maybeLinkifyScriptLocation(target,null,initiatorURL,0);if(link)
contentHelper.appendElementRow(title,link);}}
function action(fulfill)
{WebInspector.DOMPresentationUtils.buildImagePreviewContents((target),request.url,false,saveImage);function saveImage(element)
{request.previewElement=element||null;fulfill(request.previewElement);}}
var previewPromise;if(request.previewElement)
previewPromise=Promise.resolve(request.previewElement);else
previewPromise=request.url&&target?new Promise(action):Promise.resolve(null);function appendPreview(element)
{if(element)
contentHelper.appendElementRow(WebInspector.UIString("Preview"),request.previewElement);return contentHelper.fragment;}
return previewPromise.then(appendPreview);}
WebInspector.TimelineUIUtils._stackTraceFromCallFrames=function(callFrames)
{return({callFrames:callFrames});}
WebInspector.TimelineUIUtils._generateCauses=function(event,target,relatedNodesMap,contentHelper)
{var recordTypes=WebInspector.TimelineModel.RecordType;var callSiteStackLabel;var stackLabel;var initiator=event.initiator;switch(event.name){case recordTypes.TimerFire:callSiteStackLabel=WebInspector.UIString("Timer Installed");break;case recordTypes.FireAnimationFrame:callSiteStackLabel=WebInspector.UIString("Animation Frame Requested");break;case recordTypes.FireIdleCallback:callSiteStackLabel=WebInspector.UIString("Idle Callback Requested");break;case recordTypes.UpdateLayoutTree:case recordTypes.RecalculateStyles:stackLabel=WebInspector.UIString("Recalculation Forced");break;case recordTypes.Layout:callSiteStackLabel=WebInspector.UIString("First Layout Invalidation");stackLabel=WebInspector.UIString("Layout Forced");break;}
if(event.stackTrace&&event.stackTrace.length){contentHelper.addSection(WebInspector.UIString("Call Stacks"));contentHelper.appendStackTrace(stackLabel||WebInspector.UIString("Stack Trace"),WebInspector.TimelineUIUtils._stackTraceFromCallFrames(event.stackTrace));}
if(event.invalidationTrackingEvents&&target){contentHelper.addSection(WebInspector.UIString("Invalidations"));WebInspector.TimelineUIUtils._generateInvalidations(event,target,relatedNodesMap,contentHelper);}else if(initiator&&initiator.stackTrace){contentHelper.appendStackTrace(callSiteStackLabel||WebInspector.UIString("First Invalidated"),WebInspector.TimelineUIUtils._stackTraceFromCallFrames(initiator.stackTrace));}}
WebInspector.TimelineUIUtils._generateInvalidations=function(event,target,relatedNodesMap,contentHelper)
{if(!event.invalidationTrackingEvents)
return;var invalidations={};event.invalidationTrackingEvents.forEach(function(invalidation){if(!invalidations[invalidation.type])
invalidations[invalidation.type]=[invalidation];else
invalidations[invalidation.type].push(invalidation);});Object.keys(invalidations).forEach(function(type){WebInspector.TimelineUIUtils._generateInvalidationsForType(type,target,invalidations[type],relatedNodesMap,contentHelper);});}
WebInspector.TimelineUIUtils._generateInvalidationsForType=function(type,target,invalidations,relatedNodesMap,contentHelper)
{var title;switch(type){case WebInspector.TimelineModel.RecordType.StyleRecalcInvalidationTracking:title=WebInspector.UIString("Style Invalidations");break;case WebInspector.TimelineModel.RecordType.LayoutInvalidationTracking:title=WebInspector.UIString("Layout Invalidations");break;default:title=WebInspector.UIString("Other Invalidations");break;}
var invalidationsTreeOutline=new TreeOutlineInShadow();invalidationsTreeOutline.registerRequiredCSS("timeline/invalidationsTree.css");invalidationsTreeOutline.element.classList.add("invalidations-tree");var invalidationGroups=groupInvalidationsByCause(invalidations);invalidationGroups.forEach(function(group){var groupElement=new WebInspector.TimelineUIUtils.InvalidationsGroupElement(target,relatedNodesMap,contentHelper,group);invalidationsTreeOutline.appendChild(groupElement);});contentHelper.appendElementRow(title,invalidationsTreeOutline.element,false,true);function groupInvalidationsByCause(invalidations)
{var causeToInvalidationMap=new Map();for(var index=0;index<invalidations.length;index++){var invalidation=invalidations[index];var causeKey="";if(invalidation.cause.reason)
causeKey+=invalidation.cause.reason+".";if(invalidation.cause.stackTrace){invalidation.cause.stackTrace.forEach(function(stackFrame){causeKey+=stackFrame["functionName"]+".";causeKey+=stackFrame["scriptId"]+".";causeKey+=stackFrame["url"]+".";causeKey+=stackFrame["lineNumber"]+".";causeKey+=stackFrame["columnNumber"]+".";});}
if(causeToInvalidationMap.has(causeKey))
causeToInvalidationMap.get(causeKey).push(invalidation);else
causeToInvalidationMap.set(causeKey,[invalidation]);}
return causeToInvalidationMap.valuesArray();}}
WebInspector.TimelineUIUtils._collectInvalidationNodeIds=function(nodeIds,invalidations)
{for(var i=0;i<invalidations.length;++i){if(invalidations[i].nodeId)
nodeIds.add(invalidations[i].nodeId);}}
WebInspector.TimelineUIUtils.InvalidationsGroupElement=function(target,relatedNodesMap,contentHelper,invalidations)
{TreeElement.call(this,"",true);this.listItemElement.classList.add("header");this.selectable=false;this.toggleOnClick=true;this._relatedNodesMap=relatedNodesMap;this._contentHelper=contentHelper;this._invalidations=invalidations;this.title=this._createTitle(target);}
WebInspector.TimelineUIUtils.InvalidationsGroupElement.prototype={_createTitle:function(target)
{var first=this._invalidations[0];var reason=first.cause.reason;var topFrame=first.cause.stackTrace&&first.cause.stackTrace[0];var title=createElement("span");if(reason)
title.createTextChild(WebInspector.UIString("%s for ",reason));else
title.createTextChild(WebInspector.UIString("Unknown cause for "));this._appendTruncatedNodeList(title,this._invalidations);if(topFrame&&this._contentHelper.linkifier()){title.createTextChild(WebInspector.UIString(". "));var stack=title.createChild("span","monospace");stack.createChild("span").textContent=WebInspector.beautifyFunctionName(topFrame.functionName);var link=this._contentHelper.linkifier().maybeLinkifyConsoleCallFrame(target,topFrame);if(link){stack.createChild("span").textContent=" @ ";stack.createChild("span").appendChild(link);}}
return title;},onpopulate:function()
{var content=createElementWithClass("div","content");var first=this._invalidations[0];if(first.cause.stackTrace){var stack=content.createChild("div");stack.createTextChild(WebInspector.UIString("Stack trace:"));this._contentHelper.createChildStackTraceElement(stack,WebInspector.TimelineUIUtils._stackTraceFromCallFrames(first.cause.stackTrace));}
content.createTextChild(this._invalidations.length>1?WebInspector.UIString("Nodes:"):WebInspector.UIString("Node:"));var nodeList=content.createChild("div","node-list");var firstNode=true;for(var i=0;i<this._invalidations.length;i++){var invalidation=this._invalidations[i];var invalidationNode=this._createInvalidationNode(invalidation,true);if(invalidationNode){if(!firstNode)
nodeList.createTextChild(WebInspector.UIString(", "));firstNode=false;nodeList.appendChild(invalidationNode);var extraData=invalidation.extraData?", "+invalidation.extraData:"";if(invalidation.changedId)
nodeList.createTextChild(WebInspector.UIString("(changed id to \"%s\"%s)",invalidation.changedId,extraData));else if(invalidation.changedClass)
nodeList.createTextChild(WebInspector.UIString("(changed class to \"%s\"%s)",invalidation.changedClass,extraData));else if(invalidation.changedAttribute)
nodeList.createTextChild(WebInspector.UIString("(changed attribute to \"%s\"%s)",invalidation.changedAttribute,extraData));else if(invalidation.changedPseudo)
nodeList.createTextChild(WebInspector.UIString("(changed pesudo to \"%s\"%s)",invalidation.changedPseudo,extraData));else if(invalidation.selectorPart)
nodeList.createTextChild(WebInspector.UIString("(changed \"%s\"%s)",invalidation.selectorPart,extraData));}}
var contentTreeElement=new TreeElement(content,false);contentTreeElement.selectable=false;this.appendChild(contentTreeElement);},_appendTruncatedNodeList:function(parentElement,invalidations)
{var invalidationNodes=[];var invalidationNodeIdMap={};for(var i=0;i<invalidations.length;i++){var invalidation=invalidations[i];var invalidationNode=this._createInvalidationNode(invalidation,false);invalidationNode.addEventListener("click",consumeEvent,false);if(invalidationNode&&!invalidationNodeIdMap[invalidation.nodeId]){invalidationNodes.push(invalidationNode);invalidationNodeIdMap[invalidation.nodeId]=true;}}
if(invalidationNodes.length===1){parentElement.appendChild(invalidationNodes[0]);}else if(invalidationNodes.length===2){parentElement.appendChild(invalidationNodes[0]);parentElement.createTextChild(WebInspector.UIString(" and "));parentElement.appendChild(invalidationNodes[1]);}else if(invalidationNodes.length>=3){parentElement.appendChild(invalidationNodes[0]);parentElement.createTextChild(WebInspector.UIString(", "));parentElement.appendChild(invalidationNodes[1]);parentElement.createTextChild(WebInspector.UIString(", and %s others",invalidationNodes.length-2));}},_createInvalidationNode:function(invalidation,showUnknownNodes)
{var node=(invalidation.nodeId&&this._relatedNodesMap)?this._relatedNodesMap.get(invalidation.nodeId):null;if(node)
return WebInspector.DOMPresentationUtils.linkifyNodeReference(node);if(invalidation.nodeName){var nodeSpan=createElement("span");nodeSpan.textContent=WebInspector.UIString("[ %s ]",invalidation.nodeName);return nodeSpan;}
if(showUnknownNodes){var nodeSpan=createElement("span");return nodeSpan.createTextChild(WebInspector.UIString("[ unknown node ]"));}},__proto__:TreeElement.prototype}
WebInspector.TimelineUIUtils._aggregatedStatsForTraceEvent=function(total,model,event)
{var events=model.inspectedTargetEvents();function eventComparator(startTime,e)
{return startTime-e.startTime;}
var index=events.binaryIndexOf(event.startTime,eventComparator);if(index<0)
return false;var hasChildren=false;var endTime=event.endTime;if(endTime){for(var i=index;i<events.length;i++){var nextEvent=events[i];if(nextEvent.startTime>=endTime)
break;if(!nextEvent.selfTime)
continue;if(nextEvent.thread!==event.thread)
continue;if(i>index)
hasChildren=true;var categoryName=WebInspector.TimelineUIUtils.eventStyle(nextEvent).category.name;total[categoryName]=(total[categoryName]||0)+nextEvent.selfTime;}}
if(WebInspector.TracingModel.isAsyncPhase(event.phase)){if(event.endTime){var aggregatedTotal=0;for(var categoryName in total)
aggregatedTotal+=total[categoryName];total["idle"]=Math.max(0,event.endTime-event.startTime-aggregatedTotal);}
return false;}
return hasChildren;}
WebInspector.TimelineUIUtils.buildPicturePreviewContent=function(event,target,callback)
{new WebInspector.LayerPaintEvent(event,target).loadSnapshot(onSnapshotLoaded);function onSnapshotLoaded(rect,snapshot)
{if(!snapshot){callback();return;}
snapshot.requestImage(null,null,1,onGotImage);snapshot.dispose();}
function onGotImage(imageURL)
{if(!imageURL){callback();return;}
var container=createElement("div");container.classList.add("image-preview-container","vbox","link");var img=container.createChild("img");img.src=imageURL;var paintProfilerButton=container.createChild("a");paintProfilerButton.textContent=WebInspector.UIString("Paint Profiler");container.addEventListener("click",showPaintProfiler,false);callback(container);}
function showPaintProfiler()
{WebInspector.TimelinePanel.instance().select(WebInspector.TimelineSelection.fromTraceEvent(event),WebInspector.TimelinePanel.DetailsTab.PaintProfiler);}}
WebInspector.TimelineUIUtils.createEventDivider=function(recordType,title,position)
{var eventDivider=createElement("div");eventDivider.className="resources-event-divider";var recordTypes=WebInspector.TimelineModel.RecordType;if(recordType===recordTypes.MarkDOMContent)
eventDivider.className+=" resources-blue-divider";else if(recordType===recordTypes.MarkLoad)
eventDivider.className+=" resources-red-divider";else if(recordType===recordTypes.MarkFirstPaint)
eventDivider.className+=" resources-green-divider";else if(recordType===recordTypes.TimeStamp||recordType===recordTypes.ConsoleTime||recordType===recordTypes.UserTiming)
eventDivider.className+=" resources-orange-divider";else if(recordType===recordTypes.BeginFrame)
eventDivider.className+=" timeline-frame-divider";if(title)
eventDivider.title=title;eventDivider.style.left=position+"px";return eventDivider;}
WebInspector.TimelineUIUtils.createDividerForRecord=function(record,zeroTime,position)
{var startTime=Number.millisToString(record.startTime()-zeroTime);var title=WebInspector.UIString("%s at %s",WebInspector.TimelineUIUtils.eventTitle(record.traceEvent()),startTime);return WebInspector.TimelineUIUtils.createEventDivider(record.type(),title,position);}
WebInspector.TimelineUIUtils._visibleTypes=function()
{var eventStyles=WebInspector.TimelineUIUtils._initEventStyles();var result=[];for(var name in eventStyles){if(!eventStyles[name].hidden)
result.push(name);}
return result;}
WebInspector.TimelineUIUtils.visibleEventsFilter=function()
{return new WebInspector.TimelineVisibleEventsFilter(WebInspector.TimelineUIUtils._visibleTypes());}
WebInspector.TimelineUIUtils.categories=function()
{if(WebInspector.TimelineUIUtils._categories)
return WebInspector.TimelineUIUtils._categories;WebInspector.TimelineUIUtils._categories={loading:new WebInspector.TimelineCategory("loading",WebInspector.UIString("Loading"),true,"hsl(214, 67%, 74%)","hsl(214, 67%, 66%)"),scripting:new WebInspector.TimelineCategory("scripting",WebInspector.UIString("Scripting"),true,"hsl(43, 83%, 72%)","hsl(43, 83%, 64%) "),rendering:new WebInspector.TimelineCategory("rendering",WebInspector.UIString("Rendering"),true,"hsl(256, 67%, 76%)","hsl(256, 67%, 70%)"),painting:new WebInspector.TimelineCategory("painting",WebInspector.UIString("Painting"),true,"hsl(109, 33%, 64%)","hsl(109, 33%, 55%)"),gpu:new WebInspector.TimelineCategory("gpu",WebInspector.UIString("GPU"),false,"hsl(109, 33%, 64%)","hsl(109, 33%, 55%)"),other:new WebInspector.TimelineCategory("other",WebInspector.UIString("Other"),false,"hsl(0, 0%, 87%)","hsl(0, 0%, 79%)"),idle:new WebInspector.TimelineCategory("idle",WebInspector.UIString("Idle"),false,"hsl(0, 100%, 100%)","hsl(0, 100%, 100%)")};return WebInspector.TimelineUIUtils._categories;};WebInspector.TimelineUIUtils.titleForAsyncEventGroup=function(group)
{if(!WebInspector.TimelineUIUtils._titleForAsyncEventGroupMap){var groups=WebInspector.TimelineModel.AsyncEventGroup;WebInspector.TimelineUIUtils._titleForAsyncEventGroupMap=new Map([[groups.animation,WebInspector.UIString("Animation")],[groups.console,WebInspector.UIString("Console")],[groups.userTiming,WebInspector.UIString("User Timing")],[groups.input,WebInspector.UIString("Input")]]);}
return WebInspector.TimelineUIUtils._titleForAsyncEventGroupMap.get(group)||"";}
WebInspector.TimelineUIUtils.generatePieChart=function(aggregatedStats,selfCategory,selfTime)
{var total=0;for(var categoryName in aggregatedStats)
total+=aggregatedStats[categoryName];var element=createElementWithClass("div","timeline-details-view-pie-chart-wrapper hbox");var pieChart=new WebInspector.PieChart(100);pieChart.element.classList.add("timeline-details-view-pie-chart");pieChart.setTotal(total);var pieChartContainer=element.createChild("div","vbox");pieChartContainer.appendChild(pieChart.element);pieChartContainer.createChild("div","timeline-details-view-pie-chart-total").textContent=WebInspector.UIString("Total: %s",Number.millisToString(total,true));var footerElement=element.createChild("div","timeline-aggregated-info-legend");function appendLegendRow(name,title,value,color)
{if(!value)
return;pieChart.addSlice(value,color);var rowElement=footerElement.createChild("div");rowElement.createChild("span","timeline-aggregated-legend-value").textContent=Number.preciseMillisToString(value,1);rowElement.createChild("span","timeline-aggregated-legend-swatch").style.backgroundColor=color;rowElement.createChild("span","timeline-aggregated-legend-title").textContent=title;}
if(selfCategory){if(selfTime)
appendLegendRow(selfCategory.name,WebInspector.UIString("%s (self)",selfCategory.title),selfTime,selfCategory.color);var categoryTime=aggregatedStats[selfCategory.name];var value=categoryTime-selfTime;if(value>0)
appendLegendRow(selfCategory.name,WebInspector.UIString("%s (children)",selfCategory.title),value,selfCategory.childColor);}
for(var categoryName in WebInspector.TimelineUIUtils.categories()){var category=WebInspector.TimelineUIUtils.categories()[categoryName];if(category===selfCategory)
continue;appendLegendRow(category.name,category.title,aggregatedStats[category.name],category.childColor);}
return element;}
WebInspector.TimelineUIUtils.generateDetailsContentForFrame=function(frameModel,frame,filmStripFrame)
{var pieChart=WebInspector.TimelineUIUtils.generatePieChart(frame.timeByCategory);var contentHelper=new WebInspector.TimelineDetailsContentHelper(null,null);contentHelper.addSection(WebInspector.UIString("Frame"));var duration=WebInspector.TimelineUIUtils.frameDuration(frame);contentHelper.appendElementRow(WebInspector.UIString("Duration"),duration,frame.hasWarnings());if(filmStripFrame){var filmStripPreview=createElementWithClass("img","timeline-filmstrip-preview");filmStripFrame.imageDataPromise().then(onGotImageData.bind(null,filmStripPreview));contentHelper.appendElementRow("",filmStripPreview);filmStripPreview.addEventListener("click",frameClicked.bind(null,filmStripFrame),false);}
var durationInMillis=frame.endTime-frame.startTime;contentHelper.appendTextRow(WebInspector.UIString("FPS"),Math.floor(1000/durationInMillis));contentHelper.appendTextRow(WebInspector.UIString("CPU time"),Number.millisToString(frame.cpuTime,true));if(Runtime.experiments.isEnabled("layersPanel")&&frame.layerTree){contentHelper.appendElementRow(WebInspector.UIString("Layer tree"),WebInspector.Linkifier.linkifyUsingRevealer(frame.layerTree,WebInspector.UIString("show")));}
function onGotImageData(image,data)
{if(data)
image.src="data:image/jpg;base64,"+data;}
function frameClicked(filmStripFrame)
{new WebInspector.FilmStripView.Dialog(filmStripFrame,0);}
return contentHelper.fragment;}
WebInspector.TimelineUIUtils.frameDuration=function(frame)
{var durationText=WebInspector.UIString("%s (at %s)",Number.millisToString(frame.endTime-frame.startTime,true),Number.millisToString(frame.startTimeOffset,true));var element=createElement("span");element.createTextChild(durationText);if(!frame.hasWarnings())
return element;element.createTextChild(WebInspector.UIString(". Long frame times are an indication of "));element.appendChild(WebInspector.linkifyURLAsNode("https://developers.google.com/web/fundamentals/performance/rendering/",WebInspector.UIString("jank"),undefined,true));element.createTextChild(".");return element;}
WebInspector.TimelineUIUtils.createFillStyle=function(context,width,height,color0,color1,color2)
{var gradient=context.createLinearGradient(0,0,width,height);gradient.addColorStop(0,color0);gradient.addColorStop(0.25,color1);gradient.addColorStop(0.75,color1);gradient.addColorStop(1,color2);return gradient;}
WebInspector.TimelineUIUtils.quadWidth=function(quad)
{return Math.round(Math.sqrt(Math.pow(quad[0]-quad[2],2)+Math.pow(quad[1]-quad[3],2)));}
WebInspector.TimelineUIUtils.quadHeight=function(quad)
{return Math.round(Math.sqrt(Math.pow(quad[0]-quad[6],2)+Math.pow(quad[1]-quad[7],2)));}
WebInspector.TimelineUIUtils.EventDispatchTypeDescriptor=function(priority,color,eventTypes)
{this.priority=priority;this.color=color;this.eventTypes=eventTypes;}
WebInspector.TimelineUIUtils.eventDispatchDesciptors=function()
{if(WebInspector.TimelineUIUtils._eventDispatchDesciptors)
return WebInspector.TimelineUIUtils._eventDispatchDesciptors;var lightOrange="hsl(40,100%,80%)";var orange="hsl(40,100%,50%)";var green="hsl(90,100%,40%)";var purple="hsl(256,100%,75%)";WebInspector.TimelineUIUtils._eventDispatchDesciptors=[new WebInspector.TimelineUIUtils.EventDispatchTypeDescriptor(1,lightOrange,["mousemove","mouseenter","mouseleave","mouseout","mouseover"]),new WebInspector.TimelineUIUtils.EventDispatchTypeDescriptor(1,lightOrange,["pointerover","pointerout","pointerenter","pointerleave","pointermove"]),new WebInspector.TimelineUIUtils.EventDispatchTypeDescriptor(2,green,["wheel"]),new WebInspector.TimelineUIUtils.EventDispatchTypeDescriptor(3,orange,["click","mousedown","mouseup"]),new WebInspector.TimelineUIUtils.EventDispatchTypeDescriptor(3,orange,["touchstart","touchend","touchmove","touchcancel"]),new WebInspector.TimelineUIUtils.EventDispatchTypeDescriptor(3,orange,["pointerdown","pointerup","pointercancel","gotpointercapture","lostpointercapture"]),new WebInspector.TimelineUIUtils.EventDispatchTypeDescriptor(3,purple,["keydown","keyup","keypress"])];return WebInspector.TimelineUIUtils._eventDispatchDesciptors;}
WebInspector.TimelineCategory=function(name,title,visible,childColor,color)
{this.name=name;this.title=title;this.visible=visible;this.childColor=childColor;this.color=color;this.hidden=false;}
WebInspector.TimelineCategory.Events={VisibilityChanged:Symbol("VisibilityChanged")};WebInspector.TimelineCategory.prototype={get hidden()
{return this._hidden;},set hidden(hidden)
{this._hidden=hidden;this.dispatchEventToListeners(WebInspector.TimelineCategory.Events.VisibilityChanged,this);},__proto__:WebInspector.Object.prototype}
WebInspector.TimelineMarkerStyle;WebInspector.TimelineUIUtils.markerStyleForEvent=function(event)
{var red="rgb(255, 0, 0)";var blue="rgb(0, 0, 255)";var orange="rgb(255, 178, 23)";var green="rgb(0, 130, 0)";var tallMarkerDashStyle=[10,5];var title=WebInspector.TimelineUIUtils.eventTitle(event)
if(event.hasCategory(WebInspector.TimelineModel.Category.Console)||event.hasCategory(WebInspector.TimelineModel.Category.UserTiming)){return{title:title,dashStyle:tallMarkerDashStyle,lineWidth:0.5,color:orange,tall:false,lowPriority:false,};}
var recordTypes=WebInspector.TimelineModel.RecordType;var tall=false;var color=green;switch(event.name){case recordTypes.MarkDOMContent:color=blue;tall=true;break;case recordTypes.MarkLoad:color=red;tall=true;break;case recordTypes.MarkFirstPaint:color=green;tall=true;break;case recordTypes.TimeStamp:color=orange;break;}
return{title:title,dashStyle:tallMarkerDashStyle,lineWidth:0.5,color:color,tall:tall,lowPriority:false,};}
WebInspector.TimelineUIUtils.markerStyleForFrame=function()
{return{title:WebInspector.UIString("Frame"),color:"rgba(100, 100, 100, 0.4)",lineWidth:3,dashStyle:[3],tall:true,lowPriority:true};}
WebInspector.TimelineUIUtils.colorForURL=function(url)
{if(!WebInspector.TimelineUIUtils.colorForURL._colorGenerator){WebInspector.TimelineUIUtils.colorForURL._colorGenerator=new WebInspector.FlameChart.ColorGenerator({min:30,max:330},{min:50,max:80,count:3},85);}
return WebInspector.TimelineUIUtils.colorForURL._colorGenerator.colorForID(url);}
WebInspector.TimelinePopupContentHelper=function(title)
{this._contentTable=createElement("table");var titleCell=this._createCell(WebInspector.UIString("%s - Details",title),"timeline-details-title");titleCell.colSpan=2;var titleRow=createElement("tr");titleRow.appendChild(titleCell);this._contentTable.appendChild(titleRow);}
WebInspector.TimelinePopupContentHelper.prototype={contentTable:function()
{return this._contentTable;},_createCell:function(content,styleName)
{var text=createElement("label");text.createTextChild(String(content));var cell=createElement("td");cell.className="timeline-details";if(styleName)
cell.className+=" "+styleName;cell.textContent=content;return cell;},appendTextRow:function(title,content)
{var row=createElement("tr");row.appendChild(this._createCell(title,"timeline-details-row-title"));row.appendChild(this._createCell(content,"timeline-details-row-data"));this._contentTable.appendChild(row);},appendElementRow:function(title,content)
{var row=createElement("tr");var titleCell=this._createCell(title,"timeline-details-row-title");row.appendChild(titleCell);var cell=createElement("td");cell.className="details";if(content instanceof Node)
cell.appendChild(content);else
cell.createTextChild(content||"");row.appendChild(cell);this._contentTable.appendChild(row);}}
WebInspector.TimelineDetailsContentHelper=function(target,linkifier)
{this.fragment=createDocumentFragment();this._linkifier=linkifier;this._target=target;this.element=createElementWithClass("div","timeline-details-view-block");this._tableElement=this.element.createChild("div","vbox timeline-details-chip-body");this.fragment.appendChild(this.element);}
WebInspector.TimelineDetailsContentHelper.prototype={addSection:function(title,category)
{if(!this._tableElement.hasChildNodes()){this.element.removeChildren();}else{this.element=createElementWithClass("div","timeline-details-view-block");this.fragment.appendChild(this.element);}
if(title){var titleElement=this.element.createChild("div","timeline-details-chip-title");if(category)
titleElement.createChild("div").style.backgroundColor=category.color;titleElement.createTextChild(title);}
this._tableElement=this.element.createChild("div","vbox timeline-details-chip-body");this.fragment.appendChild(this.element);},linkifier:function()
{return this._linkifier;},appendTextRow:function(title,value)
{var rowElement=this._tableElement.createChild("div","timeline-details-view-row");rowElement.createChild("div","timeline-details-view-row-title").textContent=title;rowElement.createChild("div","timeline-details-view-row-value").textContent=value;},appendElementRow:function(title,content,isWarning,isStacked)
{var rowElement=this._tableElement.createChild("div","timeline-details-view-row");if(isWarning)
rowElement.classList.add("timeline-details-warning");if(isStacked)
rowElement.classList.add("timeline-details-stack-values");var titleElement=rowElement.createChild("div","timeline-details-view-row-title");titleElement.textContent=title;var valueElement=rowElement.createChild("div","timeline-details-view-row-value");if(content instanceof Node)
valueElement.appendChild(content);else
valueElement.createTextChild(content||"");},appendLocationRow:function(title,url,startLine,startColumn)
{if(!this._linkifier||!this._target)
return;var link=this._linkifier.maybeLinkifyScriptLocation(this._target,null,url,startLine,startColumn);if(!link)
return;this.appendElementRow(title,link);},appendLocationRange:function(title,url,startLine,endLine)
{if(!this._linkifier||!this._target)
return;var locationContent=createElement("span");var link=this._linkifier.maybeLinkifyScriptLocation(this._target,null,url,startLine);if(!link)
return;locationContent.appendChild(link);locationContent.createTextChild(String.sprintf(" [%s\u2026%s]",startLine+1,endLine+1||""));this.appendElementRow(title,locationContent);},appendStackTrace:function(title,stackTrace)
{if(!this._linkifier||!this._target)
return;var rowElement=this._tableElement.createChild("div","timeline-details-view-row");rowElement.createChild("div","timeline-details-view-row-title").textContent=title;this.createChildStackTraceElement(rowElement,stackTrace);},createChildStackTraceElement:function(parentElement,stackTrace)
{if(!this._linkifier||!this._target)
return;parentElement.classList.add("timeline-details-stack-values");var stackTraceElement=parentElement.createChild("div","timeline-details-view-row-value timeline-details-view-row-stack-trace");var callFrameElem=WebInspector.DOMPresentationUtils.buildStackTracePreviewContents(this._target,this._linkifier,stackTrace);stackTraceElement.appendChild(callFrameElem);},appendWarningRow:function(event,warningType)
{var warning=WebInspector.TimelineUIUtils.eventWarning(event,warningType);if(warning)
this.appendElementRow(WebInspector.UIString("Warning"),warning,true);}}
WebInspector.TimelineUIUtils.eventWarning=function(event,warningType)
{var warning=warningType||event.warning;if(!warning)
return null;var warnings=WebInspector.TimelineModel.WarningType;var span=createElement("span");var eventData=event.args["data"];switch(warning){case warnings.ForcedStyle:case warnings.ForcedLayout:span.appendChild(WebInspector.linkifyDocumentationURLAsNode("../../fundamentals/performance/rendering/avoid-large-complex-layouts-and-layout-thrashing#avoid-forced-synchronous-layouts",WebInspector.UIString("Forced reflow")));span.createTextChild(WebInspector.UIString(" is a likely performance bottleneck."));break;case warnings.IdleDeadlineExceeded:span.textContent=WebInspector.UIString("Idle callback execution extended beyond deadline by "+
Number.millisToString(event.duration-eventData["allottedMilliseconds"],true));break;case warnings.V8Deopt:span.appendChild(WebInspector.linkifyURLAsNode("https://github.com/GoogleChrome/devtools-docs/issues/53",WebInspector.UIString("Not optimized"),undefined,true));span.createTextChild(WebInspector.UIString(": %s",eventData["deoptReason"]));break;default:console.assert(false,"Unhandled TimelineModel.WarningType");}
return span;}},{}],227:[function(require,module,exports){WebInspector.TracingLayerPayload;WebInspector.TracingLayerTile;WebInspector.LayerTreeModel=function(target)
{WebInspector.SDKModel.call(this,WebInspector.LayerTreeModel,target);target.registerLayerTreeDispatcher(new WebInspector.LayerTreeDispatcher(this));WebInspector.targetManager.addEventListener(WebInspector.TargetManager.Events.MainFrameNavigated,this._onMainFrameNavigated,this);this._layerTree=null;}
WebInspector.LayerTreeModel.Events={LayerTreeChanged:Symbol("LayerTreeChanged"),LayerPainted:Symbol("LayerPainted"),}
WebInspector.LayerTreeModel.ScrollRectType={NonFastScrollable:{name:"NonFastScrollable",description:"Non fast scrollable"},TouchEventHandler:{name:"TouchEventHandler",description:"Touch event handler"},WheelEventHandler:{name:"WheelEventHandler",description:"Wheel event handler"},RepaintsOnScroll:{name:"RepaintsOnScroll",description:"Repaints on scroll"}}
WebInspector.LayerTreeModel.prototype={disable:function()
{if(!this._enabled)
return;this._enabled=false;this._layerTree=null;this.target().layerTreeAgent().disable();},enable:function()
{if(this._enabled)
return;this._enabled=true;this._forceEnable();},_forceEnable:function()
{this._layerTree=new WebInspector.AgentLayerTree(this.target());this._lastPaintRectByLayerId={};this.target().layerTreeAgent().enable();},setLayerTree:function(layerTree)
{this.disable();this._layerTree=layerTree;this.dispatchEventToListeners(WebInspector.LayerTreeModel.Events.LayerTreeChanged);},layerTree:function()
{return this._layerTree;},_layerTreeChanged:function(layers)
{if(!this._enabled)
return;var layerTree=(this._layerTree);layerTree.setLayers(layers,onLayersSet.bind(this));function onLayersSet()
{for(var layerId in this._lastPaintRectByLayerId){var lastPaintRect=this._lastPaintRectByLayerId[layerId];var layer=layerTree.layerById(layerId);if(layer)
layer._lastPaintRect=lastPaintRect;}
this._lastPaintRectByLayerId={};this.dispatchEventToListeners(WebInspector.LayerTreeModel.Events.LayerTreeChanged);}},_layerPainted:function(layerId,clipRect)
{if(!this._enabled)
return;var layerTree=(this._layerTree);var layer=layerTree.layerById(layerId);if(!layer){this._lastPaintRectByLayerId[layerId]=clipRect;return;}
layer._didPaint(clipRect);this.dispatchEventToListeners(WebInspector.LayerTreeModel.Events.LayerPainted,layer);},_onMainFrameNavigated:function()
{if(this._enabled)
this._forceEnable();},__proto__:WebInspector.SDKModel.prototype}
WebInspector.LayerTreeBase=function(target)
{this._target=target;this._domModel=target?WebInspector.DOMModel.fromTarget(target):null;this._layersById={};this._backendNodeIdToNode=new Map();this._reset();}
WebInspector.LayerTreeBase.prototype={_reset:function()
{this._root=null;this._contentRoot=null;this._layers=null;},target:function()
{return this._target;},root:function()
{return this._root;},contentRoot:function()
{return this._contentRoot;},layers:function()
{return this._layers;},forEachLayer:function(callback,root)
{if(!root){root=this.root();if(!root)
return false;}
return callback(root)||root.children().some(this.forEachLayer.bind(this,callback));},layerById:function(id)
{return this._layersById[id]||null;},_resolveBackendNodeIds:function(requestedNodeIds,callback)
{if(!requestedNodeIds.size||!this._domModel){callback();return;}
if(this._domModel)
this._domModel.pushNodesByBackendIdsToFrontend(requestedNodeIds,populateBackendNodeMap.bind(this));function populateBackendNodeMap(nodesMap)
{if(nodesMap){for(var nodeId of nodesMap.keysArray())
this._backendNodeIdToNode.set(nodeId,nodesMap.get(nodeId)||null);}
callback();}},setViewportSize:function(viewportSize)
{this._viewportSize=viewportSize;},viewportSize:function()
{return this._viewportSize;},_nodeForId:function(id)
{return this._domModel?this._domModel.nodeForId(id):null;}}
WebInspector.TracingLayerTree=function(target)
{WebInspector.LayerTreeBase.call(this,target);this._tileById=new Map();}
WebInspector.TracingLayerTree.prototype={setLayers:function(root,layers,callback)
{var idsToResolve=new Set();if(root){this._extractNodeIdsToResolve(idsToResolve,{},root);}else{for(var i=0;i<layers.length;++i)
this._extractNodeIdsToResolve(idsToResolve,{},layers[i]);}
this._resolveBackendNodeIds(idsToResolve,onBackendNodeIdsResolved.bind(this));function onBackendNodeIdsResolved()
{var oldLayersById=this._layersById;this._layersById={};this._contentRoot=null;if(root){this._root=this._innerSetLayers(oldLayersById,root);}else{this._layers=layers.map(this._innerSetLayers.bind(this,oldLayersById));this._root=this._contentRoot;for(var i=0;i<this._layers.length;++i){if(this._layers[i].id()!==this._contentRoot.id()){this._contentRoot.addChild(this._layers[i]);}}}
callback();}},setTiles:function(tiles)
{this._tileById=new Map();for(var tile of tiles)
this._tileById.set(tile.id,tile);},tileById:function(id)
{return this._tileById.get(id)||null;},_innerSetLayers:function(oldLayersById,payload)
{var layer=(oldLayersById[payload.layer_id]);if(layer)
layer._reset(payload);else
layer=new WebInspector.TracingLayer(payload);this._layersById[payload.layer_id]=layer;if(payload.owner_node)
layer._setNode(this._backendNodeIdToNode.get(payload.owner_node)||null);if(!this._contentRoot&&layer.drawsContent())
this._contentRoot=layer;for(var i=0;payload.children&&i<payload.children.length;++i)
layer.addChild(this._innerSetLayers(oldLayersById,payload.children[i]));return layer;},_extractNodeIdsToResolve:function(nodeIdsToResolve,seenNodeIds,payload)
{var backendNodeId=payload.owner_node;if(backendNodeId&&!this._backendNodeIdToNode.has(backendNodeId))
nodeIdsToResolve.add(backendNodeId);for(var i=0;payload.children&&i<payload.children.length;++i)
this._extractNodeIdsToResolve(nodeIdsToResolve,seenNodeIds,payload.children[i]);},__proto__:WebInspector.LayerTreeBase.prototype}
WebInspector.AgentLayerTree=function(target)
{WebInspector.LayerTreeBase.call(this,target);}
WebInspector.AgentLayerTree.prototype={setLayers:function(payload,callback)
{if(!payload){onBackendNodeIdsResolved.call(this);return;}
var idsToResolve=new Set();for(var i=0;i<payload.length;++i){var backendNodeId=payload[i].backendNodeId;if(!backendNodeId||this._backendNodeIdToNode.has(backendNodeId))
continue;idsToResolve.add(backendNodeId);}
this._resolveBackendNodeIds(idsToResolve,onBackendNodeIdsResolved.bind(this));function onBackendNodeIdsResolved()
{this._innerSetLayers(payload);callback();}},_innerSetLayers:function(layers)
{this._reset();if(!layers)
return;var oldLayersById=this._layersById;this._layersById={};for(var i=0;i<layers.length;++i){var layerId=layers[i].layerId;var layer=oldLayersById[layerId];if(layer)
layer._reset(layers[i]);else
layer=new WebInspector.AgentLayer(this._target,layers[i]);this._layersById[layerId]=layer;var backendNodeId=layers[i].backendNodeId;if(backendNodeId)
layer._setNode(this._backendNodeIdToNode.get(backendNodeId));if(!this._contentRoot&&layer.drawsContent())
this._contentRoot=layer;var parentId=layer.parentId();if(parentId){var parent=this._layersById[parentId];if(!parent)
console.assert(parent,"missing parent "+parentId+" for layer "+layerId);parent.addChild(layer);}else{if(this._root)
console.assert(false,"Multiple root layers");this._root=layer;}}
if(this._root)
this._root._calculateQuad(new WebKitCSSMatrix());},__proto__:WebInspector.LayerTreeBase.prototype}
WebInspector.Layer=function()
{}
WebInspector.Layer.prototype={id:function(){},parentId:function(){},parent:function(){},isRoot:function(){},children:function(){},addChild:function(child){},node:function(){},nodeForSelfOrAncestor:function(){},offsetX:function(){},offsetY:function(){},width:function(){},height:function(){},transform:function(){},quad:function(){},anchorPoint:function(){},invisible:function(){},paintCount:function(){},lastPaintRect:function(){},scrollRects:function(){},gpuMemoryUsage:function(){},requestCompositingReasons:function(callback){},drawsContent:function(){}}
WebInspector.AgentLayer=function(target,layerPayload)
{this._target=target;this._reset(layerPayload);}
WebInspector.AgentLayer.prototype={id:function()
{return this._layerPayload.layerId;},parentId:function()
{return this._layerPayload.parentLayerId;},parent:function()
{return this._parent;},isRoot:function()
{return!this.parentId();},children:function()
{return this._children;},addChild:function(child)
{if(child._parent)
console.assert(false,"Child already has a parent");this._children.push(child);child._parent=this;},_setNode:function(node)
{this._node=node;},node:function()
{return this._node;},nodeForSelfOrAncestor:function()
{for(var layer=this;layer;layer=layer._parent){if(layer._node)
return layer._node;}
return null;},offsetX:function()
{return this._layerPayload.offsetX;},offsetY:function()
{return this._layerPayload.offsetY;},width:function()
{return this._layerPayload.width;},height:function()
{return this._layerPayload.height;},transform:function()
{return this._layerPayload.transform;},quad:function()
{return this._quad;},anchorPoint:function()
{return[this._layerPayload.anchorX||0,this._layerPayload.anchorY||0,this._layerPayload.anchorZ||0,];},invisible:function()
{return this._layerPayload.invisible;},paintCount:function()
{return this._paintCount||this._layerPayload.paintCount;},lastPaintRect:function()
{return this._lastPaintRect;},scrollRects:function()
{return this._scrollRects;},requestCompositingReasons:function(callback)
{if(!this._target){callback([]);return;}
var wrappedCallback=InspectorBackend.wrapClientCallback(callback,"LayerTreeAgent.reasonsForCompositingLayer(): ",undefined,[]);this._target.layerTreeAgent().compositingReasons(this.id(),wrappedCallback);},drawsContent:function()
{return this._layerPayload.drawsContent;},gpuMemoryUsage:function()
{var bytesPerPixel=4;return this.drawsContent()?this.width()*this.height()*bytesPerPixel:0;},requestSnapshot:function(callback)
{if(!this._target){callback();return;}
var wrappedCallback=InspectorBackend.wrapClientCallback(callback,"LayerTreeAgent.makeSnapshot(): ",WebInspector.PaintProfilerSnapshot.bind(null,this._target));this._target.layerTreeAgent().makeSnapshot(this.id(),wrappedCallback);},_didPaint:function(rect)
{this._lastPaintRect=rect;this._paintCount=this.paintCount()+1;this._image=null;},_reset:function(layerPayload)
{this._node=null;this._children=[];this._parent=null;this._paintCount=0;this._layerPayload=layerPayload;this._image=null;this._scrollRects=this._layerPayload.scrollRects||[];},_matrixFromArray:function(a)
{function toFixed9(x){return x.toFixed(9);}
return new WebKitCSSMatrix("matrix3d("+a.map(toFixed9).join(",")+")");},_calculateTransformToViewport:function(parentTransform)
{var offsetMatrix=new WebKitCSSMatrix().translate(this._layerPayload.offsetX,this._layerPayload.offsetY);var matrix=offsetMatrix;if(this._layerPayload.transform){var transformMatrix=this._matrixFromArray(this._layerPayload.transform);var anchorVector=new WebInspector.Geometry.Vector(this._layerPayload.width*this.anchorPoint()[0],this._layerPayload.height*this.anchorPoint()[1],this.anchorPoint()[2]);var anchorPoint=WebInspector.Geometry.multiplyVectorByMatrixAndNormalize(anchorVector,matrix);var anchorMatrix=new WebKitCSSMatrix().translate(-anchorPoint.x,-anchorPoint.y,-anchorPoint.z);matrix=anchorMatrix.inverse().multiply(transformMatrix.multiply(anchorMatrix.multiply(matrix)));}
matrix=parentTransform.multiply(matrix);return matrix;},_createVertexArrayForRect:function(width,height)
{return[0,0,0,width,0,0,width,height,0,0,height,0];},_calculateQuad:function(parentTransform)
{var matrix=this._calculateTransformToViewport(parentTransform);this._quad=[];var vertices=this._createVertexArrayForRect(this._layerPayload.width,this._layerPayload.height);for(var i=0;i<4;++i){var point=WebInspector.Geometry.multiplyVectorByMatrixAndNormalize(new WebInspector.Geometry.Vector(vertices[i*3],vertices[i*3+1],vertices[i*3+2]),matrix);this._quad.push(point.x,point.y);}
function calculateQuadForLayer(layer)
{layer._calculateQuad(matrix);}
this._children.forEach(calculateQuadForLayer);}}
WebInspector.TracingLayer=function(payload)
{this._reset(payload);}
WebInspector.TracingLayer.prototype={_reset:function(payload)
{this._node=null;this._layerId=String(payload.layer_id);this._offsetX=payload.position[0];this._offsetY=payload.position[1];this._width=payload.bounds.width;this._height=payload.bounds.height;this._children=[];this._parentLayerId=null;this._parent=null;this._quad=payload.layer_quad||[];this._createScrollRects(payload);this._compositingReasons=payload.compositing_reasons||[];this._drawsContent=!!payload.draws_content;this._gpuMemoryUsage=payload.gpu_memory_usage;},id:function()
{return this._layerId;},parentId:function()
{return this._parentLayerId;},parent:function()
{return this._parent;},isRoot:function()
{return!this.parentId();},children:function()
{return this._children;},addChild:function(child)
{if(child._parent)
console.assert(false,"Child already has a parent");this._children.push(child);child._parent=this;child._parentLayerId=this._layerId;},_setNode:function(node)
{this._node=node;},node:function()
{return this._node;},nodeForSelfOrAncestor:function()
{for(var layer=this;layer;layer=layer._parent){if(layer._node)
return layer._node;}
return null;},offsetX:function()
{return this._offsetX;},offsetY:function()
{return this._offsetY;},width:function()
{return this._width;},height:function()
{return this._height;},transform:function()
{return null;},quad:function()
{return this._quad;},anchorPoint:function()
{return[0.5,0.5,0];},invisible:function()
{return false;},paintCount:function()
{return 0;},lastPaintRect:function()
{return null;},scrollRects:function()
{return this._scrollRects;},gpuMemoryUsage:function()
{return this._gpuMemoryUsage;},_scrollRectsFromParams:function(params,type)
{return{rect:{x:params[0],y:params[1],width:params[2],height:params[3]},type:type};},_createScrollRects:function(payload)
{this._scrollRects=[];if(payload.non_fast_scrollable_region)
this._scrollRects.push(this._scrollRectsFromParams(payload.non_fast_scrollable_region,WebInspector.LayerTreeModel.ScrollRectType.NonFastScrollable.name));if(payload.touch_event_handler_region)
this._scrollRects.push(this._scrollRectsFromParams(payload.touch_event_handler_region,WebInspector.LayerTreeModel.ScrollRectType.TouchEventHandler.name));if(payload.wheel_event_handler_region)
this._scrollRects.push(this._scrollRectsFromParams(payload.wheel_event_handler_region,WebInspector.LayerTreeModel.ScrollRectType.WheelEventHandler.name));if(payload.scroll_event_handler_region)
this._scrollRects.push(this._scrollRectsFromParams(payload.scroll_event_handler_region,WebInspector.LayerTreeModel.ScrollRectType.RepaintsOnScroll.name));},requestCompositingReasons:function(callback)
{callback(this._compositingReasons);},drawsContent:function()
{return this._drawsContent;}}
WebInspector.DeferredLayerTree=function(target)
{this._target=target;}
WebInspector.DeferredLayerTree.prototype={resolve:function(callback){},target:function()
{return this._target;}};WebInspector.LayerTreeDispatcher=function(layerTreeModel)
{this._layerTreeModel=layerTreeModel;}
WebInspector.LayerTreeDispatcher.prototype={layerTreeDidChange:function(layers)
{this._layerTreeModel._layerTreeChanged(layers||null);},layerPainted:function(layerId,clipRect)
{this._layerTreeModel._layerPainted(layerId,clipRect);}}
WebInspector.LayerTreeModel.fromTarget=function(target)
{if(!target.hasDOMCapability())
return null;var model=(target.model(WebInspector.LayerTreeModel));if(!model)
model=new WebInspector.LayerTreeModel(target);return model;}},{}],228:[function(require,module,exports){WebInspector.TimelineFrameModel=function(categoryMapper)
{this._categoryMapper=categoryMapper;this.reset();}
WebInspector.TimelineFrameModel._mainFrameMarkers=[WebInspector.TimelineModel.RecordType.ScheduleStyleRecalculation,WebInspector.TimelineModel.RecordType.InvalidateLayout,WebInspector.TimelineModel.RecordType.BeginMainThreadFrame,WebInspector.TimelineModel.RecordType.ScrollLayer];WebInspector.TimelineFrameModel.prototype={frames:function()
{return this._frames;},filteredFrames:function(startTime,endTime)
{function compareStartTime(value,object)
{return value-object.startTime;}
function compareEndTime(value,object)
{return value-object.endTime;}
var frames=this._frames;var firstFrame=frames.lowerBound(startTime,compareEndTime);var lastFrame=frames.lowerBound(endTime,compareStartTime);return frames.slice(firstFrame,lastFrame);},hasRasterTile:function(rasterTask)
{var data=rasterTask.args["tileData"];if(!data)
return false;var frameId=data["sourceFrameNumber"];var frame=frameId&&this._frameById[frameId];if(!frame||!frame.layerTree)
return false;return true;},requestRasterTile:function(rasterTask,callback)
{var target=this._target;if(!target){callback(null,null);return;}
var data=rasterTask.args["tileData"];var frameId=data["sourceFrameNumber"];var frame=frameId&&this._frameById[frameId];if(!frame||!frame.layerTree){callback(null,null);return;}
var tileId=data["tileId"]&&data["tileId"]["id_ref"];var fragments=[];var tile=null;var x0=Infinity;var y0=Infinity;frame.layerTree.resolve(layerTreeResolved);function layerTreeResolved(layerTree)
{tile=tileId&&((layerTree)).tileById("cc::Tile/"+tileId);if(!tile){console.error("Tile "+tileId+" missing in frame "+frameId);callback(null,null);return;}
var fetchPictureFragmentsBarrier=new CallbackBarrier();for(var paint of frame.paints){if(tile.layer_id===paint.layerId())
paint.loadPicture(fetchPictureFragmentsBarrier.createCallback(pictureLoaded));}
fetchPictureFragmentsBarrier.callWhenDone(allPicturesLoaded);}
function segmentsOverlap(a1,a2,b1,b2)
{console.assert(a1<=a2&&b1<=b2,"segments should be specified as ordered pairs");return a2>b1&&a1<b2;}
function rectsOverlap(a,b)
{return segmentsOverlap(a[0],a[0]+a[2],b[0],b[0]+b[2])&&segmentsOverlap(a[1],a[1]+a[3],b[1],b[1]+b[3]);}
function pictureLoaded(rect,picture)
{if(!rect||!picture)
return;if(!rectsOverlap(rect,tile.content_rect))
return;var x=rect[0];var y=rect[1];x0=Math.min(x0,x);y0=Math.min(y0,y);fragments.push({x:x,y:y,picture:picture});}
function allPicturesLoaded()
{if(!fragments.length){callback(null,null);return;}
var rectArray=tile.content_rect;var rect={x:rectArray[0]-x0,y:rectArray[1]-y0,width:rectArray[2],height:rectArray[3]};WebInspector.PaintProfilerSnapshot.loadFromFragments(target,fragments,callback.bind(null,rect));}},reset:function()
{this._minimumRecordTime=Infinity;this._frames=[];this._frameById={};this._lastFrame=null;this._lastLayerTree=null;this._mainFrameCommitted=false;this._mainFrameRequested=false;this._framePendingCommit=null;this._lastBeginFrame=null;this._lastNeedsBeginFrame=null;this._framePendingActivation=null;this._lastTaskBeginTime=null;this._target=null;this._sessionId=null;this._currentTaskTimeByCategory={};},handleBeginFrame:function(startTime)
{if(!this._lastFrame)
this._startFrame(startTime);this._lastBeginFrame=startTime;},handleDrawFrame:function(startTime)
{if(!this._lastFrame){this._startFrame(startTime);return;}
if(this._mainFrameCommitted||!this._mainFrameRequested){if(this._lastNeedsBeginFrame){var idleTimeEnd=this._framePendingActivation?this._framePendingActivation.triggerTime:(this._lastBeginFrame||this._lastNeedsBeginFrame);if(idleTimeEnd>this._lastFrame.startTime){this._lastFrame.idle=true;this._startFrame(idleTimeEnd);if(this._framePendingActivation)
this._commitPendingFrame();this._lastBeginFrame=null;}
this._lastNeedsBeginFrame=null;}
this._startFrame(startTime);}
this._mainFrameCommitted=false;},handleActivateLayerTree:function()
{if(!this._lastFrame)
return;if(this._framePendingActivation&&!this._lastNeedsBeginFrame)
this._commitPendingFrame();},handleRequestMainThreadFrame:function()
{if(!this._lastFrame)
return;this._mainFrameRequested=true;},handleCompositeLayers:function()
{if(!this._framePendingCommit)
return;this._framePendingActivation=this._framePendingCommit;this._framePendingCommit=null;this._mainFrameRequested=false;this._mainFrameCommitted=true;},handleLayerTreeSnapshot:function(layerTree)
{this._lastLayerTree=layerTree;},handleNeedFrameChanged:function(startTime,needsBeginFrame)
{if(needsBeginFrame)
this._lastNeedsBeginFrame=startTime;},_startFrame:function(startTime)
{if(this._lastFrame)
this._flushFrame(this._lastFrame,startTime);this._lastFrame=new WebInspector.TimelineFrame(startTime,startTime-this._minimumRecordTime);},_flushFrame:function(frame,endTime)
{frame._setLayerTree(this._lastLayerTree);frame._setEndTime(endTime);if(this._frames.length&&(frame.startTime!==this._frames.peekLast().endTime||frame.startTime>frame.endTime))
console.assert(false,`Inconsistent frame time for frame ${this._frames.length} (${frame.startTime} - ${frame.endTime})`);this._frames.push(frame);if(typeof frame._mainFrameId==="number")
this._frameById[frame._mainFrameId]=frame;},_commitPendingFrame:function()
{this._lastFrame._addTimeForCategories(this._framePendingActivation.timeByCategory);this._lastFrame.paints=this._framePendingActivation.paints;this._lastFrame._mainFrameId=this._framePendingActivation.mainFrameId;this._framePendingActivation=null;},_findRecordRecursively:function(types,record)
{if(types.indexOf(record.type())>=0)
return record;if(!record.children())
return null;for(var i=0;i<record.children().length;++i){var result=this._findRecordRecursively(types,record.children()[i]);if(result)
return result;}
return null;},addTraceEvents:function(target,events,sessionId)
{this._target=target;this._sessionId=sessionId;if(!events.length)
return;if(events[0].startTime<this._minimumRecordTime)
this._minimumRecordTime=events[0].startTime;for(var i=0;i<events.length;++i)
this._addTraceEvent(events[i]);},_addTraceEvent:function(event)
{var eventNames=WebInspector.TimelineModel.RecordType;if(event.name===eventNames.SetLayerTreeId){var sessionId=event.args["sessionId"]||event.args["data"]["sessionId"];if(this._sessionId===sessionId)
this._layerTreeId=event.args["layerTreeId"]||event.args["data"]["layerTreeId"];}else if(event.name===eventNames.TracingStartedInPage){this._mainThread=event.thread;}else if(event.phase===WebInspector.TracingModel.Phase.SnapshotObject&&event.name===eventNames.LayerTreeHostImplSnapshot&&parseInt(event.id,0)===this._layerTreeId){var snapshot=(event);this.handleLayerTreeSnapshot(new WebInspector.DeferredTracingLayerTree(snapshot,this._target));}else{this._processCompositorEvents(event);if(event.thread===this._mainThread)
this._addMainThreadTraceEvent(event);else if(this._lastFrame&&event.selfTime&&!WebInspector.TracingModel.isTopLevelEvent(event))
this._lastFrame._addTimeForCategory(this._categoryMapper(event),event.selfTime);}},_processCompositorEvents:function(event)
{var eventNames=WebInspector.TimelineModel.RecordType;if(event.args["layerTreeId"]!==this._layerTreeId)
return;var timestamp=event.startTime;if(event.name===eventNames.BeginFrame)
this.handleBeginFrame(timestamp);else if(event.name===eventNames.DrawFrame)
this.handleDrawFrame(timestamp);else if(event.name===eventNames.ActivateLayerTree)
this.handleActivateLayerTree();else if(event.name===eventNames.RequestMainThreadFrame)
this.handleRequestMainThreadFrame();else if(event.name===eventNames.NeedsBeginFrameChanged)
this.handleNeedFrameChanged(timestamp,event.args["data"]&&event.args["data"]["needsBeginFrame"]);},_addMainThreadTraceEvent:function(event)
{var eventNames=WebInspector.TimelineModel.RecordType;var timestamp=event.startTime;var selfTime=event.selfTime||0;if(WebInspector.TracingModel.isTopLevelEvent(event)){this._currentTaskTimeByCategory={};this._lastTaskBeginTime=event.startTime;}
if(!this._framePendingCommit&&WebInspector.TimelineFrameModel._mainFrameMarkers.indexOf(event.name)>=0)
this._framePendingCommit=new WebInspector.PendingFrame(this._lastTaskBeginTime||event.startTime,this._currentTaskTimeByCategory);if(!this._framePendingCommit){this._addTimeForCategory(this._currentTaskTimeByCategory,event);return;}
this._addTimeForCategory(this._framePendingCommit.timeByCategory,event);if(event.name===eventNames.BeginMainThreadFrame&&event.args["data"]&&event.args["data"]["frameId"])
this._framePendingCommit.mainFrameId=event.args["data"]["frameId"];if(event.name===eventNames.Paint&&event.args["data"]["layerId"]&&event.picture&&this._target)
this._framePendingCommit.paints.push(new WebInspector.LayerPaintEvent(event,this._target));if(event.name===eventNames.CompositeLayers&&event.args["layerTreeId"]===this._layerTreeId)
this.handleCompositeLayers();},_addTimeForCategory:function(timeByCategory,event)
{if(!event.selfTime)
return;var categoryName=this._categoryMapper(event);timeByCategory[categoryName]=(timeByCategory[categoryName]||0)+event.selfTime;},}
WebInspector.DeferredTracingLayerTree=function(snapshot,target)
{WebInspector.DeferredLayerTree.call(this,target);this._snapshot=snapshot;}
WebInspector.DeferredTracingLayerTree.prototype={resolve:function(callback)
{this._snapshot.requestObject(onGotObject.bind(this));function onGotObject(result)
{if(!result)
return;var viewport=result["device_viewport_size"];var tiles=result["active_tiles"];var rootLayer=result["active_tree"]["root_layer"];var layers=result["active_tree"]["layers"];var layerTree=new WebInspector.TracingLayerTree(this._target);layerTree.setViewportSize(viewport);layerTree.setTiles(tiles);layerTree.setLayers(rootLayer,layers,callback.bind(null,layerTree));}},__proto__:WebInspector.DeferredLayerTree.prototype};WebInspector.TimelineFrame=function(startTime,startTimeOffset)
{this.startTime=startTime;this.startTimeOffset=startTimeOffset;this.endTime=this.startTime;this.duration=0;this.timeByCategory={};this.cpuTime=0;this.idle=false;this.layerTree=null;this.paints=[];this._mainFrameId=undefined;}
WebInspector.TimelineFrame.prototype={hasWarnings:function()
{var longFrameDurationThresholdMs=22;return!this.idle&&this.duration>longFrameDurationThresholdMs;},_setEndTime:function(endTime)
{this.endTime=endTime;this.duration=this.endTime-this.startTime;},_setLayerTree:function(layerTree)
{this.layerTree=layerTree;},_addTimeForCategories:function(timeByCategory)
{for(var category in timeByCategory)
this._addTimeForCategory(category,timeByCategory[category]);},_addTimeForCategory:function(category,time)
{this.timeByCategory[category]=(this.timeByCategory[category]||0)+time;this.cpuTime+=time;},}
WebInspector.LayerPaintEvent=function(event,target)
{this._event=event;this._target=target;}
WebInspector.LayerPaintEvent.prototype={layerId:function()
{return this._event.args["data"]["layerId"];},event:function()
{return this._event;},loadPicture:function(callback)
{this._event.picture.requestObject(onGotObject);function onGotObject(result)
{if(!result||!result["skp64"]){callback(null,null);return;}
var rect=result["params"]&&result["params"]["layer_rect"];callback(rect,result["skp64"]);}},loadSnapshot:function(callback)
{this.loadPicture(onGotPicture.bind(this));function onGotPicture(rect,picture)
{if(!rect||!picture||!this._target){callback(null,null);return;}
WebInspector.PaintProfilerSnapshot.load(this._target,picture,callback.bind(null,rect));}}};WebInspector.PendingFrame=function(triggerTime,timeByCategory)
{this.timeByCategory=timeByCategory;this.paints=[];this.mainFrameId=undefined;this.triggerTime=triggerTime;}},{}],229:[function(require,module,exports){WebInspector.TimelineIRModel=function()
{this.reset();}
WebInspector.TimelineIRModel.Phases={Idle:"Idle",Response:"Response",Scroll:"Scroll",Fling:"Fling",Drag:"Drag",Animation:"Animation",Uncategorized:"Uncategorized"};WebInspector.TimelineIRModel.InputEvents={Char:"Char",Click:"GestureClick",ContextMenu:"ContextMenu",FlingCancel:"GestureFlingCancel",FlingStart:"GestureFlingStart",ImplSideFling:WebInspector.TimelineModel.RecordType.ImplSideFling,KeyDown:"KeyDown",KeyDownRaw:"RawKeyDown",KeyUp:"KeyUp",LatencyScrollUpdate:"ScrollUpdate",MouseDown:"MouseDown",MouseMove:"MouseMove",MouseUp:"MouseUp",MouseWheel:"MouseWheel",PinchBegin:"GesturePinchBegin",PinchEnd:"GesturePinchEnd",PinchUpdate:"GesturePinchUpdate",ScrollBegin:"GestureScrollBegin",ScrollEnd:"GestureScrollEnd",ScrollUpdate:"GestureScrollUpdate",ScrollUpdateRenderer:"ScrollUpdate",ShowPress:"GestureShowPress",Tap:"GestureTap",TapCancel:"GestureTapCancel",TapDown:"GestureTapDown",TouchCancel:"TouchCancel",TouchEnd:"TouchEnd",TouchMove:"TouchMove",TouchStart:"TouchStart"};WebInspector.TimelineIRModel._mergeThresholdsMs={animation:1,mouse:40,};WebInspector.TimelineIRModel._eventIRPhase=Symbol("eventIRPhase");WebInspector.TimelineIRModel.phaseForEvent=function(event)
{return event[WebInspector.TimelineIRModel._eventIRPhase];}
WebInspector.TimelineIRModel.prototype={populate:function(inputLatencies,animations)
{var eventTypes=WebInspector.TimelineIRModel.InputEvents;var phases=WebInspector.TimelineIRModel.Phases;this.reset();if(!inputLatencies)
return;this._processInputLatencies(inputLatencies);if(animations)
this._processAnimations(animations);var range=new WebInspector.SegmentedRange();range.appendRange(this._drags);range.appendRange(this._cssAnimations);range.appendRange(this._scrolls);range.appendRange(this._responses);this._segments=range.segments();},_processInputLatencies:function(events)
{var eventTypes=WebInspector.TimelineIRModel.InputEvents;var phases=WebInspector.TimelineIRModel.Phases;var thresholdsMs=WebInspector.TimelineIRModel._mergeThresholdsMs;var scrollStart;var flingStart;var touchStart;var firstTouchMove;var mouseWheel;var mouseDown;var mouseMove;for(var i=0;i<events.length;++i){var event=events[i];if(i>0&&events[i].startTime<events[i-1].startTime)
console.assert(false,"Unordered input events");var type=this._inputEventType(event.name);switch(type){case eventTypes.ScrollBegin:this._scrolls.append(this._segmentForEvent(event,phases.Scroll));scrollStart=event;break;case eventTypes.ScrollEnd:if(scrollStart)
this._scrolls.append(this._segmentForEventRange(scrollStart,event,phases.Scroll));else
this._scrolls.append(this._segmentForEvent(event,phases.Scroll));scrollStart=null;break;case eventTypes.ScrollUpdate:touchStart=null;this._scrolls.append(this._segmentForEvent(event,phases.Scroll));break;case eventTypes.FlingStart:if(flingStart){WebInspector.console.error(WebInspector.UIString("Two flings at the same time? %s vs %s",flingStart.startTime,event.startTime));break;}
flingStart=event;break;case eventTypes.FlingCancel:if(!flingStart)
break;this._scrolls.append(this._segmentForEventRange(flingStart,event,phases.Fling));flingStart=null;break;case eventTypes.ImplSideFling:this._scrolls.append(this._segmentForEvent(event,phases.Fling));break;case eventTypes.ShowPress:case eventTypes.Tap:case eventTypes.KeyDown:case eventTypes.KeyDownRaw:case eventTypes.KeyUp:case eventTypes.Char:case eventTypes.Click:case eventTypes.ContextMenu:this._responses.append(this._segmentForEvent(event,phases.Response));break;case eventTypes.TouchStart:if(touchStart){WebInspector.console.error(WebInspector.UIString("Two touches at the same time? %s vs %s",touchStart.startTime,event.startTime));break;}
touchStart=event;event.steps[0][WebInspector.TimelineIRModel._eventIRPhase]=phases.Response;firstTouchMove=null;break;case eventTypes.TouchCancel:touchStart=null;break;case eventTypes.TouchMove:if(firstTouchMove){this._drags.append(this._segmentForEvent(event,phases.Drag));}else if(touchStart){firstTouchMove=event;this._responses.append(this._segmentForEventRange(touchStart,event,phases.Response));}
break;case eventTypes.TouchEnd:touchStart=null;break;case eventTypes.MouseDown:mouseDown=event;mouseMove=null;break;case eventTypes.MouseMove:if(mouseDown&&!mouseMove&&mouseDown.startTime+thresholdsMs.mouse>event.startTime){this._responses.append(this._segmentForEvent(mouseDown,phases.Response));this._responses.append(this._segmentForEvent(event,phases.Response));}else if(mouseDown){this._drags.append(this._segmentForEvent(event,phases.Drag));}
mouseMove=event;break;case eventTypes.MouseUp:this._responses.append(this._segmentForEvent(event,phases.Response));mouseDown=null;break;case eventTypes.MouseWheel:if(mouseWheel&&canMerge(thresholdsMs.mouse,mouseWheel,event))
this._scrolls.append(this._segmentForEventRange(mouseWheel,event,phases.Scroll));else
this._scrolls.append(this._segmentForEvent(event,phases.Scroll));mouseWheel=event;break;}}
function canMerge(threshold,first,second)
{return first.endTime<second.startTime&&second.startTime<first.endTime+threshold;}},_processAnimations:function(events)
{for(var i=0;i<events.length;++i)
this._cssAnimations.append(this._segmentForEvent(events[i],WebInspector.TimelineIRModel.Phases.Animation));},_segmentForEvent:function(event,phase)
{this._setPhaseForEvent(event,phase);return new WebInspector.Segment(event.startTime,event.endTime,phase);},_segmentForEventRange:function(startEvent,endEvent,phase)
{this._setPhaseForEvent(startEvent,phase);this._setPhaseForEvent(endEvent,phase);return new WebInspector.Segment(startEvent.startTime,endEvent.endTime,phase);},_setPhaseForEvent:function(asyncEvent,phase)
{asyncEvent.steps[0][WebInspector.TimelineIRModel._eventIRPhase]=phase;},interactionRecords:function()
{return this._segments;},reset:function()
{var thresholdsMs=WebInspector.TimelineIRModel._mergeThresholdsMs;this._segments=[];this._drags=new WebInspector.SegmentedRange(merge.bind(null,thresholdsMs.mouse));this._cssAnimations=new WebInspector.SegmentedRange(merge.bind(null,thresholdsMs.animation));this._responses=new WebInspector.SegmentedRange(merge.bind(null,0));this._scrolls=new WebInspector.SegmentedRange(merge.bind(null,thresholdsMs.animation));function merge(threshold,first,second)
{return first.end+threshold>=second.begin&&first.data===second.data?first:null;}},_inputEventType:function(eventName)
{var prefix="InputLatency::";if(!eventName.startsWith(prefix)){if(eventName===WebInspector.TimelineIRModel.InputEvents.ImplSideFling)
return(eventName);console.error("Unrecognized input latency event: "+eventName);return null;}
return(eventName.substr(prefix.length));}};},{}],230:[function(require,module,exports){WebInspector.TimelineJSProfileProcessor={};WebInspector.TimelineJSProfileProcessor.generateTracingEventsFromCpuProfile=function(jsProfileModel,thread)
{var idleNode=jsProfileModel.idleNode;var programNode=jsProfileModel.programNode;var gcNode=jsProfileModel.gcNode;var samples=jsProfileModel.samples;var timestamps=jsProfileModel.timestamps;var jsEvents=[];var nodeToStackMap=new Map();nodeToStackMap.set(programNode,[]);for(var i=0;i<samples.length;++i){var node=jsProfileModel.nodeByIndex(i);if(!node){console.error(`Node with unknown id ${samples[i]} at index ${i}`);continue;}
if(node===gcNode||node===idleNode)
continue;var callFrames=nodeToStackMap.get(node);if(!callFrames){callFrames=(new Array(node.depth+1));nodeToStackMap.set(node,callFrames);for(var j=0;node.parent;node=node.parent)
callFrames[j++]=(node);}
var jsSampleEvent=new WebInspector.TracingModel.Event(WebInspector.TracingModel.DevToolsTimelineEventCategory,WebInspector.TimelineModel.RecordType.JSSample,WebInspector.TracingModel.Phase.Instant,timestamps[i],thread);jsSampleEvent.args["data"]={stackTrace:callFrames};jsEvents.push(jsSampleEvent);}
return jsEvents;}
WebInspector.TimelineJSProfileProcessor.generateJSFrameEvents=function(events)
{function equalFrames(frame1,frame2)
{return frame1.scriptId===frame2.scriptId&&frame1.functionName===frame2.functionName;}
function eventEndTime(e)
{return e.endTime||e.startTime;}
function isJSInvocationEvent(e)
{switch(e.name){case WebInspector.TimelineModel.RecordType.RunMicrotasks:case WebInspector.TimelineModel.RecordType.FunctionCall:case WebInspector.TimelineModel.RecordType.EvaluateScript:return true;}
return false;}
var jsFrameEvents=[];var jsFramesStack=[];var lockedJsStackDepth=[];var ordinal=0;var filterNativeFunctions=!WebInspector.moduleSetting("showNativeFunctionsInJSProfile").get();function onStartEvent(e)
{e.ordinal=++ordinal;extractStackTrace(e);lockedJsStackDepth.push(jsFramesStack.length);}
function onInstantEvent(e,parent)
{e.ordinal=++ordinal;if(parent&&isJSInvocationEvent(parent))
extractStackTrace(e);}
function onEndEvent(e)
{truncateJSStack(lockedJsStackDepth.pop(),e.endTime);}
function truncateJSStack(depth,time)
{if(lockedJsStackDepth.length){var lockedDepth=lockedJsStackDepth.peekLast();if(depth<lockedDepth){console.error("Child stack is shallower ("+depth+") than the parent stack ("+lockedDepth+") at "+time);depth=lockedDepth;}}
if(jsFramesStack.length<depth){console.error("Trying to truncate higher than the current stack size at "+time);depth=jsFramesStack.length;}
for(var k=0;k<jsFramesStack.length;++k)
jsFramesStack[k].setEndTime(time);jsFramesStack.length=depth;}
function filterStackFrames(stack)
{for(var i=0,j=0;i<stack.length;++i){var url=stack[i].url;if(url&&url.startsWith("native "))
continue;stack[j++]=stack[i];}
stack.length=j;}
function extractStackTrace(e)
{var recordTypes=WebInspector.TimelineModel.RecordType;var callFrames;if(e.name===recordTypes.JSSample){var eventData=e.args["data"]||e.args["beginData"];callFrames=(eventData&&eventData["stackTrace"]);}else{callFrames=(jsFramesStack.map(frameEvent=>frameEvent.args["data"]).reverse());}
if(filterNativeFunctions)
filterStackFrames(callFrames);var endTime=eventEndTime(e);var numFrames=callFrames.length;var minFrames=Math.min(numFrames,jsFramesStack.length);var i;for(i=lockedJsStackDepth.peekLast()||0;i<minFrames;++i){var newFrame=callFrames[numFrames-1-i];var oldFrame=jsFramesStack[i].args["data"];if(!equalFrames(newFrame,oldFrame))
break;jsFramesStack[i].setEndTime(Math.max(jsFramesStack[i].endTime,endTime));}
truncateJSStack(i,e.startTime);for(;i<numFrames;++i){var frame=callFrames[numFrames-1-i];var jsFrameEvent=new WebInspector.TracingModel.Event(WebInspector.TracingModel.DevToolsTimelineEventCategory,recordTypes.JSFrame,WebInspector.TracingModel.Phase.Complete,e.startTime,e.thread);jsFrameEvent.ordinal=e.ordinal;jsFrameEvent.addArgs({data:frame});jsFrameEvent.setEndTime(endTime);jsFramesStack.push(jsFrameEvent);jsFrameEvents.push(jsFrameEvent);}}
function findFirstTopLevelEvent(events)
{for(var i=0;i<events.length;++i){if(WebInspector.TracingModel.isTopLevelEvent(events[i]))
return events[i];}
return null;}
var firstTopLevelEvent=findFirstTopLevelEvent(events);if(firstTopLevelEvent)
WebInspector.TimelineModel.forEachEvent(events,onStartEvent,onEndEvent,onInstantEvent,firstTopLevelEvent.startTime);return jsFrameEvents;}
WebInspector.TimelineJSProfileProcessor.CodeMap=function()
{this._banks=new Map();}
WebInspector.TimelineJSProfileProcessor.CodeMap.Entry=function(address,size,callFrame)
{this.address=address;this.size=size;this.callFrame=callFrame;}
WebInspector.TimelineJSProfileProcessor.CodeMap.comparator=function(address,entry)
{return address-entry.address;}
WebInspector.TimelineJSProfileProcessor.CodeMap.prototype={addEntry:function(addressHex,size,callFrame)
{var entry=new WebInspector.TimelineJSProfileProcessor.CodeMap.Entry(this._getAddress(addressHex),size,callFrame);this._addEntry(addressHex,entry);},moveEntry:function(oldAddressHex,newAddressHex,size)
{var entry=this._getBank(oldAddressHex).removeEntry(this._getAddress(oldAddressHex));if(!entry){console.error("Entry at address "+oldAddressHex+" not found");return;}
entry.address=this._getAddress(newAddressHex);entry.size=size;this._addEntry(newAddressHex,entry);},lookupEntry:function(addressHex)
{return this._getBank(addressHex).lookupEntry(this._getAddress(addressHex));},_addEntry:function(addressHex,entry)
{this._getBank(addressHex).addEntry(entry);},_getBank:function(addressHex)
{addressHex=addressHex.slice(2);var bankSizeHexDigits=13;var maxHexDigits=16;var bankName=addressHex.slice(-maxHexDigits,-bankSizeHexDigits);var bank=this._banks.get(bankName);if(!bank){bank=new WebInspector.TimelineJSProfileProcessor.CodeMap.Bank();this._banks.set(bankName,bank);}
return bank;},_getAddress:function(addressHex)
{var bankSizeHexDigits=13;addressHex=addressHex.slice(2);return parseInt(addressHex.slice(-bankSizeHexDigits),16);}}
WebInspector.TimelineJSProfileProcessor.CodeMap.Bank=function()
{this._entries=[];}
WebInspector.TimelineJSProfileProcessor.CodeMap.Bank.prototype={removeEntry:function(address)
{var index=this._entries.lowerBound(address,WebInspector.TimelineJSProfileProcessor.CodeMap.comparator);var entry=this._entries[index];if(!entry||entry.address!==address)
return null;this._entries.splice(index,1);return entry;},lookupEntry:function(address)
{var index=this._entries.upperBound(address,WebInspector.TimelineJSProfileProcessor.CodeMap.comparator)-1;var entry=this._entries[index];return entry&&address<entry.address+entry.size?entry.callFrame:null;},addEntry:function(newEntry)
{var endAddress=newEntry.address+newEntry.size;var lastIndex=this._entries.lowerBound(endAddress,WebInspector.TimelineJSProfileProcessor.CodeMap.comparator);var index;for(index=lastIndex-1;index>=0;--index){var entry=this._entries[index];var entryEndAddress=entry.address+entry.size;if(entryEndAddress<=newEntry.address)
break;}
++index;this._entries.splice(index,lastIndex-index,newEntry);}}
WebInspector.TimelineJSProfileProcessor._buildCallFrame=function(name,scriptId)
{function createFrame(functionName,url,scriptId,line,column,isNative)
{return({"functionName":functionName,"url":url||"","scriptId":scriptId||"0","lineNumber":line||0,"columnNumber":column||0,"isNative":isNative||false});}
var rePrefix=/^(\w*:)?[*~]?(.*)$/m;var tokens=rePrefix.exec(name);var prefix=tokens[1];var body=tokens[2];var rawName;var rawUrl;if(prefix==="Script:"){rawName="";rawUrl=body;}else{var spacePos=body.lastIndexOf(" ");rawName=spacePos!==-1?body.substr(0,spacePos):body;rawUrl=spacePos!==-1?body.substr(spacePos+1):"";}
var nativeSuffix=" native";var isNative=rawName.endsWith(nativeSuffix);var functionName=isNative?rawName.slice(0,-nativeSuffix.length):rawName;var urlData=WebInspector.ParsedURL.splitLineAndColumn(rawUrl);var url=urlData.url||"";var line=urlData.lineNumber||0;var column=urlData.columnNumber||0;return createFrame(functionName,url,String(scriptId),line,column,isNative);}
WebInspector.TimelineJSProfileProcessor.processRawV8Samples=function(events)
{var missingAddesses=new Set();function convertRawFrame(address)
{var entry=codeMap.lookupEntry(address);if(entry)
return entry.isNative?null:entry;if(!missingAddesses.has(address)){missingAddesses.add(address);console.error("Address "+address+" has missing code entry");}
return null;}
var recordTypes=WebInspector.TimelineModel.RecordType;var samples=[];var codeMap=new WebInspector.TimelineJSProfileProcessor.CodeMap();for(var i=0;i<events.length;++i){var e=events[i];var data=e.args["data"];switch(e.name){case recordTypes.JitCodeAdded:var frame=WebInspector.TimelineJSProfileProcessor._buildCallFrame(data["name"],data["script_id"]);codeMap.addEntry(data["code_start"],data["code_len"],frame);break;case recordTypes.JitCodeMoved:codeMap.moveEntry(data["code_start"],data["new_code_start"],data["code_len"]);break;case recordTypes.V8Sample:var rawStack=data["stack"];if(data["vm_state"]==="js"&&!rawStack.length)
break;var stack=rawStack.map(convertRawFrame);stack.remove(null);var sampleEvent=new WebInspector.TracingModel.Event(WebInspector.TracingModel.DevToolsTimelineEventCategory,WebInspector.TimelineModel.RecordType.JSSample,WebInspector.TracingModel.Phase.Instant,e.startTime,e.thread);sampleEvent.ordinal=e.ordinal;sampleEvent.args={"data":{"stackTrace":stack}};samples.push(sampleEvent);break;}}
return samples;}},{}],231:[function(require,module,exports){WebInspector.TimelineModel=function(eventFilter)
{this._eventFilter=eventFilter;this.reset();}
WebInspector.TimelineModel.RecordType={Task:"Task",Program:"Program",EventDispatch:"EventDispatch",GPUTask:"GPUTask",Animation:"Animation",RequestMainThreadFrame:"RequestMainThreadFrame",BeginFrame:"BeginFrame",NeedsBeginFrameChanged:"NeedsBeginFrameChanged",BeginMainThreadFrame:"BeginMainThreadFrame",ActivateLayerTree:"ActivateLayerTree",DrawFrame:"DrawFrame",HitTest:"HitTest",ScheduleStyleRecalculation:"ScheduleStyleRecalculation",RecalculateStyles:"RecalculateStyles",UpdateLayoutTree:"UpdateLayoutTree",InvalidateLayout:"InvalidateLayout",Layout:"Layout",UpdateLayer:"UpdateLayer",UpdateLayerTree:"UpdateLayerTree",PaintSetup:"PaintSetup",Paint:"Paint",PaintImage:"PaintImage",Rasterize:"Rasterize",RasterTask:"RasterTask",ScrollLayer:"ScrollLayer",CompositeLayers:"CompositeLayers",ScheduleStyleInvalidationTracking:"ScheduleStyleInvalidationTracking",StyleRecalcInvalidationTracking:"StyleRecalcInvalidationTracking",StyleInvalidatorInvalidationTracking:"StyleInvalidatorInvalidationTracking",LayoutInvalidationTracking:"LayoutInvalidationTracking",LayerInvalidationTracking:"LayerInvalidationTracking",PaintInvalidationTracking:"PaintInvalidationTracking",ScrollInvalidationTracking:"ScrollInvalidationTracking",ParseHTML:"ParseHTML",ParseAuthorStyleSheet:"ParseAuthorStyleSheet",TimerInstall:"TimerInstall",TimerRemove:"TimerRemove",TimerFire:"TimerFire",XHRReadyStateChange:"XHRReadyStateChange",XHRLoad:"XHRLoad",CompileScript:"v8.compile",EvaluateScript:"EvaluateScript",CommitLoad:"CommitLoad",MarkLoad:"MarkLoad",MarkDOMContent:"MarkDOMContent",MarkFirstPaint:"MarkFirstPaint",TimeStamp:"TimeStamp",ConsoleTime:"ConsoleTime",UserTiming:"UserTiming",ResourceSendRequest:"ResourceSendRequest",ResourceReceiveResponse:"ResourceReceiveResponse",ResourceReceivedData:"ResourceReceivedData",ResourceFinish:"ResourceFinish",RunMicrotasks:"RunMicrotasks",FunctionCall:"FunctionCall",GCEvent:"GCEvent",MajorGC:"MajorGC",MinorGC:"MinorGC",JSFrame:"JSFrame",JSSample:"JSSample",V8Sample:"V8Sample",JitCodeAdded:"JitCodeAdded",JitCodeMoved:"JitCodeMoved",ParseScriptOnBackground:"v8.parseOnBackground",UpdateCounters:"UpdateCounters",RequestAnimationFrame:"RequestAnimationFrame",CancelAnimationFrame:"CancelAnimationFrame",FireAnimationFrame:"FireAnimationFrame",RequestIdleCallback:"RequestIdleCallback",CancelIdleCallback:"CancelIdleCallback",FireIdleCallback:"FireIdleCallback",WebSocketCreate:"WebSocketCreate",WebSocketSendHandshakeRequest:"WebSocketSendHandshakeRequest",WebSocketReceiveHandshakeResponse:"WebSocketReceiveHandshakeResponse",WebSocketDestroy:"WebSocketDestroy",EmbedderCallback:"EmbedderCallback",SetLayerTreeId:"SetLayerTreeId",TracingStartedInPage:"TracingStartedInPage",TracingSessionIdForWorker:"TracingSessionIdForWorker",DecodeImage:"Decode Image",ResizeImage:"Resize Image",DrawLazyPixelRef:"Draw LazyPixelRef",DecodeLazyPixelRef:"Decode LazyPixelRef",LazyPixelRef:"LazyPixelRef",LayerTreeHostImplSnapshot:"cc::LayerTreeHostImpl",PictureSnapshot:"cc::Picture",DisplayItemListSnapshot:"cc::DisplayItemList",LatencyInfo:"LatencyInfo",LatencyInfoFlow:"LatencyInfo.Flow",InputLatencyMouseMove:"InputLatency::MouseMove",InputLatencyMouseWheel:"InputLatency::MouseWheel",ImplSideFling:"InputHandlerProxy::HandleGestureFling::started",GCIdleLazySweep:"ThreadState::performIdleLazySweep",GCCompleteSweep:"ThreadState::completeSweep",GCCollectGarbage:"BlinkGCMarking",CpuProfile:"CpuProfile"}
WebInspector.TimelineModel.Category={Console:"blink.console",UserTiming:"blink.user_timing",LatencyInfo:"latencyInfo"};WebInspector.TimelineModel.WarningType={ForcedStyle:"ForcedStyle",ForcedLayout:"ForcedLayout",IdleDeadlineExceeded:"IdleDeadlineExceeded",V8Deopt:"V8Deopt"}
WebInspector.TimelineModel.MainThreadName="main";WebInspector.TimelineModel.WorkerThreadName="DedicatedWorker Thread";WebInspector.TimelineModel.RendererMainThreadName="CrRendererMain";WebInspector.TimelineModel.AsyncEventGroup={animation:Symbol("animation"),console:Symbol("console"),userTiming:Symbol("userTiming"),input:Symbol("input")};WebInspector.TimelineModel.forEachEvent=function(events,onStartEvent,onEndEvent,onInstantEvent,startTime,endTime)
{startTime=startTime||0;endTime=endTime||Infinity;var stack=[];for(var i=0;i<events.length;++i){var e=events[i];if((e.endTime||e.startTime)<startTime)
continue;if(e.startTime>=endTime)
break;if(WebInspector.TracingModel.isAsyncPhase(e.phase)||WebInspector.TracingModel.isFlowPhase(e.phase))
continue;while(stack.length&&stack.peekLast().endTime<=e.startTime)
onEndEvent(stack.pop());if(e.duration){onStartEvent(e);stack.push(e);}else{onInstantEvent&&onInstantEvent(e,stack.peekLast()||null);}}
while(stack.length)
onEndEvent(stack.pop());}
WebInspector.TimelineModel.DevToolsMetadataEvent={TracingStartedInBrowser:"TracingStartedInBrowser",TracingStartedInPage:"TracingStartedInPage",TracingSessionIdForWorker:"TracingSessionIdForWorker",};WebInspector.TimelineModel.VirtualThread=function(name)
{this.name=name;this.events=[];this.asyncEventsByGroup=new Map();}
WebInspector.TimelineModel.VirtualThread.prototype={isWorker:function()
{return this.name===WebInspector.TimelineModel.WorkerThreadName;}}
WebInspector.TimelineModel.Record=function(traceEvent)
{this._event=traceEvent;this._children=[];}
WebInspector.TimelineModel.Record._compareStartTime=function(a,b)
{return a.startTime()<=b.startTime()?-1:1;}
WebInspector.TimelineModel.Record.prototype={target:function()
{var threadName=this._event.thread.name();return threadName===WebInspector.TimelineModel.RendererMainThreadName?WebInspector.targetManager.targets()[0]||null:null;},children:function()
{return this._children;},startTime:function()
{return this._event.startTime;},endTime:function()
{return this._event.endTime||this._event.startTime;},thread:function()
{if(this._event.thread.name()===WebInspector.TimelineModel.RendererMainThreadName)
return WebInspector.TimelineModel.MainThreadName;return this._event.thread.name();},type:function()
{return WebInspector.TimelineModel._eventType(this._event);},getUserObject:function(key)
{if(key==="TimelineUIUtils::preview-element")
return this._event.previewElement;throw new Error("Unexpected key: "+key);},setUserObject:function(key,value)
{if(key!=="TimelineUIUtils::preview-element")
throw new Error("Unexpected key: "+key);this._event.previewElement=(value);},traceEvent:function()
{return this._event;},_addChild:function(child)
{this._children.push(child);child.parent=this;}}
WebInspector.TimelineModel.MetadataEvents;WebInspector.TimelineModel._eventType=function(event)
{if(event.hasCategory(WebInspector.TimelineModel.Category.Console))
return WebInspector.TimelineModel.RecordType.ConsoleTime;if(event.hasCategory(WebInspector.TimelineModel.Category.UserTiming))
return WebInspector.TimelineModel.RecordType.UserTiming;if(event.hasCategory(WebInspector.TimelineModel.Category.LatencyInfo))
return WebInspector.TimelineModel.RecordType.LatencyInfo;return(event.name);}
WebInspector.TimelineModel.prototype={forAllRecords:function(preOrderCallback,postOrderCallback)
{function processRecords(records,depth)
{for(var i=0;i<records.length;++i){var record=records[i];if(preOrderCallback&&preOrderCallback(record,depth))
return true;if(processRecords(record.children(),depth+1))
return true;if(postOrderCallback&&postOrderCallback(record,depth))
return true;}
return false;}
return processRecords(this._records,0);},forAllFilteredRecords:function(filters,callback)
{function processRecord(record,depth)
{var visible=WebInspector.TimelineModel.isVisible(filters,record.traceEvent());if(visible&&callback(record,depth))
return true;for(var i=0;i<record.children().length;++i){if(processRecord.call(this,record.children()[i],visible?depth+1:depth))
return true;}
return false;}
for(var i=0;i<this._records.length;++i)
processRecord.call(this,this._records[i],0);},records:function()
{return this._records;},cpuProfiles:function()
{return this._cpuProfiles;},sessionId:function()
{return this._sessionId;},targetByEvent:function(event)
{var workerId=this._workerIdByThread.get(event.thread);var mainTarget=WebInspector.targetManager.mainTarget();return workerId?mainTarget.workerManager.targetByWorkerId(workerId):mainTarget;},setEvents:function(tracingModel,produceTraceStartedInPage)
{this.reset();this._resetProcessingState();this._minimumRecordTime=tracingModel.minimumRecordTime();this._maximumRecordTime=tracingModel.maximumRecordTime();var metadataEvents=this._processMetadataEvents(tracingModel,!!produceTraceStartedInPage);if(Runtime.experiments.isEnabled("timelineShowAllProcesses")){var lastPageMetaEvent=metadataEvents.page.peekLast();for(var process of tracingModel.sortedProcesses()){for(var thread of process.sortedThreads())
this._processThreadEvents(0,Infinity,thread,thread===lastPageMetaEvent.thread);}}else{var startTime=0;for(var i=0,length=metadataEvents.page.length;i<length;i++){var metaEvent=metadataEvents.page[i];var process=metaEvent.thread.process();var endTime=i+1<length?metadataEvents.page[i+1].startTime:Infinity;this._currentPage=metaEvent.args["data"]&&metaEvent.args["data"]["page"];for(var thread of process.sortedThreads()){if(thread.name()===WebInspector.TimelineModel.WorkerThreadName){var workerMetaEvent=metadataEvents.workers.find(e=>e.args["data"]["workerThreadId"]===thread.id());if(!workerMetaEvent)
continue;var workerId=workerMetaEvent.args["data"]["workerId"];if(workerId)
this._workerIdByThread.set(thread,workerId);}
this._processThreadEvents(startTime,endTime,thread,thread===metaEvent.thread);}
startTime=endTime;}}
this._inspectedTargetEvents.sort(WebInspector.TracingModel.Event.compareStartTime);this._processBrowserEvents(tracingModel);this._buildTimelineRecords();this._buildGPUEvents(tracingModel);this._insertFirstPaintEvent();this._resetProcessingState();},_processMetadataEvents:function(tracingModel,produceTraceStartedInPage)
{var metadataEvents=tracingModel.devToolsMetadataEvents();var pageDevToolsMetadataEvents=[];var workersDevToolsMetadataEvents=[];for(var event of metadataEvents){if(event.name===WebInspector.TimelineModel.DevToolsMetadataEvent.TracingStartedInPage){pageDevToolsMetadataEvents.push(event);}else if(event.name===WebInspector.TimelineModel.DevToolsMetadataEvent.TracingSessionIdForWorker){workersDevToolsMetadataEvents.push(event);}else if(event.name===WebInspector.TimelineModel.DevToolsMetadataEvent.TracingStartedInBrowser){console.assert(!this._mainFrameNodeId,"Multiple sessions in trace");this._mainFrameNodeId=event.args["frameTreeNodeId"];}}
if(!pageDevToolsMetadataEvents.length){var pageMetaEvent=produceTraceStartedInPage?this._makeMockPageMetadataEvent(tracingModel):null;if(!pageMetaEvent){console.error(WebInspector.TimelineModel.DevToolsMetadataEvent.TracingStartedInPage+" event not found.");return{page:[],workers:[]};}
pageDevToolsMetadataEvents.push(pageMetaEvent);}
var sessionId=pageDevToolsMetadataEvents[0].args["sessionId"]||pageDevToolsMetadataEvents[0].args["data"]["sessionId"];this._sessionId=sessionId;var mismatchingIds=new Set();function checkSessionId(event)
{var args=event.args;if(args["data"])
args=args["data"];var id=args["sessionId"];if(id===sessionId)
return true;mismatchingIds.add(id);return false;}
var result={page:pageDevToolsMetadataEvents.filter(checkSessionId).sort(WebInspector.TracingModel.Event.compareStartTime),workers:workersDevToolsMetadataEvents.filter(checkSessionId).sort(WebInspector.TracingModel.Event.compareStartTime)};if(mismatchingIds.size)
WebInspector.console.error("Timeline recording was started in more than one page simultaneously. Session id mismatch: "+this._sessionId+" and "+mismatchingIds.valuesArray()+".");return result;},_makeMockPageMetadataEvent:function(tracingModel)
{var rendererMainThreadName=WebInspector.TimelineModel.RendererMainThreadName;var process=tracingModel.sortedProcesses().filter(function(p){return p.threadByName(rendererMainThreadName);})[0];var thread=process&&process.threadByName(rendererMainThreadName);if(!thread)
return null;var pageMetaEvent=new WebInspector.TracingModel.Event(WebInspector.TracingModel.DevToolsMetadataEventCategory,WebInspector.TimelineModel.DevToolsMetadataEvent.TracingStartedInPage,WebInspector.TracingModel.Phase.Metadata,tracingModel.minimumRecordTime(),thread);pageMetaEvent.addArgs({"data":{"sessionId":"mockSessionId"}});return pageMetaEvent;},_insertFirstPaintEvent:function()
{if(!this._firstCompositeLayers)
return;var recordTypes=WebInspector.TimelineModel.RecordType;var i=this._inspectedTargetEvents.lowerBound(this._firstCompositeLayers,WebInspector.TracingModel.Event.compareStartTime);for(;i<this._inspectedTargetEvents.length&&this._inspectedTargetEvents[i].name!==recordTypes.DrawFrame;++i){}
if(i>=this._inspectedTargetEvents.length)
return;var drawFrameEvent=this._inspectedTargetEvents[i];var firstPaintEvent=new WebInspector.TracingModel.Event(drawFrameEvent.categoriesString,recordTypes.MarkFirstPaint,WebInspector.TracingModel.Phase.Instant,drawFrameEvent.startTime,drawFrameEvent.thread);this._mainThreadEvents.splice(this._mainThreadEvents.lowerBound(firstPaintEvent,WebInspector.TracingModel.Event.compareStartTime),0,firstPaintEvent);var firstPaintRecord=new WebInspector.TimelineModel.Record(firstPaintEvent);this._eventDividerRecords.splice(this._eventDividerRecords.lowerBound(firstPaintRecord,WebInspector.TimelineModel.Record._compareStartTime),0,firstPaintRecord);},_processBrowserEvents:function(tracingModel)
{var browserMain=WebInspector.TracingModel.browserMainThread(tracingModel);if(!browserMain)
return;browserMain.events().forEach(this._processBrowserEvent,this);var asyncEventsByGroup=new Map();this._processAsyncEvents(asyncEventsByGroup,browserMain.asyncEvents());this._mergeAsyncEvents(this._mainThreadAsyncEventsByGroup,asyncEventsByGroup);},_buildTimelineRecords:function()
{var topLevelRecords=this._buildTimelineRecordsForThread(this.mainThreadEvents());for(var i=0;i<topLevelRecords.length;i++){var record=topLevelRecords[i];if(WebInspector.TracingModel.isTopLevelEvent(record.traceEvent()))
this._mainThreadTasks.push(record);}
function processVirtualThreadEvents(virtualThread)
{var threadRecords=this._buildTimelineRecordsForThread(virtualThread.events);topLevelRecords=topLevelRecords.mergeOrdered(threadRecords,WebInspector.TimelineModel.Record._compareStartTime);}
this.virtualThreads().forEach(processVirtualThreadEvents.bind(this));this._records=topLevelRecords;},_buildGPUEvents:function(tracingModel)
{var thread=tracingModel.threadByName("GPU Process","CrGpuMain");if(!thread)
return;var gpuEventName=WebInspector.TimelineModel.RecordType.GPUTask;this._gpuEvents=thread.events().filter(event=>event.name===gpuEventName);},_buildTimelineRecordsForThread:function(threadEvents)
{var recordStack=[];var topLevelRecords=[];for(var i=0,size=threadEvents.length;i<size;++i){var event=threadEvents[i];for(var top=recordStack.peekLast();top&&top._event.endTime<=event.startTime;top=recordStack.peekLast())
recordStack.pop();if(event.phase===WebInspector.TracingModel.Phase.AsyncEnd||event.phase===WebInspector.TracingModel.Phase.NestableAsyncEnd)
continue;var parentRecord=recordStack.peekLast();if(WebInspector.TracingModel.isAsyncBeginPhase(event.phase)&&parentRecord&&event.endTime>parentRecord._event.endTime)
continue;var record=new WebInspector.TimelineModel.Record(event);if(WebInspector.TimelineModel.isMarkerEvent(event))
this._eventDividerRecords.push(record);if(!this._eventFilter.accept(event)&&!WebInspector.TracingModel.isTopLevelEvent(event))
continue;if(parentRecord)
parentRecord._addChild(record);else
topLevelRecords.push(record);if(event.endTime)
recordStack.push(record);}
return topLevelRecords;},_resetProcessingState:function()
{this._asyncEventTracker=new WebInspector.TimelineAsyncEventTracker();this._invalidationTracker=new WebInspector.InvalidationTracker();this._layoutInvalidate={};this._lastScheduleStyleRecalculation={};this._paintImageEventByPixelRefId={};this._lastPaintForLayer={};this._lastRecalculateStylesEvent=null;this._currentScriptEvent=null;this._eventStack=[];this._hadCommitLoad=false;this._firstCompositeLayers=null;this._knownInputEvents=new Set();this._currentPage=null;},_processThreadEvents:function(startTime,endTime,thread,isMainThread)
{var events=thread.events();var asyncEvents=thread.asyncEvents();var jsSamples;if(Runtime.experiments.isEnabled("timelineTracingJSProfile")){jsSamples=WebInspector.TimelineJSProfileProcessor.processRawV8Samples(events);}else{var cpuProfileEvent=events.peekLast();if(cpuProfileEvent&&cpuProfileEvent.name===WebInspector.TimelineModel.RecordType.CpuProfile){var cpuProfile=cpuProfileEvent.args["data"]["cpuProfile"];if(cpuProfile){var jsProfileModel=new WebInspector.CPUProfileDataModel(cpuProfile);this._cpuProfiles.push(jsProfileModel);jsSamples=WebInspector.TimelineJSProfileProcessor.generateTracingEventsFromCpuProfile(jsProfileModel,thread);}}}
if(jsSamples&&jsSamples.length)
events=events.mergeOrdered(jsSamples,WebInspector.TracingModel.Event.orderedCompareStartTime);if(jsSamples||events.some(function(e){return e.name===WebInspector.TimelineModel.RecordType.JSSample;})){var jsFrameEvents=WebInspector.TimelineJSProfileProcessor.generateJSFrameEvents(events);if(jsFrameEvents&&jsFrameEvents.length)
events=jsFrameEvents.mergeOrdered(events,WebInspector.TracingModel.Event.orderedCompareStartTime);}
var threadEvents;var threadAsyncEventsByGroup;if(isMainThread){threadEvents=this._mainThreadEvents;threadAsyncEventsByGroup=this._mainThreadAsyncEventsByGroup;}else{var virtualThread=new WebInspector.TimelineModel.VirtualThread(thread.name());this._virtualThreads.push(virtualThread);threadEvents=virtualThread.events;threadAsyncEventsByGroup=virtualThread.asyncEventsByGroup;}
this._eventStack=[];var i=events.lowerBound(startTime,function(time,event){return time-event.startTime});var length=events.length;for(;i<length;i++){var event=events[i];if(endTime&&event.startTime>=endTime)
break;if(!this._processEvent(event))
continue;threadEvents.push(event);this._inspectedTargetEvents.push(event);}
this._processAsyncEvents(threadAsyncEventsByGroup,asyncEvents,startTime,endTime);if(thread.name()==="Compositor"){this._mergeAsyncEvents(this._mainThreadAsyncEventsByGroup,threadAsyncEventsByGroup);threadAsyncEventsByGroup.clear();}},_processAsyncEvents:function(asyncEventsByGroup,asyncEvents,startTime,endTime)
{var i=startTime?asyncEvents.lowerBound(startTime,function(time,asyncEvent){return time-asyncEvent.startTime}):0;for(;i<asyncEvents.length;++i){var asyncEvent=asyncEvents[i];if(endTime&&asyncEvent.startTime>=endTime)
break;var asyncGroup=this._processAsyncEvent(asyncEvent);if(!asyncGroup)
continue;var groupAsyncEvents=asyncEventsByGroup.get(asyncGroup);if(!groupAsyncEvents){groupAsyncEvents=[];asyncEventsByGroup.set(asyncGroup,groupAsyncEvents);}
groupAsyncEvents.push(asyncEvent);}},_processEvent:function(event)
{var eventStack=this._eventStack;while(eventStack.length&&eventStack.peekLast().endTime<=event.startTime)
eventStack.pop();var recordTypes=WebInspector.TimelineModel.RecordType;if(this._currentScriptEvent&&event.startTime>this._currentScriptEvent.endTime)
this._currentScriptEvent=null;var eventData=event.args["data"]||event.args["beginData"]||{};if(eventData["stackTrace"])
event.stackTrace=eventData["stackTrace"];if(event.stackTrace&&event.name!==recordTypes.JSSample){for(var i=0;i<event.stackTrace.length;++i){--event.stackTrace[i].lineNumber;--event.stackTrace[i].columnNumber;}}
if(eventStack.length&&eventStack.peekLast().name===recordTypes.EventDispatch)
eventStack.peekLast().hasChildren=true;this._asyncEventTracker.processEvent(event);if(event.initiator&&event.initiator.url)
event.url=event.initiator.url;switch(event.name){case recordTypes.ResourceSendRequest:case recordTypes.WebSocketCreate:event.url=eventData["url"];event.initiator=eventStack.peekLast()||null;break;case recordTypes.ScheduleStyleRecalculation:this._lastScheduleStyleRecalculation[eventData["frame"]]=event;break;case recordTypes.UpdateLayoutTree:case recordTypes.RecalculateStyles:this._invalidationTracker.didRecalcStyle(event);if(event.args["beginData"])
event.initiator=this._lastScheduleStyleRecalculation[event.args["beginData"]["frame"]];this._lastRecalculateStylesEvent=event;if(this._currentScriptEvent)
event.warning=WebInspector.TimelineModel.WarningType.ForcedStyle;break;case recordTypes.ScheduleStyleInvalidationTracking:case recordTypes.StyleRecalcInvalidationTracking:case recordTypes.StyleInvalidatorInvalidationTracking:case recordTypes.LayoutInvalidationTracking:case recordTypes.LayerInvalidationTracking:case recordTypes.PaintInvalidationTracking:case recordTypes.ScrollInvalidationTracking:this._invalidationTracker.addInvalidation(new WebInspector.InvalidationTrackingEvent(event));break;case recordTypes.InvalidateLayout:var layoutInitator=event;var frameId=eventData["frame"];if(!this._layoutInvalidate[frameId]&&this._lastRecalculateStylesEvent&&this._lastRecalculateStylesEvent.endTime>event.startTime)
layoutInitator=this._lastRecalculateStylesEvent.initiator;this._layoutInvalidate[frameId]=layoutInitator;break;case recordTypes.Layout:this._invalidationTracker.didLayout(event);var frameId=event.args["beginData"]["frame"];event.initiator=this._layoutInvalidate[frameId];if(event.args["endData"]){event.backendNodeId=event.args["endData"]["rootNode"];event.highlightQuad=event.args["endData"]["root"];}
this._layoutInvalidate[frameId]=null;if(this._currentScriptEvent)
event.warning=WebInspector.TimelineModel.WarningType.ForcedLayout;break;case recordTypes.FunctionCall:if(typeof eventData["scriptName"]==="string")
eventData["url"]=eventData["scriptName"];if(typeof eventData["scriptLine"]==="number")
eventData["lineNumber"]=eventData["scriptLine"];case recordTypes.EvaluateScript:case recordTypes.CompileScript:if(typeof eventData["lineNumber"]==="number")
--eventData["lineNumber"];if(typeof eventData["columnNumber"]==="number")
--eventData["columnNumber"];if(!this._currentScriptEvent)
this._currentScriptEvent=event;break;case recordTypes.SetLayerTreeId:this._inspectedTargetLayerTreeId=event.args["layerTreeId"]||event.args["data"]["layerTreeId"];break;case recordTypes.Paint:this._invalidationTracker.didPaint(event);event.highlightQuad=eventData["clip"];event.backendNodeId=eventData["nodeId"];if(!eventData["layerId"])
break;var layerId=eventData["layerId"];this._lastPaintForLayer[layerId]=event;break;case recordTypes.DisplayItemListSnapshot:case recordTypes.PictureSnapshot:var layerUpdateEvent=this._findAncestorEvent(recordTypes.UpdateLayer);if(!layerUpdateEvent||layerUpdateEvent.args["layerTreeId"]!==this._inspectedTargetLayerTreeId)
break;var paintEvent=this._lastPaintForLayer[layerUpdateEvent.args["layerId"]];if(paintEvent)
paintEvent.picture=event;break;case recordTypes.ScrollLayer:event.backendNodeId=eventData["nodeId"];break;case recordTypes.PaintImage:event.backendNodeId=eventData["nodeId"];event.url=eventData["url"];break;case recordTypes.DecodeImage:case recordTypes.ResizeImage:var paintImageEvent=this._findAncestorEvent(recordTypes.PaintImage);if(!paintImageEvent){var decodeLazyPixelRefEvent=this._findAncestorEvent(recordTypes.DecodeLazyPixelRef);paintImageEvent=decodeLazyPixelRefEvent&&this._paintImageEventByPixelRefId[decodeLazyPixelRefEvent.args["LazyPixelRef"]];}
if(!paintImageEvent)
break;event.backendNodeId=paintImageEvent.backendNodeId;event.url=paintImageEvent.url;break;case recordTypes.DrawLazyPixelRef:var paintImageEvent=this._findAncestorEvent(recordTypes.PaintImage);if(!paintImageEvent)
break;this._paintImageEventByPixelRefId[event.args["LazyPixelRef"]]=paintImageEvent;event.backendNodeId=paintImageEvent.backendNodeId;event.url=paintImageEvent.url;break;case recordTypes.MarkDOMContent:case recordTypes.MarkLoad:var page=eventData["page"];if(page&&page!==this._currentPage)
return false;break;case recordTypes.CommitLoad:var page=eventData["page"];if(page&&page!==this._currentPage)
return false;if(!eventData["isMainFrame"])
break;this._hadCommitLoad=true;this._firstCompositeLayers=null;break;case recordTypes.CompositeLayers:if(!this._firstCompositeLayers&&this._hadCommitLoad)
this._firstCompositeLayers=event;break;case recordTypes.FireIdleCallback:if(event.duration>eventData["allottedMilliseconds"]){event.warning=WebInspector.TimelineModel.WarningType.IdleDeadlineExceeded;}
break;}
if(WebInspector.TracingModel.isAsyncPhase(event.phase))
return true;var duration=event.duration;if(!duration)
return true;if(eventStack.length){var parent=eventStack.peekLast();parent.selfTime-=duration;if(parent.selfTime<0){var epsilon=1e-3;if(parent.selfTime<-epsilon)
console.error("Children are longer than parent at "+event.startTime+" ("+(event.startTime-this.minimumRecordTime()).toFixed(3)+") by "+parent.selfTime.toFixed(3));parent.selfTime=0;}}
event.selfTime=duration;eventStack.push(event);return true;},_processBrowserEvent:function(event)
{if(event.name!==WebInspector.TimelineModel.RecordType.LatencyInfoFlow)
return;var frameId=event.args["frameTreeNodeId"];if(typeof frameId==="number"&&frameId===this._mainFrameNodeId)
this._knownInputEvents.add(event.bind_id);},_processAsyncEvent:function(asyncEvent)
{var groups=WebInspector.TimelineModel.AsyncEventGroup;if(asyncEvent.hasCategory(WebInspector.TimelineModel.Category.Console))
return groups.console;if(asyncEvent.hasCategory(WebInspector.TimelineModel.Category.UserTiming))
return groups.userTiming;if(asyncEvent.name===WebInspector.TimelineModel.RecordType.Animation)
return groups.animation;if(asyncEvent.hasCategory(WebInspector.TimelineModel.Category.LatencyInfo)||asyncEvent.name===WebInspector.TimelineModel.RecordType.ImplSideFling){var lastStep=asyncEvent.steps.peekLast();if(lastStep.phase!==WebInspector.TracingModel.Phase.AsyncEnd)
return null;var data=lastStep.args["data"];asyncEvent.causedFrame=!!(data&&data["INPUT_EVENT_LATENCY_RENDERER_SWAP_COMPONENT"]);if(asyncEvent.hasCategory(WebInspector.TimelineModel.Category.LatencyInfo)){if(!this._knownInputEvents.has(lastStep.id))
return null;if(asyncEvent.name===WebInspector.TimelineModel.RecordType.InputLatencyMouseMove&&!asyncEvent.causedFrame)
return null;var rendererMain=data["INPUT_EVENT_LATENCY_RENDERER_MAIN_COMPONENT"];if(rendererMain){var time=rendererMain["time"]/1000;asyncEvent.steps[0].timeWaitingForMainThread=time-asyncEvent.steps[0].startTime;}}
return groups.input;}
return null;},_findAncestorEvent:function(name)
{for(var i=this._eventStack.length-1;i>=0;--i){var event=this._eventStack[i];if(event.name===name)
return event;}
return null;},_mergeAsyncEvents:function(target,source)
{for(var group of source.keys()){var events=target.get(group)||[];events=events.mergeOrdered(source.get(group)||[],WebInspector.TracingModel.Event.compareStartAndEndTime);target.set(group,events);}},reset:function()
{this._virtualThreads=[];this._mainThreadEvents=[];this._mainThreadAsyncEventsByGroup=new Map();this._inspectedTargetEvents=[];this._records=[];this._mainThreadTasks=[];this._gpuEvents=[];this._eventDividerRecords=[];this._sessionId=null;this._mainFrameNodeId=null;this._cpuProfiles=[];this._workerIdByThread=new WeakMap();this._minimumRecordTime=0;this._maximumRecordTime=0;},minimumRecordTime:function()
{return this._minimumRecordTime;},maximumRecordTime:function()
{return this._maximumRecordTime;},inspectedTargetEvents:function()
{return this._inspectedTargetEvents;},mainThreadEvents:function()
{return this._mainThreadEvents;},_setMainThreadEvents:function(events)
{this._mainThreadEvents=events;},mainThreadAsyncEvents:function()
{return this._mainThreadAsyncEventsByGroup;},virtualThreads:function()
{return this._virtualThreads;},isEmpty:function()
{return this.minimumRecordTime()===0&&this.maximumRecordTime()===0;},mainThreadTasks:function()
{return this._mainThreadTasks;},gpuEvents:function()
{return this._gpuEvents;},eventDividerRecords:function()
{return this._eventDividerRecords;},networkRequests:function()
{var requests=new Map();var requestsList=[];var zeroStartRequestsList=[];var types=WebInspector.TimelineModel.RecordType;var resourceTypes=new Set([types.ResourceSendRequest,types.ResourceReceiveResponse,types.ResourceReceivedData,types.ResourceFinish]);var events=this.mainThreadEvents();for(var i=0;i<events.length;++i){var e=events[i];if(!resourceTypes.has(e.name))
continue;var id=e.args["data"]["requestId"];var request=requests.get(id);if(request){request.addEvent(e);}else{request=new WebInspector.TimelineModel.NetworkRequest(e);requests.set(id,request);if(request.startTime)
requestsList.push(request);else
zeroStartRequestsList.push(request);}}
return zeroStartRequestsList.concat(requestsList);},}
WebInspector.TimelineModel.isVisible=function(filters,event)
{for(var i=0;i<filters.length;++i){if(!filters[i].accept(event))
return false;}
return true;}
WebInspector.TimelineModel.isMarkerEvent=function(event)
{var recordTypes=WebInspector.TimelineModel.RecordType;switch(event.name){case recordTypes.TimeStamp:case recordTypes.MarkFirstPaint:return true;case recordTypes.MarkDOMContent:case recordTypes.MarkLoad:return event.args["data"]["isMainFrame"];default:return false;}}
WebInspector.TimelineModel.NetworkRequest=function(event)
{this.startTime=event.name===WebInspector.TimelineModel.RecordType.ResourceSendRequest?event.startTime:0;this.endTime=Infinity;this.children=[];this.addEvent(event);}
WebInspector.TimelineModel.NetworkRequest.prototype={addEvent:function(event)
{this.children.push(event);var recordType=WebInspector.TimelineModel.RecordType;this.startTime=Math.min(this.startTime,event.startTime);var eventData=event.args["data"];if(eventData["mimeType"])
this.mimeType=eventData["mimeType"];if("priority"in eventData)
this.priority=eventData["priority"];if(event.name===recordType.ResourceFinish)
this.endTime=event.startTime;if(!this.responseTime&&(event.name===recordType.ResourceReceiveResponse||event.name===recordType.ResourceReceivedData))
this.responseTime=event.startTime;if(!this.url)
this.url=eventData["url"];if(!this.requestMethod)
this.requestMethod=eventData["requestMethod"];}}
WebInspector.TimelineModel.Filter=function()
{}
WebInspector.TimelineModel.Filter.prototype={accept:function(event)
{return true;}}
WebInspector.TimelineVisibleEventsFilter=function(visibleTypes)
{WebInspector.TimelineModel.Filter.call(this);this._visibleTypes=new Set(visibleTypes);}
WebInspector.TimelineVisibleEventsFilter.prototype={accept:function(event)
{return this._visibleTypes.has(WebInspector.TimelineModel._eventType(event));},__proto__:WebInspector.TimelineModel.Filter.prototype}
WebInspector.ExclusiveNameFilter=function(excludeNames)
{WebInspector.TimelineModel.Filter.call(this);this._excludeNames=new Set(excludeNames);}
WebInspector.ExclusiveNameFilter.prototype={accept:function(event)
{return!this._excludeNames.has(event.name);},__proto__:WebInspector.TimelineModel.Filter.prototype}
WebInspector.ExcludeTopLevelFilter=function()
{WebInspector.TimelineModel.Filter.call(this);}
WebInspector.ExcludeTopLevelFilter.prototype={accept:function(event)
{return!WebInspector.TracingModel.isTopLevelEvent(event);},__proto__:WebInspector.TimelineModel.Filter.prototype}
WebInspector.InvalidationTrackingEvent=function(event)
{this.type=event.name;this.startTime=event.startTime;this._tracingEvent=event;var eventData=event.args["data"];this.frame=eventData["frame"];this.nodeId=eventData["nodeId"];this.nodeName=eventData["nodeName"];this.paintId=eventData["paintId"];this.invalidationSet=eventData["invalidationSet"];this.invalidatedSelectorId=eventData["invalidatedSelectorId"];this.changedId=eventData["changedId"];this.changedClass=eventData["changedClass"];this.changedAttribute=eventData["changedAttribute"];this.changedPseudo=eventData["changedPseudo"];this.selectorPart=eventData["selectorPart"];this.extraData=eventData["extraData"];this.invalidationList=eventData["invalidationList"];this.cause={reason:eventData["reason"],stackTrace:eventData["stackTrace"]};if(!this.cause.reason&&this.cause.stackTrace&&this.type===WebInspector.TimelineModel.RecordType.LayoutInvalidationTracking)
this.cause.reason="Layout forced";}
WebInspector.InvalidationCause;WebInspector.InvalidationTracker=function()
{this._initializePerFrameState();}
WebInspector.InvalidationTracker.prototype={addInvalidation:function(invalidation)
{this._startNewFrameIfNeeded();if(!invalidation.nodeId&&!invalidation.paintId){console.error("Invalidation lacks node information.");console.error(invalidation);return;}
var recordTypes=WebInspector.TimelineModel.RecordType;if(invalidation.type===recordTypes.PaintInvalidationTracking&&invalidation.nodeId){var invalidations=this._invalidationsByNodeId[invalidation.nodeId]||[];for(var i=0;i<invalidations.length;++i)
invalidations[i].paintId=invalidation.paintId;return;}
if(invalidation.type===recordTypes.StyleRecalcInvalidationTracking&&invalidation.cause.reason==="StyleInvalidator")
return;var styleRecalcInvalidation=(invalidation.type===recordTypes.ScheduleStyleInvalidationTracking||invalidation.type===recordTypes.StyleInvalidatorInvalidationTracking||invalidation.type===recordTypes.StyleRecalcInvalidationTracking);if(styleRecalcInvalidation){var duringRecalcStyle=invalidation.startTime&&this._lastRecalcStyle&&invalidation.startTime>=this._lastRecalcStyle.startTime&&invalidation.startTime<=this._lastRecalcStyle.endTime;if(duringRecalcStyle)
this._associateWithLastRecalcStyleEvent(invalidation);}
if(this._invalidations[invalidation.type])
this._invalidations[invalidation.type].push(invalidation);else
this._invalidations[invalidation.type]=[invalidation];if(invalidation.nodeId){if(this._invalidationsByNodeId[invalidation.nodeId])
this._invalidationsByNodeId[invalidation.nodeId].push(invalidation);else
this._invalidationsByNodeId[invalidation.nodeId]=[invalidation];}},didRecalcStyle:function(recalcStyleEvent)
{this._lastRecalcStyle=recalcStyleEvent;var types=[WebInspector.TimelineModel.RecordType.ScheduleStyleInvalidationTracking,WebInspector.TimelineModel.RecordType.StyleInvalidatorInvalidationTracking,WebInspector.TimelineModel.RecordType.StyleRecalcInvalidationTracking];for(var invalidation of this._invalidationsOfTypes(types))
this._associateWithLastRecalcStyleEvent(invalidation);},_associateWithLastRecalcStyleEvent:function(invalidation)
{if(invalidation.linkedRecalcStyleEvent)
return;var recordTypes=WebInspector.TimelineModel.RecordType;var recalcStyleFrameId=this._lastRecalcStyle.args["beginData"]["frame"];if(invalidation.type===recordTypes.StyleInvalidatorInvalidationTracking){this._addSyntheticStyleRecalcInvalidations(this._lastRecalcStyle,recalcStyleFrameId,invalidation);}else if(invalidation.type===recordTypes.ScheduleStyleInvalidationTracking){}else{this._addInvalidationToEvent(this._lastRecalcStyle,recalcStyleFrameId,invalidation);}
invalidation.linkedRecalcStyleEvent=true;},_addSyntheticStyleRecalcInvalidations:function(event,frameId,styleInvalidatorInvalidation)
{if(!styleInvalidatorInvalidation.invalidationList){this._addSyntheticStyleRecalcInvalidation(styleInvalidatorInvalidation._tracingEvent,styleInvalidatorInvalidation);return;}
if(!styleInvalidatorInvalidation.nodeId){console.error("Invalidation lacks node information.");console.error(invalidation);return;}
for(var i=0;i<styleInvalidatorInvalidation.invalidationList.length;i++){var setId=styleInvalidatorInvalidation.invalidationList[i]["id"];var lastScheduleStyleRecalculation;var nodeInvalidations=this._invalidationsByNodeId[styleInvalidatorInvalidation.nodeId]||[];for(var j=0;j<nodeInvalidations.length;j++){var invalidation=nodeInvalidations[j];if(invalidation.frame!==frameId||invalidation.invalidationSet!==setId||invalidation.type!==WebInspector.TimelineModel.RecordType.ScheduleStyleInvalidationTracking)
continue;lastScheduleStyleRecalculation=invalidation;}
if(!lastScheduleStyleRecalculation){console.error("Failed to lookup the event that scheduled a style invalidator invalidation.");continue;}
this._addSyntheticStyleRecalcInvalidation(lastScheduleStyleRecalculation._tracingEvent,styleInvalidatorInvalidation);}},_addSyntheticStyleRecalcInvalidation:function(baseEvent,styleInvalidatorInvalidation)
{var invalidation=new WebInspector.InvalidationTrackingEvent(baseEvent);invalidation.type=WebInspector.TimelineModel.RecordType.StyleRecalcInvalidationTracking;invalidation.synthetic=true;if(styleInvalidatorInvalidation.cause.reason)
invalidation.cause.reason=styleInvalidatorInvalidation.cause.reason;if(styleInvalidatorInvalidation.selectorPart)
invalidation.selectorPart=styleInvalidatorInvalidation.selectorPart;this.addInvalidation(invalidation);if(!invalidation.linkedRecalcStyleEvent)
this._associateWithLastRecalcStyleEvent(invalidation);},didLayout:function(layoutEvent)
{var layoutFrameId=layoutEvent.args["beginData"]["frame"];for(var invalidation of this._invalidationsOfTypes([WebInspector.TimelineModel.RecordType.LayoutInvalidationTracking])){if(invalidation.linkedLayoutEvent)
continue;this._addInvalidationToEvent(layoutEvent,layoutFrameId,invalidation);invalidation.linkedLayoutEvent=true;}},didPaint:function(paintEvent)
{this._didPaint=true;var layerId=paintEvent.args["data"]["layerId"];if(layerId)
this._lastPaintWithLayer=paintEvent;if(!this._lastPaintWithLayer)
return;var effectivePaintId=this._lastPaintWithLayer.args["data"]["nodeId"];var paintFrameId=paintEvent.args["data"]["frame"];var types=[WebInspector.TimelineModel.RecordType.StyleRecalcInvalidationTracking,WebInspector.TimelineModel.RecordType.LayoutInvalidationTracking,WebInspector.TimelineModel.RecordType.PaintInvalidationTracking,WebInspector.TimelineModel.RecordType.ScrollInvalidationTracking];for(var invalidation of this._invalidationsOfTypes(types)){if(invalidation.paintId===effectivePaintId)
this._addInvalidationToEvent(paintEvent,paintFrameId,invalidation);}},_addInvalidationToEvent:function(event,eventFrameId,invalidation)
{if(eventFrameId!==invalidation.frame)
return;if(!event.invalidationTrackingEvents)
event.invalidationTrackingEvents=[invalidation];else
event.invalidationTrackingEvents.push(invalidation);},_invalidationsOfTypes:function(types)
{var invalidations=this._invalidations;if(!types)
types=Object.keys(invalidations);function*generator()
{for(var i=0;i<types.length;++i){var invalidationList=invalidations[types[i]]||[];for(var j=0;j<invalidationList.length;++j)
yield invalidationList[j];}}
return generator();},_startNewFrameIfNeeded:function()
{if(!this._didPaint)
return;this._initializePerFrameState();},_initializePerFrameState:function()
{this._invalidations={};this._invalidationsByNodeId={};this._lastRecalcStyle=undefined;this._lastPaintWithLayer=undefined;this._didPaint=false;}}
WebInspector.TimelineAsyncEventTracker=function()
{WebInspector.TimelineAsyncEventTracker._initialize();this._initiatorByType=new Map();for(var initiator of WebInspector.TimelineAsyncEventTracker._asyncEvents.keys())
this._initiatorByType.set(initiator,new Map());}
WebInspector.TimelineAsyncEventTracker._initialize=function()
{if(WebInspector.TimelineAsyncEventTracker._asyncEvents)
return;var events=new Map();var type=WebInspector.TimelineModel.RecordType;events.set(type.TimerInstall,{causes:[type.TimerFire],joinBy:"timerId"});events.set(type.ResourceSendRequest,{causes:[type.ResourceReceiveResponse,type.ResourceReceivedData,type.ResourceFinish],joinBy:"requestId"});events.set(type.RequestAnimationFrame,{causes:[type.FireAnimationFrame],joinBy:"id"});events.set(type.RequestIdleCallback,{causes:[type.FireIdleCallback],joinBy:"id"});events.set(type.WebSocketCreate,{causes:[type.WebSocketSendHandshakeRequest,type.WebSocketReceiveHandshakeResponse,type.WebSocketDestroy],joinBy:"identifier"});WebInspector.TimelineAsyncEventTracker._asyncEvents=events;WebInspector.TimelineAsyncEventTracker._typeToInitiator=new Map();for(var entry of events){var types=entry[1].causes;for(type of types)
WebInspector.TimelineAsyncEventTracker._typeToInitiator.set(type,entry[0]);}}
WebInspector.TimelineAsyncEventTracker.prototype={processEvent:function(event)
{var initiatorType=WebInspector.TimelineAsyncEventTracker._typeToInitiator.get((event.name));var isInitiator=!initiatorType;if(!initiatorType)
initiatorType=(event.name);var initiatorInfo=WebInspector.TimelineAsyncEventTracker._asyncEvents.get(initiatorType);if(!initiatorInfo)
return;var id=event.args["data"][initiatorInfo.joinBy];if(!id)
return;var initiatorMap=this._initiatorByType.get(initiatorType);if(isInitiator)
initiatorMap.set(id,event);else
event.initiator=initiatorMap.get(id)||null;}}},{}],232:[function(require,module,exports){WebInspector.TimelineProfileTree={};WebInspector.TimelineProfileTree.Node=function()
{this.totalTime;this.selfTime;this.id;this.event;this.children;this.parent;this._isGroupNode=false;}
WebInspector.TimelineProfileTree.Node.prototype={isGroupNode:function()
{return this._isGroupNode;}}
WebInspector.TimelineProfileTree.buildTopDown=function(events,filters,startTime,endTime,eventIdCallback)
{var initialTime=1e7;var root=new WebInspector.TimelineProfileTree.Node();root.totalTime=initialTime;root.selfTime=initialTime;root.children=(new Map());var parent=root;function onStartEvent(e)
{if(!WebInspector.TimelineModel.isVisible(filters,e))
return;var time=e.endTime?Math.min(endTime,e.endTime)-Math.max(startTime,e.startTime):0;var id=eventIdCallback?eventIdCallback(e):Symbol("uniqueEventId");if(!parent.children)
parent.children=(new Map());var node=parent.children.get(id);if(node){node.selfTime+=time;node.totalTime+=time;}else{node=new WebInspector.TimelineProfileTree.Node();node.totalTime=time;node.selfTime=time;node.parent=parent;node.id=id;node.event=e;parent.children.set(id,node);}
parent.selfTime-=time;if(parent.selfTime<0){console.log("Error: Negative self of "+parent.selfTime,e);parent.selfTime=0;}
if(e.endTime)
parent=node;}
function onEndEvent(e)
{if(!WebInspector.TimelineModel.isVisible(filters,e))
return;parent=parent.parent;}
var instantEventCallback=eventIdCallback?undefined:onStartEvent;WebInspector.TimelineModel.forEachEvent(events,onStartEvent,onEndEvent,instantEventCallback,startTime,endTime);root.totalTime-=root.selfTime;root.selfTime=0;return root;}
WebInspector.TimelineProfileTree.buildBottomUp=function(topDownTree,groupingCallback)
{var buRoot=new WebInspector.TimelineProfileTree.Node();buRoot.selfTime=0;buRoot.totalTime=0;buRoot.children=new Map();var nodesOnStack=(new Set());if(topDownTree.children)
topDownTree.children.forEach(processNode);buRoot.totalTime=topDownTree.totalTime;function processNode(tdNode)
{var buParent=groupingCallback&&groupingCallback(tdNode)||buRoot;if(buParent!==buRoot){buRoot.children.set(buParent.id,buParent);buParent.parent=buRoot;}
appendNode(tdNode,buParent);var hadNode=nodesOnStack.has(tdNode.id);if(!hadNode)
nodesOnStack.add(tdNode.id);if(tdNode.children)
tdNode.children.forEach(processNode);if(!hadNode)
nodesOnStack.delete(tdNode.id);}
function appendNode(tdNode,buParent)
{var selfTime=tdNode.selfTime;var totalTime=tdNode.totalTime;buParent.selfTime+=selfTime;buParent.totalTime+=selfTime;while(tdNode.parent){if(!buParent.children)
buParent.children=(new Map());var id=tdNode.id;var buNode=buParent.children.get(id);if(!buNode){buNode=new WebInspector.TimelineProfileTree.Node();buNode.selfTime=selfTime;buNode.totalTime=totalTime;buNode.event=tdNode.event;buNode.id=id;buNode.parent=buParent;buParent.children.set(id,buNode);}else{buNode.selfTime+=selfTime;if(!nodesOnStack.has(id))
buNode.totalTime+=totalTime;}
tdNode=tdNode.parent;buParent=buNode;}}
var rootChildren=buRoot.children;for(var item of rootChildren.entries()){if(item[1].selfTime===0)
rootChildren.delete((item[0]));}
return buRoot;}
WebInspector.TimelineProfileTree.eventURL=function(event)
{var data=event.args["data"]||event.args["beginData"];if(data&&data["url"])
return data["url"];var frame=WebInspector.TimelineProfileTree.eventStackFrame(event);while(frame){var url=frame["url"];if(url)
return url;frame=frame.parent;}
return null;}
WebInspector.TimelineProfileTree.eventStackFrame=function(event)
{if(event.name===WebInspector.TimelineModel.RecordType.JSFrame)
return(event.args["data"]||null);var topFrame=event.stackTrace&&event.stackTrace[0];if(topFrame)
return(topFrame);var initiator=event.initiator;return(initiator&&initiator.stackTrace&&initiator.stackTrace[0]||null);}
WebInspector.TimelineAggregator=function(titleMapper,categoryMapper)
{this._titleMapper=titleMapper;this._categoryMapper=categoryMapper;this._groupNodes=new Map();}
WebInspector.TimelineAggregator.GroupBy={None:"None",EventName:"EventName",Category:"Category",Domain:"Domain",Subdomain:"Subdomain",URL:"URL"}
WebInspector.TimelineAggregator.eventId=function(event)
{if(event.name===WebInspector.TimelineModel.RecordType.JSFrame){var data=event.args["data"];return"f:"+data["functionName"]+"@"+(data["scriptId"]||data["url"]||"");}
return event.name+":@"+WebInspector.TimelineProfileTree.eventURL(event);}
WebInspector.TimelineAggregator._extensionInternalPrefix="extensions::";WebInspector.TimelineAggregator._groupNodeFlag=Symbol("groupNode");WebInspector.TimelineAggregator.isExtensionInternalURL=function(url)
{return url.startsWith(WebInspector.TimelineAggregator._extensionInternalPrefix);}
WebInspector.TimelineAggregator.prototype={groupFunction:function(groupBy)
{var idMapper=this._nodeToGroupIdFunction(groupBy);return idMapper&&this._nodeToGroupNode.bind(this,idMapper);},performGrouping:function(root,groupBy)
{var nodeMapper=this.groupFunction(groupBy);if(!nodeMapper)
return root;for(var node of root.children.values()){var groupNode=nodeMapper(node);groupNode.parent=root;groupNode.selfTime+=node.selfTime;groupNode.totalTime+=node.totalTime;groupNode.children.set(node.id,node);node.parent=root;}
root.children=this._groupNodes;return root;},_nodeToGroupIdFunction:function(groupBy)
{function groupByURL(node)
{return WebInspector.TimelineProfileTree.eventURL(node.event)||"";}
function groupByDomain(groupSubdomains,node)
{var url=WebInspector.TimelineProfileTree.eventURL(node.event)||"";if(WebInspector.TimelineAggregator.isExtensionInternalURL(url))
return WebInspector.TimelineAggregator._extensionInternalPrefix;var parsedURL=url.asParsedURL();if(!parsedURL)
return"";if(parsedURL.scheme==="chrome-extension")
return parsedURL.scheme+"://"+parsedURL.host;if(!groupSubdomains)
return parsedURL.host;if(/^[.0-9]+$/.test(parsedURL.host))
return parsedURL.host;var domainMatch=/([^.]*\.)?[^.]*$/.exec(parsedURL.host);return domainMatch&&domainMatch[0]||"";}
switch(groupBy){case WebInspector.TimelineAggregator.GroupBy.None:return null;case WebInspector.TimelineAggregator.GroupBy.EventName:return node=>node.event?this._titleMapper(node.event):"";case WebInspector.TimelineAggregator.GroupBy.Category:return node=>node.event?this._categoryMapper(node.event):"";case WebInspector.TimelineAggregator.GroupBy.Subdomain:return groupByDomain.bind(null,false);case WebInspector.TimelineAggregator.GroupBy.Domain:return groupByDomain.bind(null,true);case WebInspector.TimelineAggregator.GroupBy.URL:return groupByURL;default:return null;}},_buildGroupNode:function(id,event)
{var groupNode=new WebInspector.TimelineProfileTree.Node();groupNode.id=id;groupNode.selfTime=0;groupNode.totalTime=0;groupNode.children=new Map();groupNode.event=event;groupNode._isGroupNode=true;this._groupNodes.set(id,groupNode);return groupNode;},_nodeToGroupNode:function(nodeToGroupId,node)
{var id=nodeToGroupId(node);return this._groupNodes.get(id)||this._buildGroupNode(id,node.event);},}},{}],233:[function(require,module,exports){WebInspector.SortableDataGrid=function(columnsArray,editCallback,deleteCallback,refreshCallback,contextMenuCallback)
{WebInspector.ViewportDataGrid.call(this,columnsArray,editCallback,deleteCallback,refreshCallback,contextMenuCallback);this._sortingFunction=WebInspector.SortableDataGrid.TrivialComparator;this.setRootNode(new WebInspector.SortableDataGridNode());}
WebInspector.SortableDataGrid.NodeComparator;WebInspector.SortableDataGrid.TrivialComparator=function(a,b)
{return 0;}
WebInspector.SortableDataGrid.NumericComparator=function(columnIdentifier,a,b)
{var aValue=a.data[columnIdentifier];var bValue=b.data[columnIdentifier];var aNumber=Number(aValue instanceof Node?aValue.textContent:aValue);var bNumber=Number(bValue instanceof Node?bValue.textContent:bValue);return aNumber<bNumber?-1:(aNumber>bNumber?1:0);}
WebInspector.SortableDataGrid.StringComparator=function(columnIdentifier,a,b)
{var aValue=a.data[columnIdentifier];var bValue=b.data[columnIdentifier];var aString=aValue instanceof Node?aValue.textContent:String(aValue);var bString=bValue instanceof Node?bValue.textContent:String(bValue);return aString<bString?-1:(aString>bString?1:0);}
WebInspector.SortableDataGrid.Comparator=function(comparator,reverseMode,a,b)
{return reverseMode?comparator(b,a):comparator(a,b);}
WebInspector.SortableDataGrid.create=function(columnNames,values)
{var numColumns=columnNames.length;if(!numColumns)
return null;var columns=[];for(var i=0;i<columnNames.length;++i)
columns.push({title:columnNames[i],width:columnNames[i].length,sortable:true});var nodes=[];for(var i=0;i<values.length/numColumns;++i){var data={};for(var j=0;j<columnNames.length;++j)
data[j]=values[numColumns*i+j];var node=new WebInspector.SortableDataGridNode(data);node.selectable=false;nodes.push(node);}
var dataGrid=new WebInspector.SortableDataGrid(columns);var length=nodes.length;var rootNode=dataGrid.rootNode();for(var i=0;i<length;++i)
rootNode.appendChild(nodes[i]);dataGrid.addEventListener(WebInspector.DataGrid.Events.SortingChanged,sortDataGrid);function sortDataGrid()
{var nodes=dataGrid.rootNode().children;var sortColumnIdentifier=dataGrid.sortColumnIdentifier();if(!sortColumnIdentifier)
return;var columnIsNumeric=true;for(var i=0;i<nodes.length;i++){var value=nodes[i].data[sortColumnIdentifier];if(isNaN(value instanceof Node?value.textContent:value)){columnIsNumeric=false;break;}}
var comparator=columnIsNumeric?WebInspector.SortableDataGrid.NumericComparator:WebInspector.SortableDataGrid.StringComparator;dataGrid.sortNodes(comparator.bind(null,sortColumnIdentifier),!dataGrid.isSortOrderAscending());}
return dataGrid;}
WebInspector.SortableDataGrid.prototype={insertChild:function(node)
{var root=(this.rootNode());root.insertChildOrdered(node);},sortNodes:function(comparator,reverseMode)
{this._sortingFunction=WebInspector.SortableDataGrid.Comparator.bind(null,comparator,reverseMode);this._rootNode._sortChildren(reverseMode);this.scheduleUpdateStructure();},__proto__:WebInspector.ViewportDataGrid.prototype}
WebInspector.SortableDataGridNode=function(data,hasChildren)
{WebInspector.ViewportDataGridNode.call(this,data,hasChildren);}
WebInspector.SortableDataGridNode.prototype={insertChildOrdered:function(node)
{this.insertChild(node,this.children.upperBound(node,this.dataGrid._sortingFunction));},_sortChildren:function()
{this.children.sort(this.dataGrid._sortingFunction);for(var i=0;i<this.children.length;++i)
this.children[i].recalculateSiblings(i);for(var child of this.children)
child._sortChildren();},__proto__:WebInspector.ViewportDataGridNode.prototype}},{}],234:[function(require,module,exports){exports=module.exports=require('./debug');exports.log=log;exports.formatArgs=formatArgs;exports.save=save;exports.load=load;exports.useColors=useColors;exports.storage='undefined'!=typeof chrome&&'undefined'!=typeof chrome.storage?chrome.storage.local:localstorage();exports.colors=['lightseagreen','forestgreen','goldenrod','dodgerblue','darkorchid','crimson'];function useColors(){return('WebkitAppearance'in document.documentElement.style)||(window.console&&(console.firebug||(console.exception&&console.table)))||(navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31);}
exports.formatters.j=function(v){return JSON.stringify(v);};function formatArgs(){var args=arguments;var useColors=this.useColors;args[0]=(useColors?'%c':'')
+this.namespace
+(useColors?' %c':' ')
+args[0]
+(useColors?'%c ':' ')
+'+'+exports.humanize(this.diff);if(!useColors)return args;var c='color: '+this.color;args=[args[0],c,'color: inherit'].concat(Array.prototype.slice.call(args,1));var index=0;var lastC=0;args[0].replace(/%[a-z%]/g,function(match){if('%%'===match)return;index++;if('%c'===match){lastC=index;}});args.splice(lastC,0,c);return args;}
function log(){return'object'===typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments);}
function save(namespaces){try{if(null==namespaces){exports.storage.removeItem('debug');}else{exports.storage.debug=namespaces;}}catch(e){}}
function load(){var r;try{r=exports.storage.debug;}catch(e){}
return r;}
exports.enable(load());function localstorage(){try{return window.localStorage;}catch(e){}}},{"./debug":235}],235:[function(require,module,exports){exports=module.exports=debug;exports.coerce=coerce;exports.disable=disable;exports.enable=enable;exports.enabled=enabled;exports.humanize=require('ms');exports.names=[];exports.skips=[];exports.formatters={};var prevColor=0;var prevTime;function selectColor(){return exports.colors[prevColor++%exports.colors.length];}
function debug(namespace){function disabled(){}
disabled.enabled=false;function enabled(){var self=enabled;var curr=+new Date();var ms=curr-(prevTime||curr);self.diff=ms;self.prev=prevTime;self.curr=curr;prevTime=curr;if(null==self.useColors)self.useColors=exports.useColors();if(null==self.color&&self.useColors)self.color=selectColor();var args=Array.prototype.slice.call(arguments);args[0]=exports.coerce(args[0]);if('string'!==typeof args[0]){args=['%o'].concat(args);}
var index=0;args[0]=args[0].replace(/%([a-z%])/g,function(match,format){if(match==='%%')return match;index++;var formatter=exports.formatters[format];if('function'===typeof formatter){var val=args[index];match=formatter.call(self,val);args.splice(index,1);index--;}
return match;});if('function'===typeof exports.formatArgs){args=exports.formatArgs.apply(self,args);}
var logFn=enabled.log||exports.log||console.log.bind(console);logFn.apply(self,args);}
enabled.enabled=true;var fn=exports.enabled(namespace)?enabled:disabled;fn.namespace=namespace;return fn;}
function enable(namespaces){exports.save(namespaces);var split=(namespaces||'').split(/[\s,]+/);var len=split.length;for(var i=0;i<len;i++){if(!split[i])continue;namespaces=split[i].replace(/\*/g,'.*?');if(namespaces[0]==='-'){exports.skips.push(new RegExp('^'+namespaces.substr(1)+'$'));}else{exports.names.push(new RegExp('^'+namespaces+'$'));}}}
function disable(){exports.enable('');}
function enabled(name){var i,len;for(i=0,len=exports.skips.length;i<len;i++){if(exports.skips[i].test(name)){return false;}}
for(i=0,len=exports.names.length;i<len;i++){if(exports.names[i].test(name)){return true;}}
return false;}
function coerce(val){if(val instanceof Error)return val.stack||val.message;return val;}},{"ms":282}],236:[function(require,module,exports){module.exports=function(WebInspector){function TimelineModelTreeView(model){this._rootNode=model;}
TimelineModelTreeView.prototype.sortingChanged=function(sortItem,sortOrder){if(!sortItem)
return;var sortFunction;switch(sortItem){case'startTime':sortFunction=compareStartTime;break;case'self':sortFunction=compareNumericField.bind(null,'selfTime');break;case'total':sortFunction=compareNumericField.bind(null,'totalTime');break;case'activity':sortFunction=compareName;break;default:console.assert(false,'Unknown sort field: '+sortItem);return;}
return this.sortNodes(sortFunction,sortOrder!=='asc');function compareNumericField(field,a,b){var nodeA=(a[1]);var nodeB=(b[1]);return nodeA[field]-nodeB[field];}
function compareStartTime(a,b){var nodeA=(a[1]);var nodeB=(b[1]);return nodeA.event.startTime-nodeB.event.startTime;}
function compareName(a,b){var nodeA=(a[1]);var nodeB=(b[1]);var nameA=WebInspector.TimelineTreeView.eventNameForSorting(nodeA.event);var nameB=WebInspector.TimelineTreeView.eventNameForSorting(nodeB.event);return nameA.localeCompare(nameB);}};TimelineModelTreeView.prototype.sortNodes=function(comparator,reverseMode){this._sortingFunction=WebInspector.SortableDataGrid.Comparator.bind(null,comparator,reverseMode);sortChildren(this._rootNode,this._sortingFunction,reverseMode);};function sortChildren(parent,sortingFunction){if(!parent.children)return;parent.children=new Map([...parent.children.entries()].sort(sortingFunction));for(var i=0;i<parent.children.length;++i)
recalculateSiblings(parent.children[i],i);for(var child of parent.children.values())
sortChildren(child,sortingFunction);}
function recalculateSiblings(node,myIndex){if(!node.parent)
return;var previousChild=node.parent.children[myIndex-1]||null;if(previousChild)
previousChild.nextSibling=node;node.previousSibling=previousChild;var nextChild=node.parent.children[myIndex+1]||null;if(nextChild)
nextChild.previousSibling=node;node.nextSibling=nextChild;}
return TimelineModelTreeView;};},{}],237:[function(require,module,exports){exports.glMatrix=require("./gl-matrix/common.js");exports.mat2=require("./gl-matrix/mat2.js");exports.mat2d=require("./gl-matrix/mat2d.js");exports.mat3=require("./gl-matrix/mat3.js");exports.mat4=require("./gl-matrix/mat4.js");exports.quat=require("./gl-matrix/quat.js");exports.vec2=require("./gl-matrix/vec2.js");exports.vec3=require("./gl-matrix/vec3.js");exports.vec4=require("./gl-matrix/vec4.js");},{"./gl-matrix/common.js":238,"./gl-matrix/mat2.js":239,"./gl-matrix/mat2d.js":240,"./gl-matrix/mat3.js":241,"./gl-matrix/mat4.js":242,"./gl-matrix/quat.js":243,"./gl-matrix/vec2.js":244,"./gl-matrix/vec3.js":245,"./gl-matrix/vec4.js":246}],238:[function(require,module,exports){var glMatrix={};glMatrix.EPSILON=0.000001;glMatrix.ARRAY_TYPE=(typeof Float32Array!=='undefined')?Float32Array:Array;glMatrix.RANDOM=Math.random;glMatrix.ENABLE_SIMD=false;glMatrix.SIMD_AVAILABLE=(glMatrix.ARRAY_TYPE===Float32Array)&&('SIMD'in this);glMatrix.USE_SIMD=glMatrix.ENABLE_SIMD&&glMatrix.SIMD_AVAILABLE;glMatrix.setMatrixArrayType=function(type){glMatrix.ARRAY_TYPE=type;}
var degree=Math.PI/180;glMatrix.toRadian=function(a){return a*degree;}
glMatrix.equals=function(a,b){return Math.abs(a-b)<=glMatrix.EPSILON*Math.max(1.0,Math.abs(a),Math.abs(b));}
module.exports=glMatrix;},{}],239:[function(require,module,exports){var glMatrix=require("./common.js");var mat2={};mat2.create=function(){var out=new glMatrix.ARRAY_TYPE(4);out[0]=1;out[1]=0;out[2]=0;out[3]=1;return out;};mat2.clone=function(a){var out=new glMatrix.ARRAY_TYPE(4);out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];return out;};mat2.copy=function(out,a){out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];return out;};mat2.identity=function(out){out[0]=1;out[1]=0;out[2]=0;out[3]=1;return out;};mat2.fromValues=function(m00,m01,m10,m11){var out=new glMatrix.ARRAY_TYPE(4);out[0]=m00;out[1]=m01;out[2]=m10;out[3]=m11;return out;};mat2.set=function(out,m00,m01,m10,m11){out[0]=m00;out[1]=m01;out[2]=m10;out[3]=m11;return out;};mat2.transpose=function(out,a){if(out===a){var a1=a[1];out[1]=a[2];out[2]=a1;}else{out[0]=a[0];out[1]=a[2];out[2]=a[1];out[3]=a[3];}
return out;};mat2.invert=function(out,a){var a0=a[0],a1=a[1],a2=a[2],a3=a[3],det=a0*a3-a2*a1;if(!det){return null;}
det=1.0/det;out[0]=a3*det;out[1]=-a1*det;out[2]=-a2*det;out[3]=a0*det;return out;};mat2.adjoint=function(out,a){var a0=a[0];out[0]=a[3];out[1]=-a[1];out[2]=-a[2];out[3]=a0;return out;};mat2.determinant=function(a){return a[0]*a[3]-a[2]*a[1];};mat2.multiply=function(out,a,b){var a0=a[0],a1=a[1],a2=a[2],a3=a[3];var b0=b[0],b1=b[1],b2=b[2],b3=b[3];out[0]=a0*b0+a2*b1;out[1]=a1*b0+a3*b1;out[2]=a0*b2+a2*b3;out[3]=a1*b2+a3*b3;return out;};mat2.mul=mat2.multiply;mat2.rotate=function(out,a,rad){var a0=a[0],a1=a[1],a2=a[2],a3=a[3],s=Math.sin(rad),c=Math.cos(rad);out[0]=a0*c+a2*s;out[1]=a1*c+a3*s;out[2]=a0*-s+a2*c;out[3]=a1*-s+a3*c;return out;};mat2.scale=function(out,a,v){var a0=a[0],a1=a[1],a2=a[2],a3=a[3],v0=v[0],v1=v[1];out[0]=a0*v0;out[1]=a1*v0;out[2]=a2*v1;out[3]=a3*v1;return out;};mat2.fromRotation=function(out,rad){var s=Math.sin(rad),c=Math.cos(rad);out[0]=c;out[1]=s;out[2]=-s;out[3]=c;return out;}
mat2.fromScaling=function(out,v){out[0]=v[0];out[1]=0;out[2]=0;out[3]=v[1];return out;}
mat2.str=function(a){return'mat2('+a[0]+', '+a[1]+', '+a[2]+', '+a[3]+')';};mat2.frob=function(a){return(Math.sqrt(Math.pow(a[0],2)+Math.pow(a[1],2)+Math.pow(a[2],2)+Math.pow(a[3],2)))};mat2.LDU=function(L,D,U,a){L[2]=a[2]/a[0];U[0]=a[0];U[1]=a[1];U[3]=a[3]-L[2]*U[1];return[L,D,U];};mat2.add=function(out,a,b){out[0]=a[0]+b[0];out[1]=a[1]+b[1];out[2]=a[2]+b[2];out[3]=a[3]+b[3];return out;};mat2.subtract=function(out,a,b){out[0]=a[0]-b[0];out[1]=a[1]-b[1];out[2]=a[2]-b[2];out[3]=a[3]-b[3];return out;};mat2.sub=mat2.subtract;mat2.exactEquals=function(a,b){return a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3];};mat2.equals=function(a,b){var a0=a[0],a1=a[1],a2=a[2],a3=a[3];var b0=b[0],b1=b[1],b2=b[2],b3=b[3];return(Math.abs(a0-b0)<=glMatrix.EPSILON*Math.max(1.0,Math.abs(a0),Math.abs(b0))&&Math.abs(a1-b1)<=glMatrix.EPSILON*Math.max(1.0,Math.abs(a1),Math.abs(b1))&&Math.abs(a2-b2)<=glMatrix.EPSILON*Math.max(1.0,Math.abs(a2),Math.abs(b2))&&Math.abs(a3-b3)<=glMatrix.EPSILON*Math.max(1.0,Math.abs(a3),Math.abs(b3)));};mat2.multiplyScalar=function(out,a,b){out[0]=a[0]*b;out[1]=a[1]*b;out[2]=a[2]*b;out[3]=a[3]*b;return out;};mat2.multiplyScalarAndAdd=function(out,a,b,scale){out[0]=a[0]+(b[0]*scale);out[1]=a[1]+(b[1]*scale);out[2]=a[2]+(b[2]*scale);out[3]=a[3]+(b[3]*scale);return out;};module.exports=mat2;},{"./common.js":238}],240:[function(require,module,exports){var glMatrix=require("./common.js");var mat2d={};mat2d.create=function(){var out=new glMatrix.ARRAY_TYPE(6);out[0]=1;out[1]=0;out[2]=0;out[3]=1;out[4]=0;out[5]=0;return out;};mat2d.clone=function(a){var out=new glMatrix.ARRAY_TYPE(6);out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];out[4]=a[4];out[5]=a[5];return out;};mat2d.copy=function(out,a){out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];out[4]=a[4];out[5]=a[5];return out;};mat2d.identity=function(out){out[0]=1;out[1]=0;out[2]=0;out[3]=1;out[4]=0;out[5]=0;return out;};mat2d.fromValues=function(a,b,c,d,tx,ty){var out=new glMatrix.ARRAY_TYPE(6);out[0]=a;out[1]=b;out[2]=c;out[3]=d;out[4]=tx;out[5]=ty;return out;};mat2d.set=function(out,a,b,c,d,tx,ty){out[0]=a;out[1]=b;out[2]=c;out[3]=d;out[4]=tx;out[5]=ty;return out;};mat2d.invert=function(out,a){var aa=a[0],ab=a[1],ac=a[2],ad=a[3],atx=a[4],aty=a[5];var det=aa*ad-ab*ac;if(!det){return null;}
det=1.0/det;out[0]=ad*det;out[1]=-ab*det;out[2]=-ac*det;out[3]=aa*det;out[4]=(ac*aty-ad*atx)*det;out[5]=(ab*atx-aa*aty)*det;return out;};mat2d.determinant=function(a){return a[0]*a[3]-a[1]*a[2];};mat2d.multiply=function(out,a,b){var a0=a[0],a1=a[1],a2=a[2],a3=a[3],a4=a[4],a5=a[5],b0=b[0],b1=b[1],b2=b[2],b3=b[3],b4=b[4],b5=b[5];out[0]=a0*b0+a2*b1;out[1]=a1*b0+a3*b1;out[2]=a0*b2+a2*b3;out[3]=a1*b2+a3*b3;out[4]=a0*b4+a2*b5+a4;out[5]=a1*b4+a3*b5+a5;return out;};mat2d.mul=mat2d.multiply;mat2d.rotate=function(out,a,rad){var a0=a[0],a1=a[1],a2=a[2],a3=a[3],a4=a[4],a5=a[5],s=Math.sin(rad),c=Math.cos(rad);out[0]=a0*c+a2*s;out[1]=a1*c+a3*s;out[2]=a0*-s+a2*c;out[3]=a1*-s+a3*c;out[4]=a4;out[5]=a5;return out;};mat2d.scale=function(out,a,v){var a0=a[0],a1=a[1],a2=a[2],a3=a[3],a4=a[4],a5=a[5],v0=v[0],v1=v[1];out[0]=a0*v0;out[1]=a1*v0;out[2]=a2*v1;out[3]=a3*v1;out[4]=a4;out[5]=a5;return out;};mat2d.translate=function(out,a,v){var a0=a[0],a1=a[1],a2=a[2],a3=a[3],a4=a[4],a5=a[5],v0=v[0],v1=v[1];out[0]=a0;out[1]=a1;out[2]=a2;out[3]=a3;out[4]=a0*v0+a2*v1+a4;out[5]=a1*v0+a3*v1+a5;return out;};mat2d.fromRotation=function(out,rad){var s=Math.sin(rad),c=Math.cos(rad);out[0]=c;out[1]=s;out[2]=-s;out[3]=c;out[4]=0;out[5]=0;return out;}
mat2d.fromScaling=function(out,v){out[0]=v[0];out[1]=0;out[2]=0;out[3]=v[1];out[4]=0;out[5]=0;return out;}
mat2d.fromTranslation=function(out,v){out[0]=1;out[1]=0;out[2]=0;out[3]=1;out[4]=v[0];out[5]=v[1];return out;}
mat2d.str=function(a){return'mat2d('+a[0]+', '+a[1]+', '+a[2]+', '+
a[3]+', '+a[4]+', '+a[5]+')';};mat2d.frob=function(a){return(Math.sqrt(Math.pow(a[0],2)+Math.pow(a[1],2)+Math.pow(a[2],2)+Math.pow(a[3],2)+Math.pow(a[4],2)+Math.pow(a[5],2)+1))};mat2d.add=function(out,a,b){out[0]=a[0]+b[0];out[1]=a[1]+b[1];out[2]=a[2]+b[2];out[3]=a[3]+b[3];out[4]=a[4]+b[4];out[5]=a[5]+b[5];return out;};mat2d.subtract=function(out,a,b){out[0]=a[0]-b[0];out[1]=a[1]-b[1];out[2]=a[2]-b[2];out[3]=a[3]-b[3];out[4]=a[4]-b[4];out[5]=a[5]-b[5];return out;};mat2d.sub=mat2d.subtract;mat2d.multiplyScalar=function(out,a,b){out[0]=a[0]*b;out[1]=a[1]*b;out[2]=a[2]*b;out[3]=a[3]*b;out[4]=a[4]*b;out[5]=a[5]*b;return out;};mat2d.multiplyScalarAndAdd=function(out,a,b,scale){out[0]=a[0]+(b[0]*scale);out[1]=a[1]+(b[1]*scale);out[2]=a[2]+(b[2]*scale);out[3]=a[3]+(b[3]*scale);out[4]=a[4]+(b[4]*scale);out[5]=a[5]+(b[5]*scale);return out;};mat2d.exactEquals=function(a,b){return a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5];};mat2d.equals=function(a,b){var a0=a[0],a1=a[1],a2=a[2],a3=a[3],a4=a[4],a5=a[5];var b0=b[0],b1=b[1],b2=b[2],b3=b[3],b4=b[4],b5=b[5];return(Math.abs(a0-b0)<=glMatrix.EPSILON*Math.max(1.0,Math.abs(a0),Math.abs(b0))&&Math.abs(a1-b1)<=glMatrix.EPSILON*Math.max(1.0,Math.abs(a1),Math.abs(b1))&&Math.abs(a2-b2)<=glMatrix.EPSILON*Math.max(1.0,Math.abs(a2),Math.abs(b2))&&Math.abs(a3-b3)<=glMatrix.EPSILON*Math.max(1.0,Math.abs(a3),Math.abs(b3))&&Math.abs(a4-b4)<=glMatrix.EPSILON*Math.max(1.0,Math.abs(a4),Math.abs(b4))&&Math.abs(a5-b5)<=glMatrix.EPSILON*Math.max(1.0,Math.abs(a5),Math.abs(b5)));};module.exports=mat2d;},{"./common.js":238}],241:[function(require,module,exports){var glMatrix=require("./common.js");var mat3={};mat3.create=function(){var out=new glMatrix.ARRAY_TYPE(9);out[0]=1;out[1]=0;out[2]=0;out[3]=0;out[4]=1;out[5]=0;out[6]=0;out[7]=0;out[8]=1;return out;};mat3.fromMat4=function(out,a){out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[4];out[4]=a[5];out[5]=a[6];out[6]=a[8];out[7]=a[9];out[8]=a[10];return out;};mat3.clone=function(a){var out=new glMatrix.ARRAY_TYPE(9);out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];out[4]=a[4];out[5]=a[5];out[6]=a[6];out[7]=a[7];out[8]=a[8];return out;};mat3.copy=function(out,a){out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];out[4]=a[4];out[5]=a[5];out[6]=a[6];out[7]=a[7];out[8]=a[8];return out;};mat3.fromValues=function(m00,m01,m02,m10,m11,m12,m20,m21,m22){var out=new glMatrix.ARRAY_TYPE(9);out[0]=m00;out[1]=m01;out[2]=m02;out[3]=m10;out[4]=m11;out[5]=m12;out[6]=m20;out[7]=m21;out[8]=m22;return out;};mat3.set=function(out,m00,m01,m02,m10,m11,m12,m20,m21,m22){out[0]=m00;out[1]=m01;out[2]=m02;out[3]=m10;out[4]=m11;out[5]=m12;out[6]=m20;out[7]=m21;out[8]=m22;return out;};mat3.identity=function(out){out[0]=1;out[1]=0;out[2]=0;out[3]=0;out[4]=1;out[5]=0;out[6]=0;out[7]=0;out[8]=1;return out;};mat3.transpose=function(out,a){if(out===a){var a01=a[1],a02=a[2],a12=a[5];out[1]=a[3];out[2]=a[6];out[3]=a01;out[5]=a[7];out[6]=a02;out[7]=a12;}else{out[0]=a[0];out[1]=a[3];out[2]=a[6];out[3]=a[1];out[4]=a[4];out[5]=a[7];out[6]=a[2];out[7]=a[5];out[8]=a[8];}
return out;};mat3.invert=function(out,a){var a00=a[0],a01=a[1],a02=a[2],a10=a[3],a11=a[4],a12=a[5],a20=a[6],a21=a[7],a22=a[8],b01=a22*a11-a12*a21,b11=-a22*a10+a12*a20,b21=a21*a10-a11*a20,det=a00*b01+a01*b11+a02*b21;if(!det){return null;}
det=1.0/det;out[0]=b01*det;out[1]=(-a22*a01+a02*a21)*det;out[2]=(a12*a01-a02*a11)*det;out[3]=b11*det;out[4]=(a22*a00-a02*a20)*det;out[5]=(-a12*a00+a02*a10)*det;out[6]=b21*det;out[7]=(-a21*a00+a01*a20)*det;out[8]=(a11*a00-a01*a10)*det;return out;};mat3.adjoint=function(out,a){var a00=a[0],a01=a[1],a02=a[2],a10=a[3],a11=a[4],a12=a[5],a20=a[6],a21=a[7],a22=a[8];out[0]=(a11*a22-a12*a21);out[1]=(a02*a21-a01*a22);out[2]=(a01*a12-a02*a11);out[3]=(a12*a20-a10*a22);out[4]=(a00*a22-a02*a20);out[5]=(a02*a10-a00*a12);out[6]=(a10*a21-a11*a20);out[7]=(a01*a20-a00*a21);out[8]=(a00*a11-a01*a10);return out;};mat3.determinant=function(a){var a00=a[0],a01=a[1],a02=a[2],a10=a[3],a11=a[4],a12=a[5],a20=a[6],a21=a[7],a22=a[8];return a00*(a22*a11-a12*a21)+a01*(-a22*a10+a12*a20)+a02*(a21*a10-a11*a20);};mat3.multiply=function(out,a,b){var a00=a[0],a01=a[1],a02=a[2],a10=a[3],a11=a[4],a12=a[5],a20=a[6],a21=a[7],a22=a[8],b00=b[0],b01=b[1],b02=b[2],b10=b[3],b11=b[4],b12=b[5],b20=b[6],b21=b[7],b22=b[8];out[0]=b00*a00+b01*a10+b02*a20;out[1]=b00*a01+b01*a11+b02*a21;out[2]=b00*a02+b01*a12+b02*a22;out[3]=b10*a00+b11*a10+b12*a20;out[4]=b10*a01+b11*a11+b12*a21;out[5]=b10*a02+b11*a12+b12*a22;out[6]=b20*a00+b21*a10+b22*a20;out[7]=b20*a01+b21*a11+b22*a21;out[8]=b20*a02+b21*a12+b22*a22;return out;};mat3.mul=mat3.multiply;mat3.translate=function(out,a,v){var a00=a[0],a01=a[1],a02=a[2],a10=a[3],a11=a[4],a12=a[5],a20=a[6],a21=a[7],a22=a[8],x=v[0],y=v[1];out[0]=a00;out[1]=a01;out[2]=a02;out[3]=a10;out[4]=a11;out[5]=a12;out[6]=x*a00+y*a10+a20;out[7]=x*a01+y*a11+a21;out[8]=x*a02+y*a12+a22;return out;};mat3.rotate=function(out,a,rad){var a00=a[0],a01=a[1],a02=a[2],a10=a[3],a11=a[4],a12=a[5],a20=a[6],a21=a[7],a22=a[8],s=Math.sin(rad),c=Math.cos(rad);out[0]=c*a00+s*a10;out[1]=c*a01+s*a11;out[2]=c*a02+s*a12;out[3]=c*a10-s*a00;out[4]=c*a11-s*a01;out[5]=c*a12-s*a02;out[6]=a20;out[7]=a21;out[8]=a22;return out;};mat3.scale=function(out,a,v){var x=v[0],y=v[1];out[0]=x*a[0];out[1]=x*a[1];out[2]=x*a[2];out[3]=y*a[3];out[4]=y*a[4];out[5]=y*a[5];out[6]=a[6];out[7]=a[7];out[8]=a[8];return out;};mat3.fromTranslation=function(out,v){out[0]=1;out[1]=0;out[2]=0;out[3]=0;out[4]=1;out[5]=0;out[6]=v[0];out[7]=v[1];out[8]=1;return out;}
mat3.fromRotation=function(out,rad){var s=Math.sin(rad),c=Math.cos(rad);out[0]=c;out[1]=s;out[2]=0;out[3]=-s;out[4]=c;out[5]=0;out[6]=0;out[7]=0;out[8]=1;return out;}
mat3.fromScaling=function(out,v){out[0]=v[0];out[1]=0;out[2]=0;out[3]=0;out[4]=v[1];out[5]=0;out[6]=0;out[7]=0;out[8]=1;return out;}
mat3.fromMat2d=function(out,a){out[0]=a[0];out[1]=a[1];out[2]=0;out[3]=a[2];out[4]=a[3];out[5]=0;out[6]=a[4];out[7]=a[5];out[8]=1;return out;};mat3.fromQuat=function(out,q){var x=q[0],y=q[1],z=q[2],w=q[3],x2=x+x,y2=y+y,z2=z+z,xx=x*x2,yx=y*x2,yy=y*y2,zx=z*x2,zy=z*y2,zz=z*z2,wx=w*x2,wy=w*y2,wz=w*z2;out[0]=1-yy-zz;out[3]=yx-wz;out[6]=zx+wy;out[1]=yx+wz;out[4]=1-xx-zz;out[7]=zy-wx;out[2]=zx-wy;out[5]=zy+wx;out[8]=1-xx-yy;return out;};mat3.normalFromMat4=function(out,a){var a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32,det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;if(!det){return null;}
det=1.0/det;out[0]=(a11*b11-a12*b10+a13*b09)*det;out[1]=(a12*b08-a10*b11-a13*b07)*det;out[2]=(a10*b10-a11*b08+a13*b06)*det;out[3]=(a02*b10-a01*b11-a03*b09)*det;out[4]=(a00*b11-a02*b08+a03*b07)*det;out[5]=(a01*b08-a00*b10-a03*b06)*det;out[6]=(a31*b05-a32*b04+a33*b03)*det;out[7]=(a32*b02-a30*b05-a33*b01)*det;out[8]=(a30*b04-a31*b02+a33*b00)*det;return out;};mat3.str=function(a){return'mat3('+a[0]+', '+a[1]+', '+a[2]+', '+
a[3]+', '+a[4]+', '+a[5]+', '+
a[6]+', '+a[7]+', '+a[8]+')';};mat3.frob=function(a){return(Math.sqrt(Math.pow(a[0],2)+Math.pow(a[1],2)+Math.pow(a[2],2)+Math.pow(a[3],2)+Math.pow(a[4],2)+Math.pow(a[5],2)+Math.pow(a[6],2)+Math.pow(a[7],2)+Math.pow(a[8],2)))};mat3.add=function(out,a,b){out[0]=a[0]+b[0];out[1]=a[1]+b[1];out[2]=a[2]+b[2];out[3]=a[3]+b[3];out[4]=a[4]+b[4];out[5]=a[5]+b[5];out[6]=a[6]+b[6];out[7]=a[7]+b[7];out[8]=a[8]+b[8];return out;};mat3.subtract=function(out,a,b){out[0]=a[0]-b[0];out[1]=a[1]-b[1];out[2]=a[2]-b[2];out[3]=a[3]-b[3];out[4]=a[4]-b[4];out[5]=a[5]-b[5];out[6]=a[6]-b[6];out[7]=a[7]-b[7];out[8]=a[8]-b[8];return out;};mat3.sub=mat3.subtract;mat3.multiplyScalar=function(out,a,b){out[0]=a[0]*b;out[1]=a[1]*b;out[2]=a[2]*b;out[3]=a[3]*b;out[4]=a[4]*b;out[5]=a[5]*b;out[6]=a[6]*b;out[7]=a[7]*b;out[8]=a[8]*b;return out;};mat3.multiplyScalarAndAdd=function(out,a,b,scale){out[0]=a[0]+(b[0]*scale);out[1]=a[1]+(b[1]*scale);out[2]=a[2]+(b[2]*scale);out[3]=a[3]+(b[3]*scale);out[4]=a[4]+(b[4]*scale);out[5]=a[5]+(b[5]*scale);out[6]=a[6]+(b[6]*scale);out[7]=a[7]+(b[7]*scale);out[8]=a[8]+(b[8]*scale);return out;};mat3.exactEquals=function(a,b){return a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8];};mat3.equals=function(a,b){var a0=a[0],a1=a[1],a2=a[2],a3=a[3],a4=a[4],a5=a[5],a6=a[6],a7=a[7],a8=a[8];var b0=b[0],b1=b[1],b2=b[2],b3=b[3],b4=b[4],b5=b[5],b6=a[6],b7=b[7],b8=b[8];return(Math.abs(a0-b0)<=glMatrix.EPSILON*Math.max(1.0,Math.abs(a0),Math.abs(b0))&&Math.abs(a1-b1)<=glMatrix.EPSILON*Math.max(1.0,Math.abs(a1),Math.abs(b1))&&Math.abs(a2-b2)<=glMatrix.EPSILON*Math.max(1.0,Math.abs(a2),Math.abs(b2))&&Math.abs(a3-b3)<=glMatrix.EPSILON*Math.max(1.0,Math.abs(a3),Math.abs(b3))&&Math.abs(a4-b4)<=glMatrix.EPSILON*Math.max(1.0,Math.abs(a4),Math.abs(b4))&&Math.abs(a5-b5)<=glMatrix.EPSILON*Math.max(1.0,Math.abs(a5),Math.abs(b5))&&Math.abs(a6-b6)<=glMatrix.EPSILON*Math.max(1.0,Math.abs(a6),Math.abs(b6))&&Math.abs(a7-b7)<=glMatrix.EPSILON*Math.max(1.0,Math.abs(a7),Math.abs(b7))&&Math.abs(a8-b8)<=glMatrix.EPSILON*Math.max(1.0,Math.abs(a8),Math.abs(b8)));};module.exports=mat3;},{"./common.js":238}],242:[function(require,module,exports){var glMatrix=require("./common.js");var mat4={scalar:{},SIMD:{},};mat4.create=function(){var out=new glMatrix.ARRAY_TYPE(16);out[0]=1;out[1]=0;out[2]=0;out[3]=0;out[4]=0;out[5]=1;out[6]=0;out[7]=0;out[8]=0;out[9]=0;out[10]=1;out[11]=0;out[12]=0;out[13]=0;out[14]=0;out[15]=1;return out;};mat4.clone=function(a){var out=new glMatrix.ARRAY_TYPE(16);out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];out[4]=a[4];out[5]=a[5];out[6]=a[6];out[7]=a[7];out[8]=a[8];out[9]=a[9];out[10]=a[10];out[11]=a[11];out[12]=a[12];out[13]=a[13];out[14]=a[14];out[15]=a[15];return out;};mat4.copy=function(out,a){out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];out[4]=a[4];out[5]=a[5];out[6]=a[6];out[7]=a[7];out[8]=a[8];out[9]=a[9];out[10]=a[10];out[11]=a[11];out[12]=a[12];out[13]=a[13];out[14]=a[14];out[15]=a[15];return out;};mat4.fromValues=function(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33){var out=new glMatrix.ARRAY_TYPE(16);out[0]=m00;out[1]=m01;out[2]=m02;out[3]=m03;out[4]=m10;out[5]=m11;out[6]=m12;out[7]=m13;out[8]=m20;out[9]=m21;out[10]=m22;out[11]=m23;out[12]=m30;out[13]=m31;out[14]=m32;out[15]=m33;return out;};mat4.set=function(out,m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33){out[0]=m00;out[1]=m01;out[2]=m02;out[3]=m03;out[4]=m10;out[5]=m11;out[6]=m12;out[7]=m13;out[8]=m20;out[9]=m21;out[10]=m22;out[11]=m23;out[12]=m30;out[13]=m31;out[14]=m32;out[15]=m33;return out;};mat4.identity=function(out){out[0]=1;out[1]=0;out[2]=0;out[3]=0;out[4]=0;out[5]=1;out[6]=0;out[7]=0;out[8]=0;out[9]=0;out[10]=1;out[11]=0;out[12]=0;out[13]=0;out[14]=0;out[15]=1;return out;};mat4.scalar.transpose=function(out,a){if(out===a){var a01=a[1],a02=a[2],a03=a[3],a12=a[6],a13=a[7],a23=a[11];out[1]=a[4];out[2]=a[8];out[3]=a[12];out[4]=a01;out[6]=a[9];out[7]=a[13];out[8]=a02;out[9]=a12;out[11]=a[14];out[12]=a03;out[13]=a13;out[14]=a23;}else{out[0]=a[0];out[1]=a[4];out[2]=a[8];out[3]=a[12];out[4]=a[1];out[5]=a[5];out[6]=a[9];out[7]=a[13];out[8]=a[2];out[9]=a[6];out[10]=a[10];out[11]=a[14];out[12]=a[3];out[13]=a[7];out[14]=a[11];out[15]=a[15];}
return out;};mat4.SIMD.transpose=function(out,a){var a0,a1,a2,a3,tmp01,tmp23,out0,out1,out2,out3;a0=SIMD.Float32x4.load(a,0);a1=SIMD.Float32x4.load(a,4);a2=SIMD.Float32x4.load(a,8);a3=SIMD.Float32x4.load(a,12);tmp01=SIMD.Float32x4.shuffle(a0,a1,0,1,4,5);tmp23=SIMD.Float32x4.shuffle(a2,a3,0,1,4,5);out0=SIMD.Float32x4.shuffle(tmp01,tmp23,0,2,4,6);out1=SIMD.Float32x4.shuffle(tmp01,tmp23,1,3,5,7);SIMD.Float32x4.store(out,0,out0);SIMD.Float32x4.store(out,4,out1);tmp01=SIMD.Float32x4.shuffle(a0,a1,2,3,6,7);tmp23=SIMD.Float32x4.shuffle(a2,a3,2,3,6,7);out2=SIMD.Float32x4.shuffle(tmp01,tmp23,0,2,4,6);out3=SIMD.Float32x4.shuffle(tmp01,tmp23,1,3,5,7);SIMD.Float32x4.store(out,8,out2);SIMD.Float32x4.store(out,12,out3);return out;};mat4.transpose=glMatrix.USE_SIMD?mat4.SIMD.transpose:mat4.scalar.transpose;mat4.scalar.invert=function(out,a){var a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32,det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;if(!det){return null;}
det=1.0/det;out[0]=(a11*b11-a12*b10+a13*b09)*det;out[1]=(a02*b10-a01*b11-a03*b09)*det;out[2]=(a31*b05-a32*b04+a33*b03)*det;out[3]=(a22*b04-a21*b05-a23*b03)*det;out[4]=(a12*b08-a10*b11-a13*b07)*det;out[5]=(a00*b11-a02*b08+a03*b07)*det;out[6]=(a32*b02-a30*b05-a33*b01)*det;out[7]=(a20*b05-a22*b02+a23*b01)*det;out[8]=(a10*b10-a11*b08+a13*b06)*det;out[9]=(a01*b08-a00*b10-a03*b06)*det;out[10]=(a30*b04-a31*b02+a33*b00)*det;out[11]=(a21*b02-a20*b04-a23*b00)*det;out[12]=(a11*b07-a10*b09-a12*b06)*det;out[13]=(a00*b09-a01*b07+a02*b06)*det;out[14]=(a31*b01-a30*b03-a32*b00)*det;out[15]=(a20*b03-a21*b01+a22*b00)*det;return out;};mat4.SIMD.invert=function(out,a){var row0,row1,row2,row3,tmp1,minor0,minor1,minor2,minor3,det,a0=SIMD.Float32x4.load(a,0),a1=SIMD.Float32x4.load(a,4),a2=SIMD.Float32x4.load(a,8),a3=SIMD.Float32x4.load(a,12);tmp1=SIMD.Float32x4.shuffle(a0,a1,0,1,4,5);row1=SIMD.Float32x4.shuffle(a2,a3,0,1,4,5);row0=SIMD.Float32x4.shuffle(tmp1,row1,0,2,4,6);row1=SIMD.Float32x4.shuffle(row1,tmp1,1,3,5,7);tmp1=SIMD.Float32x4.shuffle(a0,a1,2,3,6,7);row3=SIMD.Float32x4.shuffle(a2,a3,2,3,6,7);row2=SIMD.Float32x4.shuffle(tmp1,row3,0,2,4,6);row3=SIMD.Float32x4.shuffle(row3,tmp1,1,3,5,7);tmp1=SIMD.Float32x4.mul(row2,row3);tmp1=SIMD.Float32x4.swizzle(tmp1,1,0,3,2);minor0=SIMD.Float32x4.mul(row1,tmp1);minor1=SIMD.Float32x4.mul(row0,tmp1);tmp1=SIMD.Float32x4.swizzle(tmp1,2,3,0,1);minor0=SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1,tmp1),minor0);minor1=SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0,tmp1),minor1);minor1=SIMD.Float32x4.swizzle(minor1,2,3,0,1);tmp1=SIMD.Float32x4.mul(row1,row2);tmp1=SIMD.Float32x4.swizzle(tmp1,1,0,3,2);minor0=SIMD.Float32x4.add(SIMD.Float32x4.mul(row3,tmp1),minor0);minor3=SIMD.Float32x4.mul(row0,tmp1);tmp1=SIMD.Float32x4.swizzle(tmp1,2,3,0,1);minor0=SIMD.Float32x4.sub(minor0,SIMD.Float32x4.mul(row3,tmp1));minor3=SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0,tmp1),minor3);minor3=SIMD.Float32x4.swizzle(minor3,2,3,0,1);tmp1=SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1,2,3,0,1),row3);tmp1=SIMD.Float32x4.swizzle(tmp1,1,0,3,2);row2=SIMD.Float32x4.swizzle(row2,2,3,0,1);minor0=SIMD.Float32x4.add(SIMD.Float32x4.mul(row2,tmp1),minor0);minor2=SIMD.Float32x4.mul(row0,tmp1);tmp1=SIMD.Float32x4.swizzle(tmp1,2,3,0,1);minor0=SIMD.Float32x4.sub(minor0,SIMD.Float32x4.mul(row2,tmp1));minor2=SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0,tmp1),minor2);minor2=SIMD.Float32x4.swizzle(minor2,2,3,0,1);tmp1=SIMD.Float32x4.mul(row0,row1);tmp1=SIMD.Float32x4.swizzle(tmp1,1,0,3,2);minor2=SIMD.Float32x4.add(SIMD.Float32x4.mul(row3,tmp1),minor2);minor3=SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2,tmp1),minor3);tmp1=SIMD.Float32x4.swizzle(tmp1,2,3,0,1);minor2=SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3,tmp1),minor2);minor3=SIMD.Float32x4.sub(minor3,SIMD.Float32x4.mul(row2,tmp1));tmp1=SIMD.Float32x4.mul(row0,row3);tmp1=SIMD.Float32x4.swizzle(tmp1,1,0,3,2);minor1=SIMD.Float32x4.sub(minor1,SIMD.Float32x4.mul(row2,tmp1));minor2=SIMD.Float32x4.add(SIMD.Float32x4.mul(row1,tmp1),minor2);tmp1=SIMD.Float32x4.swizzle(tmp1,2,3,0,1);minor1=SIMD.Float32x4.add(SIMD.Float32x4.mul(row2,tmp1),minor1);minor2=SIMD.Float32x4.sub(minor2,SIMD.Float32x4.mul(row1,tmp1));tmp1=SIMD.Float32x4.mul(row0,row2);tmp1=SIMD.Float32x4.swizzle(tmp1,1,0,3,2);minor1=SIMD.Float32x4.add(SIMD.Float32x4.mul(row3,tmp1),minor1);minor3=SIMD.Float32x4.sub(minor3,SIMD.Float32x4.mul(row1,tmp1));tmp1=SIMD.Float32x4.swizzle(tmp1,2,3,0,1);minor1=SIMD.Float32x4.sub(minor1,SIMD.Float32x4.mul(row3,tmp1));minor3=SIMD.Float32x4.add(SIMD.Float32x4.mul(row1,tmp1),minor3);det=SIMD.Float32x4.mul(row0,minor0);det=SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det,2,3,0,1),det);det=SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det,1,0,3,2),det);tmp1=SIMD.Float32x4.reciprocalApproximation(det);det=SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1,tmp1),SIMD.Float32x4.mul(det,SIMD.Float32x4.mul(tmp1,tmp1)));det=SIMD.Float32x4.swizzle(det,0,0,0,0);if(!det){return null;}
SIMD.Float32x4.store(out,0,SIMD.Float32x4.mul(det,minor0));SIMD.Float32x4.store(out,4,SIMD.Float32x4.mul(det,minor1));SIMD.Float32x4.store(out,8,SIMD.Float32x4.mul(det,minor2));SIMD.Float32x4.store(out,12,SIMD.Float32x4.mul(det,minor3));return out;}
mat4.invert=glMatrix.USE_SIMD?mat4.SIMD.invert:mat4.scalar.invert;mat4.scalar.adjoint=function(out,a){var a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];out[0]=(a11*(a22*a33-a23*a32)-a21*(a12*a33-a13*a32)+a31*(a12*a23-a13*a22));out[1]=-(a01*(a22*a33-a23*a32)-a21*(a02*a33-a03*a32)+a31*(a02*a23-a03*a22));out[2]=(a01*(a12*a33-a13*a32)-a11*(a02*a33-a03*a32)+a31*(a02*a13-a03*a12));out[3]=-(a01*(a12*a23-a13*a22)-a11*(a02*a23-a03*a22)+a21*(a02*a13-a03*a12));out[4]=-(a10*(a22*a33-a23*a32)-a20*(a12*a33-a13*a32)+a30*(a12*a23-a13*a22));out[5]=(a00*(a22*a33-a23*a32)-a20*(a02*a33-a03*a32)+a30*(a02*a23-a03*a22));out[6]=-(a00*(a12*a33-a13*a32)-a10*(a02*a33-a03*a32)+a30*(a02*a13-a03*a12));out[7]=(a00*(a12*a23-a13*a22)-a10*(a02*a23-a03*a22)+a20*(a02*a13-a03*a12));out[8]=(a10*(a21*a33-a23*a31)-a20*(a11*a33-a13*a31)+a30*(a11*a23-a13*a21));out[9]=-(a00*(a21*a33-a23*a31)-a20*(a01*a33-a03*a31)+a30*(a01*a23-a03*a21));out[10]=(a00*(a11*a33-a13*a31)-a10*(a01*a33-a03*a31)+a30*(a01*a13-a03*a11));out[11]=-(a00*(a11*a23-a13*a21)-a10*(a01*a23-a03*a21)+a20*(a01*a13-a03*a11));out[12]=-(a10*(a21*a32-a22*a31)-a20*(a11*a32-a12*a31)+a30*(a11*a22-a12*a21));out[13]=(a00*(a21*a32-a22*a31)-a20*(a01*a32-a02*a31)+a30*(a01*a22-a02*a21));out[14]=-(a00*(a11*a32-a12*a31)-a10*(a01*a32-a02*a31)+a30*(a01*a12-a02*a11));out[15]=(a00*(a11*a22-a12*a21)-a10*(a01*a22-a02*a21)+a20*(a01*a12-a02*a11));return out;};mat4.SIMD.adjoint=function(out,a){var a0,a1,a2,a3;var row0,row1,row2,row3;var tmp1;var minor0,minor1,minor2,minor3;var a0=SIMD.Float32x4.load(a,0);var a1=SIMD.Float32x4.load(a,4);var a2=SIMD.Float32x4.load(a,8);var a3=SIMD.Float32x4.load(a,12);tmp1=SIMD.Float32x4.shuffle(a0,a1,0,1,4,5);row1=SIMD.Float32x4.shuffle(a2,a3,0,1,4,5);row0=SIMD.Float32x4.shuffle(tmp1,row1,0,2,4,6);row1=SIMD.Float32x4.shuffle(row1,tmp1,1,3,5,7);tmp1=SIMD.Float32x4.shuffle(a0,a1,2,3,6,7);row3=SIMD.Float32x4.shuffle(a2,a3,2,3,6,7);row2=SIMD.Float32x4.shuffle(tmp1,row3,0,2,4,6);row3=SIMD.Float32x4.shuffle(row3,tmp1,1,3,5,7);tmp1=SIMD.Float32x4.mul(row2,row3);tmp1=SIMD.Float32x4.swizzle(tmp1,1,0,3,2);minor0=SIMD.Float32x4.mul(row1,tmp1);minor1=SIMD.Float32x4.mul(row0,tmp1);tmp1=SIMD.Float32x4.swizzle(tmp1,2,3,0,1);minor0=SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1,tmp1),minor0);minor1=SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0,tmp1),minor1);minor1=SIMD.Float32x4.swizzle(minor1,2,3,0,1);tmp1=SIMD.Float32x4.mul(row1,row2);tmp1=SIMD.Float32x4.swizzle(tmp1,1,0,3,2);minor0=SIMD.Float32x4.add(SIMD.Float32x4.mul(row3,tmp1),minor0);minor3=SIMD.Float32x4.mul(row0,tmp1);tmp1=SIMD.Float32x4.swizzle(tmp1,2,3,0,1);minor0=SIMD.Float32x4.sub(minor0,SIMD.Float32x4.mul(row3,tmp1));minor3=SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0,tmp1),minor3);minor3=SIMD.Float32x4.swizzle(minor3,2,3,0,1);tmp1=SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1,2,3,0,1),row3);tmp1=SIMD.Float32x4.swizzle(tmp1,1,0,3,2);row2=SIMD.Float32x4.swizzle(row2,2,3,0,1);minor0=SIMD.Float32x4.add(SIMD.Float32x4.mul(row2,tmp1),minor0);minor2=SIMD.Float32x4.mul(row0,tmp1);tmp1=SIMD.Float32x4.swizzle(tmp1,2,3,0,1);minor0=SIMD.Float32x4.sub(minor0,SIMD.Float32x4.mul(row2,tmp1));minor2=SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0,tmp1),minor2);minor2=SIMD.Float32x4.swizzle(minor2,2,3,0,1);tmp1=SIMD.Float32x4.mul(row0,row1);tmp1=SIMD.Float32x4.swizzle(tmp1,1,0,3,2);minor2=SIMD.Float32x4.add(SIMD.Float32x4.mul(row3,tmp1),minor2);minor3=SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2,tmp1),minor3);tmp1=SIMD.Float32x4.swizzle(tmp1,2,3,0,1);minor2=SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3,tmp1),minor2);minor3=SIMD.Float32x4.sub(minor3,SIMD.Float32x4.mul(row2,tmp1));tmp1=SIMD.Float32x4.mul(row0,row3);tmp1=SIMD.Float32x4.swizzle(tmp1,1,0,3,2);minor1=SIMD.Float32x4.sub(minor1,SIMD.Float32x4.mul(row2,tmp1));minor2=SIMD.Float32x4.add(SIMD.Float32x4.mul(row1,tmp1),minor2);tmp1=SIMD.Float32x4.swizzle(tmp1,2,3,0,1);minor1=SIMD.Float32x4.add(SIMD.Float32x4.mul(row2,tmp1),minor1);minor2=SIMD.Float32x4.sub(minor2,SIMD.Float32x4.mul(row1,tmp1));tmp1=SIMD.Float32x4.mul(row0,row2);tmp1=SIMD.Float32x4.swizzle(tmp1,1,0,3,2);minor1=SIMD.Float32x4.add(SIMD.Float32x4.mul(row3,tmp1),minor1);minor3=SIMD.Float32x4.sub(minor3,SIMD.Float32x4.mul(row1,tmp1));tmp1=SIMD.Float32x4.swizzle(tmp1,2,3,0,1);minor1=SIMD.Float32x4.sub(minor1,SIMD.Float32x4.mul(row3,tmp1));minor3=SIMD.Float32x4.add(SIMD.Float32x4.mul(row1,tmp1),minor3);SIMD.Float32x4.store(out,0,minor0);SIMD.Float32x4.store(out,4,minor1);SIMD.Float32x4.store(out,8,minor2);SIMD.Float32x4.store(out,12,minor3);return out;};mat4.adjoint=glMatrix.USE_SIMD?mat4.SIMD.adjoint:mat4.scalar.adjoint;mat4.determinant=function(a){var a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;return b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;};mat4.SIMD.multiply=function(out,a,b){var a0=SIMD.Float32x4.load(a,0);var a1=SIMD.Float32x4.load(a,4);var a2=SIMD.Float32x4.load(a,8);var a3=SIMD.Float32x4.load(a,12);var b0=SIMD.Float32x4.load(b,0);var out0=SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b0,0,0,0,0),a0),SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b0,1,1,1,1),a1),SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b0,2,2,2,2),a2),SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b0,3,3,3,3),a3))));SIMD.Float32x4.store(out,0,out0);var b1=SIMD.Float32x4.load(b,4);var out1=SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b1,0,0,0,0),a0),SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b1,1,1,1,1),a1),SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b1,2,2,2,2),a2),SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b1,3,3,3,3),a3))));SIMD.Float32x4.store(out,4,out1);var b2=SIMD.Float32x4.load(b,8);var out2=SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b2,0,0,0,0),a0),SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b2,1,1,1,1),a1),SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b2,2,2,2,2),a2),SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b2,3,3,3,3),a3))));SIMD.Float32x4.store(out,8,out2);var b3=SIMD.Float32x4.load(b,12);var out3=SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b3,0,0,0,0),a0),SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b3,1,1,1,1),a1),SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b3,2,2,2,2),a2),SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b3,3,3,3,3),a3))));SIMD.Float32x4.store(out,12,out3);return out;};mat4.scalar.multiply=function(out,a,b){var a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];var b0=b[0],b1=b[1],b2=b[2],b3=b[3];out[0]=b0*a00+b1*a10+b2*a20+b3*a30;out[1]=b0*a01+b1*a11+b2*a21+b3*a31;out[2]=b0*a02+b1*a12+b2*a22+b3*a32;out[3]=b0*a03+b1*a13+b2*a23+b3*a33;b0=b[4];b1=b[5];b2=b[6];b3=b[7];out[4]=b0*a00+b1*a10+b2*a20+b3*a30;out[5]=b0*a01+b1*a11+b2*a21+b3*a31;out[6]=b0*a02+b1*a12+b2*a22+b3*a32;out[7]=b0*a03+b1*a13+b2*a23+b3*a33;b0=b[8];b1=b[9];b2=b[10];b3=b[11];out[8]=b0*a00+b1*a10+b2*a20+b3*a30;out[9]=b0*a01+b1*a11+b2*a21+b3*a31;out[10]=b0*a02+b1*a12+b2*a22+b3*a32;out[11]=b0*a03+b1*a13+b2*a23+b3*a33;b0=b[12];b1=b[13];b2=b[14];b3=b[15];out[12]=b0*a00+b1*a10+b2*a20+b3*a30;out[13]=b0*a01+b1*a11+b2*a21+b3*a31;out[14]=b0*a02+b1*a12+b2*a22+b3*a32;out[15]=b0*a03+b1*a13+b2*a23+b3*a33;return out;};mat4.multiply=glMatrix.USE_SIMD?mat4.SIMD.multiply:mat4.scalar.multiply;mat4.mul=mat4.multiply;mat4.scalar.translate=function(out,a,v){var x=v[0],y=v[1],z=v[2],a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;if(a===out){out[12]=a[0]*x+a[4]*y+a[8]*z+a[12];out[13]=a[1]*x+a[5]*y+a[9]*z+a[13];out[14]=a[2]*x+a[6]*y+a[10]*z+a[14];out[15]=a[3]*x+a[7]*y+a[11]*z+a[15];}else{a00=a[0];a01=a[1];a02=a[2];a03=a[3];a10=a[4];a11=a[5];a12=a[6];a13=a[7];a20=a[8];a21=a[9];a22=a[10];a23=a[11];out[0]=a00;out[1]=a01;out[2]=a02;out[3]=a03;out[4]=a10;out[5]=a11;out[6]=a12;out[7]=a13;out[8]=a20;out[9]=a21;out[10]=a22;out[11]=a23;out[12]=a00*x+a10*y+a20*z+a[12];out[13]=a01*x+a11*y+a21*z+a[13];out[14]=a02*x+a12*y+a22*z+a[14];out[15]=a03*x+a13*y+a23*z+a[15];}
return out;};mat4.SIMD.translate=function(out,a,v){var a0=SIMD.Float32x4.load(a,0),a1=SIMD.Float32x4.load(a,4),a2=SIMD.Float32x4.load(a,8),a3=SIMD.Float32x4.load(a,12),vec=SIMD.Float32x4(v[0],v[1],v[2],0);if(a!==out){out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];out[4]=a[4];out[5]=a[5];out[6]=a[6];out[7]=a[7];out[8]=a[8];out[9]=a[9];out[10]=a[10];out[11]=a[11];}
a0=SIMD.Float32x4.mul(a0,SIMD.Float32x4.swizzle(vec,0,0,0,0));a1=SIMD.Float32x4.mul(a1,SIMD.Float32x4.swizzle(vec,1,1,1,1));a2=SIMD.Float32x4.mul(a2,SIMD.Float32x4.swizzle(vec,2,2,2,2));var t0=SIMD.Float32x4.add(a0,SIMD.Float32x4.add(a1,SIMD.Float32x4.add(a2,a3)));SIMD.Float32x4.store(out,12,t0);return out;};mat4.translate=glMatrix.USE_SIMD?mat4.SIMD.translate:mat4.scalar.translate;mat4.scalar.scale=function(out,a,v){var x=v[0],y=v[1],z=v[2];out[0]=a[0]*x;out[1]=a[1]*x;out[2]=a[2]*x;out[3]=a[3]*x;out[4]=a[4]*y;out[5]=a[5]*y;out[6]=a[6]*y;out[7]=a[7]*y;out[8]=a[8]*z;out[9]=a[9]*z;out[10]=a[10]*z;out[11]=a[11]*z;out[12]=a[12];out[13]=a[13];out[14]=a[14];out[15]=a[15];return out;};mat4.SIMD.scale=function(out,a,v){var a0,a1,a2;var vec=SIMD.Float32x4(v[0],v[1],v[2],0);a0=SIMD.Float32x4.load(a,0);SIMD.Float32x4.store(out,0,SIMD.Float32x4.mul(a0,SIMD.Float32x4.swizzle(vec,0,0,0,0)));a1=SIMD.Float32x4.load(a,4);SIMD.Float32x4.store(out,4,SIMD.Float32x4.mul(a1,SIMD.Float32x4.swizzle(vec,1,1,1,1)));a2=SIMD.Float32x4.load(a,8);SIMD.Float32x4.store(out,8,SIMD.Float32x4.mul(a2,SIMD.Float32x4.swizzle(vec,2,2,2,2)));out[12]=a[12];out[13]=a[13];out[14]=a[14];out[15]=a[15];return out;};mat4.scale=glMatrix.USE_SIMD?mat4.SIMD.scale:mat4.scalar.scale;mat4.rotate=function(out,a,rad,axis){var x=axis[0],y=axis[1],z=axis[2],len=Math.sqrt(x*x+y*y+z*z),s,c,t,a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23,b00,b01,b02,b10,b11,b12,b20,b21,b22;if(Math.abs(len)<glMatrix.EPSILON){return null;}
len=1/len;x*=len;y*=len;z*=len;s=Math.sin(rad);c=Math.cos(rad);t=1-c;a00=a[0];a01=a[1];a02=a[2];a03=a[3];a10=a[4];a11=a[5];a12=a[6];a13=a[7];a20=a[8];a21=a[9];a22=a[10];a23=a[11];b00=x*x*t+c;b01=y*x*t+z*s;b02=z*x*t-y*s;b10=x*y*t-z*s;b11=y*y*t+c;b12=z*y*t+x*s;b20=x*z*t+y*s;b21=y*z*t-x*s;b22=z*z*t+c;out[0]=a00*b00+a10*b01+a20*b02;out[1]=a01*b00+a11*b01+a21*b02;out[2]=a02*b00+a12*b01+a22*b02;out[3]=a03*b00+a13*b01+a23*b02;out[4]=a00*b10+a10*b11+a20*b12;out[5]=a01*b10+a11*b11+a21*b12;out[6]=a02*b10+a12*b11+a22*b12;out[7]=a03*b10+a13*b11+a23*b12;out[8]=a00*b20+a10*b21+a20*b22;out[9]=a01*b20+a11*b21+a21*b22;out[10]=a02*b20+a12*b21+a22*b22;out[11]=a03*b20+a13*b21+a23*b22;if(a!==out){out[12]=a[12];out[13]=a[13];out[14]=a[14];out[15]=a[15];}
return out;};mat4.scalar.rotateX=function(out,a,rad){var s=Math.sin(rad),c=Math.cos(rad),a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11];if(a!==out){out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];out[12]=a[12];out[13]=a[13];out[14]=a[14];out[15]=a[15];}
out[4]=a10*c+a20*s;out[5]=a11*c+a21*s;out[6]=a12*c+a22*s;out[7]=a13*c+a23*s;out[8]=a20*c-a10*s;out[9]=a21*c-a11*s;out[10]=a22*c-a12*s;out[11]=a23*c-a13*s;return out;};mat4.SIMD.rotateX=function(out,a,rad){var s=SIMD.Float32x4.splat(Math.sin(rad)),c=SIMD.Float32x4.splat(Math.cos(rad));if(a!==out){out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];out[12]=a[12];out[13]=a[13];out[14]=a[14];out[15]=a[15];}
var a_1=SIMD.Float32x4.load(a,4);var a_2=SIMD.Float32x4.load(a,8);SIMD.Float32x4.store(out,4,SIMD.Float32x4.add(SIMD.Float32x4.mul(a_1,c),SIMD.Float32x4.mul(a_2,s)));SIMD.Float32x4.store(out,8,SIMD.Float32x4.sub(SIMD.Float32x4.mul(a_2,c),SIMD.Float32x4.mul(a_1,s)));return out;};mat4.rotateX=glMatrix.USE_SIMD?mat4.SIMD.rotateX:mat4.scalar.rotateX;mat4.scalar.rotateY=function(out,a,rad){var s=Math.sin(rad),c=Math.cos(rad),a00=a[0],a01=a[1],a02=a[2],a03=a[3],a20=a[8],a21=a[9],a22=a[10],a23=a[11];if(a!==out){out[4]=a[4];out[5]=a[5];out[6]=a[6];out[7]=a[7];out[12]=a[12];out[13]=a[13];out[14]=a[14];out[15]=a[15];}
out[0]=a00*c-a20*s;out[1]=a01*c-a21*s;out[2]=a02*c-a22*s;out[3]=a03*c-a23*s;out[8]=a00*s+a20*c;out[9]=a01*s+a21*c;out[10]=a02*s+a22*c;out[11]=a03*s+a23*c;return out;};mat4.SIMD.rotateY=function(out,a,rad){var s=SIMD.Float32x4.splat(Math.sin(rad)),c=SIMD.Float32x4.splat(Math.cos(rad));if(a!==out){out[4]=a[4];out[5]=a[5];out[6]=a[6];out[7]=a[7];out[12]=a[12];out[13]=a[13];out[14]=a[14];out[15]=a[15];}
var a_0=SIMD.Float32x4.load(a,0);var a_2=SIMD.Float32x4.load(a,8);SIMD.Float32x4.store(out,0,SIMD.Float32x4.sub(SIMD.Float32x4.mul(a_0,c),SIMD.Float32x4.mul(a_2,s)));SIMD.Float32x4.store(out,8,SIMD.Float32x4.add(SIMD.Float32x4.mul(a_0,s),SIMD.Float32x4.mul(a_2,c)));return out;};mat4.rotateY=glMatrix.USE_SIMD?mat4.SIMD.rotateY:mat4.scalar.rotateY;mat4.scalar.rotateZ=function(out,a,rad){var s=Math.sin(rad),c=Math.cos(rad),a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7];if(a!==out){out[8]=a[8];out[9]=a[9];out[10]=a[10];out[11]=a[11];out[12]=a[12];out[13]=a[13];out[14]=a[14];out[15]=a[15];}
out[0]=a00*c+a10*s;out[1]=a01*c+a11*s;out[2]=a02*c+a12*s;out[3]=a03*c+a13*s;out[4]=a10*c-a00*s;out[5]=a11*c-a01*s;out[6]=a12*c-a02*s;out[7]=a13*c-a03*s;return out;};mat4.SIMD.rotateZ=function(out,a,rad){var s=SIMD.Float32x4.splat(Math.sin(rad)),c=SIMD.Float32x4.splat(Math.cos(rad));if(a!==out){out[8]=a[8];out[9]=a[9];out[10]=a[10];out[11]=a[11];out[12]=a[12];out[13]=a[13];out[14]=a[14];out[15]=a[15];}
var a_0=SIMD.Float32x4.load(a,0);var a_1=SIMD.Float32x4.load(a,4);SIMD.Float32x4.store(out,0,SIMD.Float32x4.add(SIMD.Float32x4.mul(a_0,c),SIMD.Float32x4.mul(a_1,s)));SIMD.Float32x4.store(out,4,SIMD.Float32x4.sub(SIMD.Float32x4.mul(a_1,c),SIMD.Float32x4.mul(a_0,s)));return out;};mat4.rotateZ=glMatrix.USE_SIMD?mat4.SIMD.rotateZ:mat4.scalar.rotateZ;mat4.fromTranslation=function(out,v){out[0]=1;out[1]=0;out[2]=0;out[3]=0;out[4]=0;out[5]=1;out[6]=0;out[7]=0;out[8]=0;out[9]=0;out[10]=1;out[11]=0;out[12]=v[0];out[13]=v[1];out[14]=v[2];out[15]=1;return out;}
mat4.fromScaling=function(out,v){out[0]=v[0];out[1]=0;out[2]=0;out[3]=0;out[4]=0;out[5]=v[1];out[6]=0;out[7]=0;out[8]=0;out[9]=0;out[10]=v[2];out[11]=0;out[12]=0;out[13]=0;out[14]=0;out[15]=1;return out;}
mat4.fromRotation=function(out,rad,axis){var x=axis[0],y=axis[1],z=axis[2],len=Math.sqrt(x*x+y*y+z*z),s,c,t;if(Math.abs(len)<glMatrix.EPSILON){return null;}
len=1/len;x*=len;y*=len;z*=len;s=Math.sin(rad);c=Math.cos(rad);t=1-c;out[0]=x*x*t+c;out[1]=y*x*t+z*s;out[2]=z*x*t-y*s;out[3]=0;out[4]=x*y*t-z*s;out[5]=y*y*t+c;out[6]=z*y*t+x*s;out[7]=0;out[8]=x*z*t+y*s;out[9]=y*z*t-x*s;out[10]=z*z*t+c;out[11]=0;out[12]=0;out[13]=0;out[14]=0;out[15]=1;return out;}
mat4.fromXRotation=function(out,rad){var s=Math.sin(rad),c=Math.cos(rad);out[0]=1;out[1]=0;out[2]=0;out[3]=0;out[4]=0;out[5]=c;out[6]=s;out[7]=0;out[8]=0;out[9]=-s;out[10]=c;out[11]=0;out[12]=0;out[13]=0;out[14]=0;out[15]=1;return out;}
mat4.fromYRotation=function(out,rad){var s=Math.sin(rad),c=Math.cos(rad);out[0]=c;out[1]=0;out[2]=-s;out[3]=0;out[4]=0;out[5]=1;out[6]=0;out[7]=0;out[8]=s;out[9]=0;out[10]=c;out[11]=0;out[12]=0;out[13]=0;out[14]=0;out[15]=1;return out;}
mat4.fromZRotation=function(out,rad){var s=Math.sin(rad),c=Math.cos(rad);out[0]=c;out[1]=s;out[2]=0;out[3]=0;out[4]=-s;out[5]=c;out[6]=0;out[7]=0;out[8]=0;out[9]=0;out[10]=1;out[11]=0;out[12]=0;out[13]=0;out[14]=0;out[15]=1;return out;}
mat4.fromRotationTranslation=function(out,q,v){var x=q[0],y=q[1],z=q[2],w=q[3],x2=x+x,y2=y+y,z2=z+z,xx=x*x2,xy=x*y2,xz=x*z2,yy=y*y2,yz=y*z2,zz=z*z2,wx=w*x2,wy=w*y2,wz=w*z2;out[0]=1-(yy+zz);out[1]=xy+wz;out[2]=xz-wy;out[3]=0;out[4]=xy-wz;out[5]=1-(xx+zz);out[6]=yz+wx;out[7]=0;out[8]=xz+wy;out[9]=yz-wx;out[10]=1-(xx+yy);out[11]=0;out[12]=v[0];out[13]=v[1];out[14]=v[2];out[15]=1;return out;};mat4.getTranslation=function(out,mat){out[0]=mat[12];out[1]=mat[13];out[2]=mat[14];return out;};mat4.getRotation=function(out,mat){var trace=mat[0]+mat[5]+mat[10];var S=0;if(trace>0){S=Math.sqrt(trace+1.0)*2;out[3]=0.25*S;out[0]=(mat[6]-mat[9])/S;out[1]=(mat[8]-mat[2])/S;out[2]=(mat[1]-mat[4])/S;}else if((mat[0]>mat[5])&(mat[0]>mat[10])){S=Math.sqrt(1.0+mat[0]-mat[5]-mat[10])*2;out[3]=(mat[6]-mat[9])/S;out[0]=0.25*S;out[1]=(mat[1]+mat[4])/S;out[2]=(mat[8]+mat[2])/S;}else if(mat[5]>mat[10]){S=Math.sqrt(1.0+mat[5]-mat[0]-mat[10])*2;out[3]=(mat[8]-mat[2])/S;out[0]=(mat[1]+mat[4])/S;out[1]=0.25*S;out[2]=(mat[6]+mat[9])/S;}else{S=Math.sqrt(1.0+mat[10]-mat[0]-mat[5])*2;out[3]=(mat[1]-mat[4])/S;out[0]=(mat[8]+mat[2])/S;out[1]=(mat[6]+mat[9])/S;out[2]=0.25*S;}
return out;};mat4.fromRotationTranslationScale=function(out,q,v,s){var x=q[0],y=q[1],z=q[2],w=q[3],x2=x+x,y2=y+y,z2=z+z,xx=x*x2,xy=x*y2,xz=x*z2,yy=y*y2,yz=y*z2,zz=z*z2,wx=w*x2,wy=w*y2,wz=w*z2,sx=s[0],sy=s[1],sz=s[2];out[0]=(1-(yy+zz))*sx;out[1]=(xy+wz)*sx;out[2]=(xz-wy)*sx;out[3]=0;out[4]=(xy-wz)*sy;out[5]=(1-(xx+zz))*sy;out[6]=(yz+wx)*sy;out[7]=0;out[8]=(xz+wy)*sz;out[9]=(yz-wx)*sz;out[10]=(1-(xx+yy))*sz;out[11]=0;out[12]=v[0];out[13]=v[1];out[14]=v[2];out[15]=1;return out;};mat4.fromRotationTranslationScaleOrigin=function(out,q,v,s,o){var x=q[0],y=q[1],z=q[2],w=q[3],x2=x+x,y2=y+y,z2=z+z,xx=x*x2,xy=x*y2,xz=x*z2,yy=y*y2,yz=y*z2,zz=z*z2,wx=w*x2,wy=w*y2,wz=w*z2,sx=s[0],sy=s[1],sz=s[2],ox=o[0],oy=o[1],oz=o[2];out[0]=(1-(yy+zz))*sx;out[1]=(xy+wz)*sx;out[2]=(xz-wy)*sx;out[3]=0;out[4]=(xy-wz)*sy;out[5]=(1-(xx+zz))*sy;out[6]=(yz+wx)*sy;out[7]=0;out[8]=(xz+wy)*sz;out[9]=(yz-wx)*sz;out[10]=(1-(xx+yy))*sz;out[11]=0;out[12]=v[0]+ox-(out[0]*ox+out[4]*oy+out[8]*oz);out[13]=v[1]+oy-(out[1]*ox+out[5]*oy+out[9]*oz);out[14]=v[2]+oz-(out[2]*ox+out[6]*oy+out[10]*oz);out[15]=1;return out;};mat4.fromQuat=function(out,q){var x=q[0],y=q[1],z=q[2],w=q[3],x2=x+x,y2=y+y,z2=z+z,xx=x*x2,yx=y*x2,yy=y*y2,zx=z*x2,zy=z*y2,zz=z*z2,wx=w*x2,wy=w*y2,wz=w*z2;out[0]=1-yy-zz;out[1]=yx+wz;out[2]=zx-wy;out[3]=0;out[4]=yx-wz;out[5]=1-xx-zz;out[6]=zy+wx;out[7]=0;out[8]=zx+wy;out[9]=zy-wx;out[10]=1-xx-yy;out[11]=0;out[12]=0;out[13]=0;out[14]=0;out[15]=1;return out;};mat4.frustum=function(out,left,right,bottom,top,near,far){var rl=1/(right-left),tb=1/(top-bottom),nf=1/(near-far);out[0]=(near*2)*rl;out[1]=0;out[2]=0;out[3]=0;out[4]=0;out[5]=(near*2)*tb;out[6]=0;out[7]=0;out[8]=(right+left)*rl;out[9]=(top+bottom)*tb;out[10]=(far+near)*nf;out[11]=-1;out[12]=0;out[13]=0;out[14]=(far*near*2)*nf;out[15]=0;return out;};mat4.perspective=function(out,fovy,aspect,near,far){var f=1.0/Math.tan(fovy/2),nf=1/(near-far);out[0]=f/aspect;out[1]=0;out[2]=0;out[3]=0;out[4]=0;out[5]=f;out[6]=0;out[7]=0;out[8]=0;out[9]=0;out[10]=(far+near)*nf;out[11]=-1;out[12]=0;out[13]=0;out[14]=(2*far*near)*nf;out[15]=0;return out;};mat4.perspectiveFromFieldOfView=function(out,fov,near,far){var upTan=Math.tan(fov.upDegrees*Math.PI/180.0),downTan=Math.tan(fov.downDegrees*Math.PI/180.0),leftTan=Math.tan(fov.leftDegrees*Math.PI/180.0),rightTan=Math.tan(fov.rightDegrees*Math.PI/180.0),xScale=2.0/(leftTan+rightTan),yScale=2.0/(upTan+downTan);out[0]=xScale;out[1]=0.0;out[2]=0.0;out[3]=0.0;out[4]=0.0;out[5]=yScale;out[6]=0.0;out[7]=0.0;out[8]=-((leftTan-rightTan)*xScale*0.5);out[9]=((upTan-downTan)*yScale*0.5);out[10]=far/(near-far);out[11]=-1.0;out[12]=0.0;out[13]=0.0;out[14]=(far*near)/(near-far);out[15]=0.0;return out;}
mat4.ortho=function(out,left,right,bottom,top,near,far){var lr=1/(left-right),bt=1/(bottom-top),nf=1/(near-far);out[0]=-2*lr;out[1]=0;out[2]=0;out[3]=0;out[4]=0;out[5]=-2*bt;out[6]=0;out[7]=0;out[8]=0;out[9]=0;out[10]=2*nf;out[11]=0;out[12]=(left+right)*lr;out[13]=(top+bottom)*bt;out[14]=(far+near)*nf;out[15]=1;return out;};mat4.lookAt=function(out,eye,center,up){var x0,x1,x2,y0,y1,y2,z0,z1,z2,len,eyex=eye[0],eyey=eye[1],eyez=eye[2],upx=up[0],upy=up[1],upz=up[2],centerx=center[0],centery=center[1],centerz=center[2];if(Math.abs(eyex-centerx)<glMatrix.EPSILON&&Math.abs(eyey-centery)<glMatrix.EPSILON&&Math.abs(eyez-centerz)<glMatrix.EPSILON){return mat4.identity(out);}
z0=eyex-centerx;z1=eyey-centery;z2=eyez-centerz;len=1/Math.sqrt(z0*z0+z1*z1+z2*z2);z0*=len;z1*=len;z2*=len;x0=upy*z2-upz*z1;x1=upz*z0-upx*z2;x2=upx*z1-upy*z0;len=Math.sqrt(x0*x0+x1*x1+x2*x2);if(!len){x0=0;x1=0;x2=0;}else{len=1/len;x0*=len;x1*=len;x2*=len;}
y0=z1*x2-z2*x1;y1=z2*x0-z0*x2;y2=z0*x1-z1*x0;len=Math.sqrt(y0*y0+y1*y1+y2*y2);if(!len){y0=0;y1=0;y2=0;}else{len=1/len;y0*=len;y1*=len;y2*=len;}
out[0]=x0;out[1]=y0;out[2]=z0;out[3]=0;out[4]=x1;out[5]=y1;out[6]=z1;out[7]=0;out[8]=x2;out[9]=y2;out[10]=z2;out[11]=0;out[12]=-(x0*eyex+x1*eyey+x2*eyez);out[13]=-(y0*eyex+y1*eyey+y2*eyez);out[14]=-(z0*eyex+z1*eyey+z2*eyez);out[15]=1;return out;};mat4.str=function(a){return'mat4('+a[0]+', '+a[1]+', '+a[2]+', '+a[3]+', '+
a[4]+', '+a[5]+', '+a[6]+', '+a[7]+', '+
a[8]+', '+a[9]+', '+a[10]+', '+a[11]+', '+
a[12]+', '+a[13]+', '+a[14]+', '+a[15]+')';};mat4.frob=function(a){return(Math.sqrt(Math.pow(a[0],2)+Math.pow(a[1],2)+Math.pow(a[2],2)+Math.pow(a[3],2)+Math.pow(a[4],2)+Math.pow(a[5],2)+Math.pow(a[6],2)+Math.pow(a[7],2)+Math.pow(a[8],2)+Math.pow(a[9],2)+Math.pow(a[10],2)+Math.pow(a[11],2)+Math.pow(a[12],2)+Math.pow(a[13],2)+Math.pow(a[14],2)+Math.pow(a[15],2)))};mat4.add=function(out,a,b){out[0]=a[0]+b[0];out[1]=a[1]+b[1];out[2]=a[2]+b[2];out[3]=a[3]+b[3];out[4]=a[4]+b[4];out[5]=a[5]+b[5];out[6]=a[6]+b[6];out[7]=a[7]+b[7];out[8]=a[8]+b[8];out[9]=a[9]+b[9];out[10]=a[10]+b[10];out[11]=a[11]+b[11];out[12]=a[12]+b[12];out[13]=a[13]+b[13];out[14]=a[14]+b[14];out[15]=a[15]+b[15];return out;};mat4.subtract=function(out,a,b){out[0]=a[0]-b[0];out[1]=a[1]-b[1];out[2]=a[2]-b[2];out[3]=a[3]-b[3];out[4]=a[4]-b[4];out[5]=a[5]-b[5];out[6]=a[6]-b[6];out[7]=a[7]-b[7];out[8]=a[8]-b[8];out[9]=a[9]-b[9];out[10]=a[10]-b[10];out[11]=a[11]-b[11];out[12]=a[12]-b[12];out[13]=a[13]-b[13];out[14]=a[14]-b[14];out[15]=a[15]-b[15];return out;};mat4.sub=mat4.subtract;mat4.multiplyScalar=function(out,a,b){out[0]=a[0]*b;out[1]=a[1]*b;out[2]=a[2]*b;out[3]=a[3]*b;out[4]=a[4]*b;out[5]=a[5]*b;out[6]=a[6]*b;out[7]=a[7]*b;out[8]=a[8]*b;out[9]=a[9]*b;out[10]=a[10]*b;out[11]=a[11]*b;out[12]=a[12]*b;out[13]=a[13]*b;out[14]=a[14]*b;out[15]=a[15]*b;return out;};mat4.multiplyScalarAndAdd=function(out,a,b,scale){out[0]=a[0]+(b[0]*scale);out[1]=a[1]+(b[1]*scale);out[2]=a[2]+(b[2]*scale);out[3]=a[3]+(b[3]*scale);out[4]=a[4]+(b[4]*scale);out[5]=a[5]+(b[5]*scale);out[6]=a[6]+(b[6]*scale);out[7]=a[7]+(b[7]*scale);out[8]=a[8]+(b[8]*scale);out[9]=a[9]+(b[9]*scale);out[10]=a[10]+(b[10]*scale);out[11]=a[11]+(b[11]*scale);out[12]=a[12]+(b[12]*scale);out[13]=a[13]+(b[13]*scale);out[14]=a[14]+(b[14]*scale);out[15]=a[15]+(b[15]*scale);return out;};mat4.exactEquals=function(a,b){return a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15];};mat4.equals=function(a,b){var a0=a[0],a1=a[1],a2=a[2],a3=a[3],a4=a[4],a5=a[5],a6=a[6],a7=a[7],a8=a[8],a9=a[9],a10=a[10],a11=a[11],a12=a[12],a13=a[13],a14=a[14],a15=a[15];var b0=b[0],b1=b[1],b2=b[2],b3=b[3],b4=b[4],b5=b[5],b6=b[6],b7=b[7],b8=b[8],b9=b[9],b10=b[10],b11=b[11],b12=b[12],b13=b[13],b14=b[14],b15=b[15];return(Math.abs(a0-b0)<=glMatrix.EPSILON*Math.max(1.0,Math.abs(a0),Math.abs(b0))&&Math.abs(a1-b1)<=glMatrix.EPSILON*Math.max(1.0,Math.abs(a1),Math.abs(b1))&&Math.abs(a2-b2)<=glMatrix.EPSILON*Math.max(1.0,Math.abs(a2),Math.abs(b2))&&Math.abs(a3-b3)<=glMatrix.EPSILON*Math.max(1.0,Math.abs(a3),Math.abs(b3))&&Math.abs(a4-b4)<=glMatrix.EPSILON*Math.max(1.0,Math.abs(a4),Math.abs(b4))&&Math.abs(a5-b5)<=glMatrix.EPSILON*Math.max(1.0,Math.abs(a5),Math.abs(b5))&&Math.abs(a6-b6)<=glMatrix.EPSILON*Math.max(1.0,Math.abs(a6),Math.abs(b6))&&Math.abs(a7-b7)<=glMatrix.EPSILON*Math.max(1.0,Math.abs(a7),Math.abs(b7))&&Math.abs(a8-b8)<=glMatrix.EPSILON*Math.max(1.0,Math.abs(a8),Math.abs(b8))&&Math.abs(a9-b9)<=glMatrix.EPSILON*Math.max(1.0,Math.abs(a9),Math.abs(b9))&&Math.abs(a10-b10)<=glMatrix.EPSILON*Math.max(1.0,Math.abs(a10),Math.abs(b10))&&Math.abs(a11-b11)<=glMatrix.EPSILON*Math.max(1.0,Math.abs(a11),Math.abs(b11))&&Math.abs(a12-b12)<=glMatrix.EPSILON*Math.max(1.0,Math.abs(a12),Math.abs(b12))&&Math.abs(a13-b13)<=glMatrix.EPSILON*Math.max(1.0,Math.abs(a13),Math.abs(b13))&&Math.abs(a14-b14)<=glMatrix.EPSILON*Math.max(1.0,Math.abs(a14),Math.abs(b14))&&Math.abs(a15-b15)<=glMatrix.EPSILON*Math.max(1.0,Math.abs(a15),Math.abs(b15)));};module.exports=mat4;},{"./common.js":238}],243:[function(require,module,exports){var glMatrix=require("./common.js");var mat3=require("./mat3.js");var vec3=require("./vec3.js");var vec4=require("./vec4.js");var quat={};quat.create=function(){var out=new glMatrix.ARRAY_TYPE(4);out[0]=0;out[1]=0;out[2]=0;out[3]=1;return out;};quat.rotationTo=(function(){var tmpvec3=vec3.create();var xUnitVec3=vec3.fromValues(1,0,0);var yUnitVec3=vec3.fromValues(0,1,0);return function(out,a,b){var dot=vec3.dot(a,b);if(dot<-0.999999){vec3.cross(tmpvec3,xUnitVec3,a);if(vec3.length(tmpvec3)<0.000001)
vec3.cross(tmpvec3,yUnitVec3,a);vec3.normalize(tmpvec3,tmpvec3);quat.setAxisAngle(out,tmpvec3,Math.PI);return out;}else if(dot>0.999999){out[0]=0;out[1]=0;out[2]=0;out[3]=1;return out;}else{vec3.cross(tmpvec3,a,b);out[0]=tmpvec3[0];out[1]=tmpvec3[1];out[2]=tmpvec3[2];out[3]=1+dot;return quat.normalize(out,out);}};})();quat.setAxes=(function(){var matr=mat3.create();return function(out,view,right,up){matr[0]=right[0];matr[3]=right[1];matr[6]=right[2];matr[1]=up[0];matr[4]=up[1];matr[7]=up[2];matr[2]=-view[0];matr[5]=-view[1];matr[8]=-view[2];return quat.normalize(out,quat.fromMat3(out,matr));};})();quat.clone=vec4.clone;quat.fromValues=vec4.fromValues;quat.copy=vec4.copy;quat.set=vec4.set;quat.identity=function(out){out[0]=0;out[1]=0;out[2]=0;out[3]=1;return out;};quat.setAxisAngle=function(out,axis,rad){rad=rad*0.5;var s=Math.sin(rad);out[0]=s*axis[0];out[1]=s*axis[1];out[2]=s*axis[2];out[3]=Math.cos(rad);return out;};quat.getAxisAngle=function(out_axis,q){var rad=Math.acos(q[3])*2.0;var s=Math.sin(rad/2.0);if(s!=0.0){out_axis[0]=q[0]/s;out_axis[1]=q[1]/s;out_axis[2]=q[2]/s;}else{out_axis[0]=1;out_axis[1]=0;out_axis[2]=0;}
return rad;};quat.add=vec4.add;quat.multiply=function(out,a,b){var ax=a[0],ay=a[1],az=a[2],aw=a[3],bx=b[0],by=b[1],bz=b[2],bw=b[3];out[0]=ax*bw+aw*bx+ay*bz-az*by;out[1]=ay*bw+aw*by+az*bx-ax*bz;out[2]=az*bw+aw*bz+ax*by-ay*bx;out[3]=aw*bw-ax*bx-ay*by-az*bz;return out;};quat.mul=quat.multiply;quat.scale=vec4.scale;quat.rotateX=function(out,a,rad){rad*=0.5;var ax=a[0],ay=a[1],az=a[2],aw=a[3],bx=Math.sin(rad),bw=Math.cos(rad);out[0]=ax*bw+aw*bx;out[1]=ay*bw+az*bx;out[2]=az*bw-ay*bx;out[3]=aw*bw-ax*bx;return out;};quat.rotateY=function(out,a,rad){rad*=0.5;var ax=a[0],ay=a[1],az=a[2],aw=a[3],by=Math.sin(rad),bw=Math.cos(rad);out[0]=ax*bw-az*by;out[1]=ay*bw+aw*by;out[2]=az*bw+ax*by;out[3]=aw*bw-ay*by;return out;};quat.rotateZ=function(out,a,rad){rad*=0.5;var ax=a[0],ay=a[1],az=a[2],aw=a[3],bz=Math.sin(rad),bw=Math.cos(rad);out[0]=ax*bw+ay*bz;out[1]=ay*bw-ax*bz;out[2]=az*bw+aw*bz;out[3]=aw*bw-az*bz;return out;};quat.calculateW=function(out,a){var x=a[0],y=a[1],z=a[2];out[0]=x;out[1]=y;out[2]=z;out[3]=Math.sqrt(Math.abs(1.0-x*x-y*y-z*z));return out;};quat.dot=vec4.dot;quat.lerp=vec4.lerp;quat.slerp=function(out,a,b,t){var ax=a[0],ay=a[1],az=a[2],aw=a[3],bx=b[0],by=b[1],bz=b[2],bw=b[3];var omega,cosom,sinom,scale0,scale1;cosom=ax*bx+ay*by+az*bz+aw*bw;if(cosom<0.0){cosom=-cosom;bx=-bx;by=-by;bz=-bz;bw=-bw;}
if((1.0-cosom)>0.000001){omega=Math.acos(cosom);sinom=Math.sin(omega);scale0=Math.sin((1.0-t)*omega)/sinom;scale1=Math.sin(t*omega)/sinom;}else{scale0=1.0-t;scale1=t;}
out[0]=scale0*ax+scale1*bx;out[1]=scale0*ay+scale1*by;out[2]=scale0*az+scale1*bz;out[3]=scale0*aw+scale1*bw;return out;};quat.sqlerp=(function(){var temp1=quat.create();var temp2=quat.create();return function(out,a,b,c,d,t){quat.slerp(temp1,a,d,t);quat.slerp(temp2,b,c,t);quat.slerp(out,temp1,temp2,2*t*(1-t));return out;};}());quat.invert=function(out,a){var a0=a[0],a1=a[1],a2=a[2],a3=a[3],dot=a0*a0+a1*a1+a2*a2+a3*a3,invDot=dot?1.0/dot:0;out[0]=-a0*invDot;out[1]=-a1*invDot;out[2]=-a2*invDot;out[3]=a3*invDot;return out;};quat.conjugate=function(out,a){out[0]=-a[0];out[1]=-a[1];out[2]=-a[2];out[3]=a[3];return out;};quat.length=vec4.length;quat.len=quat.length;quat.squaredLength=vec4.squaredLength;quat.sqrLen=quat.squaredLength;quat.normalize=vec4.normalize;quat.fromMat3=function(out,m){var fTrace=m[0]+m[4]+m[8];var fRoot;if(fTrace>0.0){fRoot=Math.sqrt(fTrace+1.0);out[3]=0.5*fRoot;fRoot=0.5/fRoot;out[0]=(m[5]-m[7])*fRoot;out[1]=(m[6]-m[2])*fRoot;out[2]=(m[1]-m[3])*fRoot;}else{var i=0;if(m[4]>m[0])
i=1;if(m[8]>m[i*3+i])
i=2;var j=(i+1)%3;var k=(i+2)%3;fRoot=Math.sqrt(m[i*3+i]-m[j*3+j]-m[k*3+k]+1.0);out[i]=0.5*fRoot;fRoot=0.5/fRoot;out[3]=(m[j*3+k]-m[k*3+j])*fRoot;out[j]=(m[j*3+i]+m[i*3+j])*fRoot;out[k]=(m[k*3+i]+m[i*3+k])*fRoot;}
return out;};quat.str=function(a){return'quat('+a[0]+', '+a[1]+', '+a[2]+', '+a[3]+')';};quat.exactEquals=vec4.exactEquals;quat.equals=vec4.equals;module.exports=quat;},{"./common.js":238,"./mat3.js":241,"./vec3.js":245,"./vec4.js":246}],244:[function(require,module,exports){var glMatrix=require("./common.js");var vec2={};vec2.create=function(){var out=new glMatrix.ARRAY_TYPE(2);out[0]=0;out[1]=0;return out;};vec2.clone=function(a){var out=new glMatrix.ARRAY_TYPE(2);out[0]=a[0];out[1]=a[1];return out;};vec2.fromValues=function(x,y){var out=new glMatrix.ARRAY_TYPE(2);out[0]=x;out[1]=y;return out;};vec2.copy=function(out,a){out[0]=a[0];out[1]=a[1];return out;};vec2.set=function(out,x,y){out[0]=x;out[1]=y;return out;};vec2.add=function(out,a,b){out[0]=a[0]+b[0];out[1]=a[1]+b[1];return out;};vec2.subtract=function(out,a,b){out[0]=a[0]-b[0];out[1]=a[1]-b[1];return out;};vec2.sub=vec2.subtract;vec2.multiply=function(out,a,b){out[0]=a[0]*b[0];out[1]=a[1]*b[1];return out;};vec2.mul=vec2.multiply;vec2.divide=function(out,a,b){out[0]=a[0]/b[0];out[1]=a[1]/b[1];return out;};vec2.div=vec2.divide;vec2.ceil=function(out,a){out[0]=Math.ceil(a[0]);out[1]=Math.ceil(a[1]);return out;};vec2.floor=function(out,a){out[0]=Math.floor(a[0]);out[1]=Math.floor(a[1]);return out;};vec2.min=function(out,a,b){out[0]=Math.min(a[0],b[0]);out[1]=Math.min(a[1],b[1]);return out;};vec2.max=function(out,a,b){out[0]=Math.max(a[0],b[0]);out[1]=Math.max(a[1],b[1]);return out;};vec2.round=function(out,a){out[0]=Math.round(a[0]);out[1]=Math.round(a[1]);return out;};vec2.scale=function(out,a,b){out[0]=a[0]*b;out[1]=a[1]*b;return out;};vec2.scaleAndAdd=function(out,a,b,scale){out[0]=a[0]+(b[0]*scale);out[1]=a[1]+(b[1]*scale);return out;};vec2.distance=function(a,b){var x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y);};vec2.dist=vec2.distance;vec2.squaredDistance=function(a,b){var x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y;};vec2.sqrDist=vec2.squaredDistance;vec2.length=function(a){var x=a[0],y=a[1];return Math.sqrt(x*x+y*y);};vec2.len=vec2.length;vec2.squaredLength=function(a){var x=a[0],y=a[1];return x*x+y*y;};vec2.sqrLen=vec2.squaredLength;vec2.negate=function(out,a){out[0]=-a[0];out[1]=-a[1];return out;};vec2.inverse=function(out,a){out[0]=1.0/a[0];out[1]=1.0/a[1];return out;};vec2.normalize=function(out,a){var x=a[0],y=a[1];var len=x*x+y*y;if(len>0){len=1/Math.sqrt(len);out[0]=a[0]*len;out[1]=a[1]*len;}
return out;};vec2.dot=function(a,b){return a[0]*b[0]+a[1]*b[1];};vec2.cross=function(out,a,b){var z=a[0]*b[1]-a[1]*b[0];out[0]=out[1]=0;out[2]=z;return out;};vec2.lerp=function(out,a,b,t){var ax=a[0],ay=a[1];out[0]=ax+t*(b[0]-ax);out[1]=ay+t*(b[1]-ay);return out;};vec2.random=function(out,scale){scale=scale||1.0;var r=glMatrix.RANDOM()*2.0*Math.PI;out[0]=Math.cos(r)*scale;out[1]=Math.sin(r)*scale;return out;};vec2.transformMat2=function(out,a,m){var x=a[0],y=a[1];out[0]=m[0]*x+m[2]*y;out[1]=m[1]*x+m[3]*y;return out;};vec2.transformMat2d=function(out,a,m){var x=a[0],y=a[1];out[0]=m[0]*x+m[2]*y+m[4];out[1]=m[1]*x+m[3]*y+m[5];return out;};vec2.transformMat3=function(out,a,m){var x=a[0],y=a[1];out[0]=m[0]*x+m[3]*y+m[6];out[1]=m[1]*x+m[4]*y+m[7];return out;};vec2.transformMat4=function(out,a,m){var x=a[0],y=a[1];out[0]=m[0]*x+m[4]*y+m[12];out[1]=m[1]*x+m[5]*y+m[13];return out;};vec2.forEach=(function(){var vec=vec2.create();return function(a,stride,offset,count,fn,arg){var i,l;if(!stride){stride=2;}
if(!offset){offset=0;}
if(count){l=Math.min((count*stride)+offset,a.length);}else{l=a.length;}
for(i=offset;i<l;i+=stride){vec[0]=a[i];vec[1]=a[i+1];fn(vec,vec,arg);a[i]=vec[0];a[i+1]=vec[1];}
return a;};})();vec2.str=function(a){return'vec2('+a[0]+', '+a[1]+')';};vec2.exactEquals=function(a,b){return a[0]===b[0]&&a[1]===b[1];};vec2.equals=function(a,b){var a0=a[0],a1=a[1];var b0=b[0],b1=b[1];return(Math.abs(a0-b0)<=glMatrix.EPSILON*Math.max(1.0,Math.abs(a0),Math.abs(b0))&&Math.abs(a1-b1)<=glMatrix.EPSILON*Math.max(1.0,Math.abs(a1),Math.abs(b1)));};module.exports=vec2;},{"./common.js":238}],245:[function(require,module,exports){var glMatrix=require("./common.js");var vec3={};vec3.create=function(){var out=new glMatrix.ARRAY_TYPE(3);out[0]=0;out[1]=0;out[2]=0;return out;};vec3.clone=function(a){var out=new glMatrix.ARRAY_TYPE(3);out[0]=a[0];out[1]=a[1];out[2]=a[2];return out;};vec3.fromValues=function(x,y,z){var out=new glMatrix.ARRAY_TYPE(3);out[0]=x;out[1]=y;out[2]=z;return out;};vec3.copy=function(out,a){out[0]=a[0];out[1]=a[1];out[2]=a[2];return out;};vec3.set=function(out,x,y,z){out[0]=x;out[1]=y;out[2]=z;return out;};vec3.add=function(out,a,b){out[0]=a[0]+b[0];out[1]=a[1]+b[1];out[2]=a[2]+b[2];return out;};vec3.subtract=function(out,a,b){out[0]=a[0]-b[0];out[1]=a[1]-b[1];out[2]=a[2]-b[2];return out;};vec3.sub=vec3.subtract;vec3.multiply=function(out,a,b){out[0]=a[0]*b[0];out[1]=a[1]*b[1];out[2]=a[2]*b[2];return out;};vec3.mul=vec3.multiply;vec3.divide=function(out,a,b){out[0]=a[0]/b[0];out[1]=a[1]/b[1];out[2]=a[2]/b[2];return out;};vec3.div=vec3.divide;vec3.ceil=function(out,a){out[0]=Math.ceil(a[0]);out[1]=Math.ceil(a[1]);out[2]=Math.ceil(a[2]);return out;};vec3.floor=function(out,a){out[0]=Math.floor(a[0]);out[1]=Math.floor(a[1]);out[2]=Math.floor(a[2]);return out;};vec3.min=function(out,a,b){out[0]=Math.min(a[0],b[0]);out[1]=Math.min(a[1],b[1]);out[2]=Math.min(a[2],b[2]);return out;};vec3.max=function(out,a,b){out[0]=Math.max(a[0],b[0]);out[1]=Math.max(a[1],b[1]);out[2]=Math.max(a[2],b[2]);return out;};vec3.round=function(out,a){out[0]=Math.round(a[0]);out[1]=Math.round(a[1]);out[2]=Math.round(a[2]);return out;};vec3.scale=function(out,a,b){out[0]=a[0]*b;out[1]=a[1]*b;out[2]=a[2]*b;return out;};vec3.scaleAndAdd=function(out,a,b,scale){out[0]=a[0]+(b[0]*scale);out[1]=a[1]+(b[1]*scale);out[2]=a[2]+(b[2]*scale);return out;};vec3.distance=function(a,b){var x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z);};vec3.dist=vec3.distance;vec3.squaredDistance=function(a,b){var x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z;};vec3.sqrDist=vec3.squaredDistance;vec3.length=function(a){var x=a[0],y=a[1],z=a[2];return Math.sqrt(x*x+y*y+z*z);};vec3.len=vec3.length;vec3.squaredLength=function(a){var x=a[0],y=a[1],z=a[2];return x*x+y*y+z*z;};vec3.sqrLen=vec3.squaredLength;vec3.negate=function(out,a){out[0]=-a[0];out[1]=-a[1];out[2]=-a[2];return out;};vec3.inverse=function(out,a){out[0]=1.0/a[0];out[1]=1.0/a[1];out[2]=1.0/a[2];return out;};vec3.normalize=function(out,a){var x=a[0],y=a[1],z=a[2];var len=x*x+y*y+z*z;if(len>0){len=1/Math.sqrt(len);out[0]=a[0]*len;out[1]=a[1]*len;out[2]=a[2]*len;}
return out;};vec3.dot=function(a,b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2];};vec3.cross=function(out,a,b){var ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];out[0]=ay*bz-az*by;out[1]=az*bx-ax*bz;out[2]=ax*by-ay*bx;return out;};vec3.lerp=function(out,a,b,t){var ax=a[0],ay=a[1],az=a[2];out[0]=ax+t*(b[0]-ax);out[1]=ay+t*(b[1]-ay);out[2]=az+t*(b[2]-az);return out;};vec3.hermite=function(out,a,b,c,d,t){var factorTimes2=t*t,factor1=factorTimes2*(2*t-3)+1,factor2=factorTimes2*(t-2)+t,factor3=factorTimes2*(t-1),factor4=factorTimes2*(3-2*t);out[0]=a[0]*factor1+b[0]*factor2+c[0]*factor3+d[0]*factor4;out[1]=a[1]*factor1+b[1]*factor2+c[1]*factor3+d[1]*factor4;out[2]=a[2]*factor1+b[2]*factor2+c[2]*factor3+d[2]*factor4;return out;};vec3.bezier=function(out,a,b,c,d,t){var inverseFactor=1-t,inverseFactorTimesTwo=inverseFactor*inverseFactor,factorTimes2=t*t,factor1=inverseFactorTimesTwo*inverseFactor,factor2=3*t*inverseFactorTimesTwo,factor3=3*factorTimes2*inverseFactor,factor4=factorTimes2*t;out[0]=a[0]*factor1+b[0]*factor2+c[0]*factor3+d[0]*factor4;out[1]=a[1]*factor1+b[1]*factor2+c[1]*factor3+d[1]*factor4;out[2]=a[2]*factor1+b[2]*factor2+c[2]*factor3+d[2]*factor4;return out;};vec3.random=function(out,scale){scale=scale||1.0;var r=glMatrix.RANDOM()*2.0*Math.PI;var z=(glMatrix.RANDOM()*2.0)-1.0;var zScale=Math.sqrt(1.0-z*z)*scale;out[0]=Math.cos(r)*zScale;out[1]=Math.sin(r)*zScale;out[2]=z*scale;return out;};vec3.transformMat4=function(out,a,m){var x=a[0],y=a[1],z=a[2],w=m[3]*x+m[7]*y+m[11]*z+m[15];w=w||1.0;out[0]=(m[0]*x+m[4]*y+m[8]*z+m[12])/w;out[1]=(m[1]*x+m[5]*y+m[9]*z+m[13])/w;out[2]=(m[2]*x+m[6]*y+m[10]*z+m[14])/w;return out;};vec3.transformMat3=function(out,a,m){var x=a[0],y=a[1],z=a[2];out[0]=x*m[0]+y*m[3]+z*m[6];out[1]=x*m[1]+y*m[4]+z*m[7];out[2]=x*m[2]+y*m[5]+z*m[8];return out;};vec3.transformQuat=function(out,a,q){var x=a[0],y=a[1],z=a[2],qx=q[0],qy=q[1],qz=q[2],qw=q[3],ix=qw*x+qy*z-qz*y,iy=qw*y+qz*x-qx*z,iz=qw*z+qx*y-qy*x,iw=-qx*x-qy*y-qz*z;out[0]=ix*qw+iw*-qx+iy*-qz-iz*-qy;out[1]=iy*qw+iw*-qy+iz*-qx-ix*-qz;out[2]=iz*qw+iw*-qz+ix*-qy-iy*-qx;return out;};vec3.rotateX=function(out,a,b,c){var p=[],r=[];p[0]=a[0]-b[0];p[1]=a[1]-b[1];p[2]=a[2]-b[2];r[0]=p[0];r[1]=p[1]*Math.cos(c)-p[2]*Math.sin(c);r[2]=p[1]*Math.sin(c)+p[2]*Math.cos(c);out[0]=r[0]+b[0];out[1]=r[1]+b[1];out[2]=r[2]+b[2];return out;};vec3.rotateY=function(out,a,b,c){var p=[],r=[];p[0]=a[0]-b[0];p[1]=a[1]-b[1];p[2]=a[2]-b[2];r[0]=p[2]*Math.sin(c)+p[0]*Math.cos(c);r[1]=p[1];r[2]=p[2]*Math.cos(c)-p[0]*Math.sin(c);out[0]=r[0]+b[0];out[1]=r[1]+b[1];out[2]=r[2]+b[2];return out;};vec3.rotateZ=function(out,a,b,c){var p=[],r=[];p[0]=a[0]-b[0];p[1]=a[1]-b[1];p[2]=a[2]-b[2];r[0]=p[0]*Math.cos(c)-p[1]*Math.sin(c);r[1]=p[0]*Math.sin(c)+p[1]*Math.cos(c);r[2]=p[2];out[0]=r[0]+b[0];out[1]=r[1]+b[1];out[2]=r[2]+b[2];return out;};vec3.forEach=(function(){var vec=vec3.create();return function(a,stride,offset,count,fn,arg){var i,l;if(!stride){stride=3;}
if(!offset){offset=0;}
if(count){l=Math.min((count*stride)+offset,a.length);}else{l=a.length;}
for(i=offset;i<l;i+=stride){vec[0]=a[i];vec[1]=a[i+1];vec[2]=a[i+2];fn(vec,vec,arg);a[i]=vec[0];a[i+1]=vec[1];a[i+2]=vec[2];}
return a;};})();vec3.angle=function(a,b){var tempA=vec3.fromValues(a[0],a[1],a[2]);var tempB=vec3.fromValues(b[0],b[1],b[2]);vec3.normalize(tempA,tempA);vec3.normalize(tempB,tempB);var cosine=vec3.dot(tempA,tempB);if(cosine>1.0){return 0;}else{return Math.acos(cosine);}};vec3.str=function(a){return'vec3('+a[0]+', '+a[1]+', '+a[2]+')';};vec3.exactEquals=function(a,b){return a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2];};vec3.equals=function(a,b){var a0=a[0],a1=a[1],a2=a[2];var b0=b[0],b1=b[1],b2=b[2];return(Math.abs(a0-b0)<=glMatrix.EPSILON*Math.max(1.0,Math.abs(a0),Math.abs(b0))&&Math.abs(a1-b1)<=glMatrix.EPSILON*Math.max(1.0,Math.abs(a1),Math.abs(b1))&&Math.abs(a2-b2)<=glMatrix.EPSILON*Math.max(1.0,Math.abs(a2),Math.abs(b2)));};module.exports=vec3;},{"./common.js":238}],246:[function(require,module,exports){var glMatrix=require("./common.js");var vec4={};vec4.create=function(){var out=new glMatrix.ARRAY_TYPE(4);out[0]=0;out[1]=0;out[2]=0;out[3]=0;return out;};vec4.clone=function(a){var out=new glMatrix.ARRAY_TYPE(4);out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];return out;};vec4.fromValues=function(x,y,z,w){var out=new glMatrix.ARRAY_TYPE(4);out[0]=x;out[1]=y;out[2]=z;out[3]=w;return out;};vec4.copy=function(out,a){out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];return out;};vec4.set=function(out,x,y,z,w){out[0]=x;out[1]=y;out[2]=z;out[3]=w;return out;};vec4.add=function(out,a,b){out[0]=a[0]+b[0];out[1]=a[1]+b[1];out[2]=a[2]+b[2];out[3]=a[3]+b[3];return out;};vec4.subtract=function(out,a,b){out[0]=a[0]-b[0];out[1]=a[1]-b[1];out[2]=a[2]-b[2];out[3]=a[3]-b[3];return out;};vec4.sub=vec4.subtract;vec4.multiply=function(out,a,b){out[0]=a[0]*b[0];out[1]=a[1]*b[1];out[2]=a[2]*b[2];out[3]=a[3]*b[3];return out;};vec4.mul=vec4.multiply;vec4.divide=function(out,a,b){out[0]=a[0]/b[0];out[1]=a[1]/b[1];out[2]=a[2]/b[2];out[3]=a[3]/b[3];return out;};vec4.div=vec4.divide;vec4.ceil=function(out,a){out[0]=Math.ceil(a[0]);out[1]=Math.ceil(a[1]);out[2]=Math.ceil(a[2]);out[3]=Math.ceil(a[3]);return out;};vec4.floor=function(out,a){out[0]=Math.floor(a[0]);out[1]=Math.floor(a[1]);out[2]=Math.floor(a[2]);out[3]=Math.floor(a[3]);return out;};vec4.min=function(out,a,b){out[0]=Math.min(a[0],b[0]);out[1]=Math.min(a[1],b[1]);out[2]=Math.min(a[2],b[2]);out[3]=Math.min(a[3],b[3]);return out;};vec4.max=function(out,a,b){out[0]=Math.max(a[0],b[0]);out[1]=Math.max(a[1],b[1]);out[2]=Math.max(a[2],b[2]);out[3]=Math.max(a[3],b[3]);return out;};vec4.round=function(out,a){out[0]=Math.round(a[0]);out[1]=Math.round(a[1]);out[2]=Math.round(a[2]);out[3]=Math.round(a[3]);return out;};vec4.scale=function(out,a,b){out[0]=a[0]*b;out[1]=a[1]*b;out[2]=a[2]*b;out[3]=a[3]*b;return out;};vec4.scaleAndAdd=function(out,a,b,scale){out[0]=a[0]+(b[0]*scale);out[1]=a[1]+(b[1]*scale);out[2]=a[2]+(b[2]*scale);out[3]=a[3]+(b[3]*scale);return out;};vec4.distance=function(a,b){var x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2],w=b[3]-a[3];return Math.sqrt(x*x+y*y+z*z+w*w);};vec4.dist=vec4.distance;vec4.squaredDistance=function(a,b){var x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2],w=b[3]-a[3];return x*x+y*y+z*z+w*w;};vec4.sqrDist=vec4.squaredDistance;vec4.length=function(a){var x=a[0],y=a[1],z=a[2],w=a[3];return Math.sqrt(x*x+y*y+z*z+w*w);};vec4.len=vec4.length;vec4.squaredLength=function(a){var x=a[0],y=a[1],z=a[2],w=a[3];return x*x+y*y+z*z+w*w;};vec4.sqrLen=vec4.squaredLength;vec4.negate=function(out,a){out[0]=-a[0];out[1]=-a[1];out[2]=-a[2];out[3]=-a[3];return out;};vec4.inverse=function(out,a){out[0]=1.0/a[0];out[1]=1.0/a[1];out[2]=1.0/a[2];out[3]=1.0/a[3];return out;};vec4.normalize=function(out,a){var x=a[0],y=a[1],z=a[2],w=a[3];var len=x*x+y*y+z*z+w*w;if(len>0){len=1/Math.sqrt(len);out[0]=x*len;out[1]=y*len;out[2]=z*len;out[3]=w*len;}
return out;};vec4.dot=function(a,b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3];};vec4.lerp=function(out,a,b,t){var ax=a[0],ay=a[1],az=a[2],aw=a[3];out[0]=ax+t*(b[0]-ax);out[1]=ay+t*(b[1]-ay);out[2]=az+t*(b[2]-az);out[3]=aw+t*(b[3]-aw);return out;};vec4.random=function(out,scale){scale=scale||1.0;out[0]=glMatrix.RANDOM();out[1]=glMatrix.RANDOM();out[2]=glMatrix.RANDOM();out[3]=glMatrix.RANDOM();vec4.normalize(out,out);vec4.scale(out,out,scale);return out;};vec4.transformMat4=function(out,a,m){var x=a[0],y=a[1],z=a[2],w=a[3];out[0]=m[0]*x+m[4]*y+m[8]*z+m[12]*w;out[1]=m[1]*x+m[5]*y+m[9]*z+m[13]*w;out[2]=m[2]*x+m[6]*y+m[10]*z+m[14]*w;out[3]=m[3]*x+m[7]*y+m[11]*z+m[15]*w;return out;};vec4.transformQuat=function(out,a,q){var x=a[0],y=a[1],z=a[2],qx=q[0],qy=q[1],qz=q[2],qw=q[3],ix=qw*x+qy*z-qz*y,iy=qw*y+qz*x-qx*z,iz=qw*z+qx*y-qy*x,iw=-qx*x-qy*y-qz*z;out[0]=ix*qw+iw*-qx+iy*-qz-iz*-qy;out[1]=iy*qw+iw*-qy+iz*-qx-ix*-qz;out[2]=iz*qw+iw*-qz+ix*-qy-iy*-qx;out[3]=a[3];return out;};vec4.forEach=(function(){var vec=vec4.create();return function(a,stride,offset,count,fn,arg){var i,l;if(!stride){stride=4;}
if(!offset){offset=0;}
if(count){l=Math.min((count*stride)+offset,a.length);}else{l=a.length;}
for(i=offset;i<l;i+=stride){vec[0]=a[i];vec[1]=a[i+1];vec[2]=a[i+2];vec[3]=a[i+3];fn(vec,vec,arg);a[i]=vec[0];a[i+1]=vec[1];a[i+2]=vec[2];a[i+3]=vec[3];}
return a;};})();vec4.str=function(a){return'vec4('+a[0]+', '+a[1]+', '+a[2]+', '+a[3]+')';};vec4.exactEquals=function(a,b){return a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3];};vec4.equals=function(a,b){var a0=a[0],a1=a[1],a2=a[2],a3=a[3];var b0=b[0],b1=b[1],b2=b[2],b3=b[3];return(Math.abs(a0-b0)<=glMatrix.EPSILON*Math.max(1.0,Math.abs(a0),Math.abs(b0))&&Math.abs(a1-b1)<=glMatrix.EPSILON*Math.max(1.0,Math.abs(a1),Math.abs(b1))&&Math.abs(a2-b2)<=glMatrix.EPSILON*Math.max(1.0,Math.abs(a2),Math.abs(b2))&&Math.abs(a3-b3)<=glMatrix.EPSILON*Math.max(1.0,Math.abs(a3),Math.abs(b3)));};module.exports=vec4;},{"./common.js":238}],247:[function(require,module,exports){'use strict';exports.__esModule=true;function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{'default':obj};}
var _handlebarsRuntime=require('./handlebars.runtime');var _handlebarsRuntime2=_interopRequireDefault(_handlebarsRuntime);var _handlebarsCompilerAst=require('./handlebars/compiler/ast');var _handlebarsCompilerAst2=_interopRequireDefault(_handlebarsCompilerAst);var _handlebarsCompilerBase=require('./handlebars/compiler/base');var _handlebarsCompilerCompiler=require('./handlebars/compiler/compiler');var _handlebarsCompilerJavascriptCompiler=require('./handlebars/compiler/javascript-compiler');var _handlebarsCompilerJavascriptCompiler2=_interopRequireDefault(_handlebarsCompilerJavascriptCompiler);var _handlebarsCompilerVisitor=require('./handlebars/compiler/visitor');var _handlebarsCompilerVisitor2=_interopRequireDefault(_handlebarsCompilerVisitor);var _handlebarsNoConflict=require('./handlebars/no-conflict');var _handlebarsNoConflict2=_interopRequireDefault(_handlebarsNoConflict);var _create=_handlebarsRuntime2['default'].create;function create(){var hb=_create();hb.compile=function(input,options){return _handlebarsCompilerCompiler.compile(input,options,hb);};hb.precompile=function(input,options){return _handlebarsCompilerCompiler.precompile(input,options,hb);};hb.AST=_handlebarsCompilerAst2['default'];hb.Compiler=_handlebarsCompilerCompiler.Compiler;hb.JavaScriptCompiler=_handlebarsCompilerJavascriptCompiler2['default'];hb.Parser=_handlebarsCompilerBase.parser;hb.parse=_handlebarsCompilerBase.parse;return hb;}
var inst=create();inst.create=create;_handlebarsNoConflict2['default'](inst);inst.Visitor=_handlebarsCompilerVisitor2['default'];inst['default']=inst;exports['default']=inst;module.exports=exports['default'];},{"./handlebars.runtime":248,"./handlebars/compiler/ast":250,"./handlebars/compiler/base":251,"./handlebars/compiler/compiler":253,"./handlebars/compiler/javascript-compiler":255,"./handlebars/compiler/visitor":258,"./handlebars/no-conflict":272}],248:[function(require,module,exports){'use strict';exports.__esModule=true;function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{'default':obj};}
function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj['default']=obj;return newObj;}}
var _handlebarsBase=require('./handlebars/base');var base=_interopRequireWildcard(_handlebarsBase);var _handlebarsSafeString=require('./handlebars/safe-string');var _handlebarsSafeString2=_interopRequireDefault(_handlebarsSafeString);var _handlebarsException=require('./handlebars/exception');var _handlebarsException2=_interopRequireDefault(_handlebarsException);var _handlebarsUtils=require('./handlebars/utils');var Utils=_interopRequireWildcard(_handlebarsUtils);var _handlebarsRuntime=require('./handlebars/runtime');var runtime=_interopRequireWildcard(_handlebarsRuntime);var _handlebarsNoConflict=require('./handlebars/no-conflict');var _handlebarsNoConflict2=_interopRequireDefault(_handlebarsNoConflict);function create(){var hb=new base.HandlebarsEnvironment();Utils.extend(hb,base);hb.SafeString=_handlebarsSafeString2['default'];hb.Exception=_handlebarsException2['default'];hb.Utils=Utils;hb.escapeExpression=Utils.escapeExpression;hb.VM=runtime;hb.template=function(spec){return runtime.template(spec,hb);};return hb;}
var inst=create();inst.create=create;_handlebarsNoConflict2['default'](inst);inst['default']=inst;exports['default']=inst;module.exports=exports['default'];},{"./handlebars/base":249,"./handlebars/exception":262,"./handlebars/no-conflict":272,"./handlebars/runtime":273,"./handlebars/safe-string":274,"./handlebars/utils":275}],249:[function(require,module,exports){'use strict';exports.__esModule=true;exports.HandlebarsEnvironment=HandlebarsEnvironment;function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{'default':obj};}
var _utils=require('./utils');var _exception=require('./exception');var _exception2=_interopRequireDefault(_exception);var _helpers=require('./helpers');var _decorators=require('./decorators');var _logger=require('./logger');var _logger2=_interopRequireDefault(_logger);var VERSION='4.0.5';exports.VERSION=VERSION;var COMPILER_REVISION=7;exports.COMPILER_REVISION=COMPILER_REVISION;var REVISION_CHANGES={1:'<= 1.0.rc.2',2:'== 1.0.0-rc.3',3:'== 1.0.0-rc.4',4:'== 1.x.x',5:'== 2.0.0-alpha.x',6:'>= 2.0.0-beta.1',7:'>= 4.0.0'};exports.REVISION_CHANGES=REVISION_CHANGES;var objectType='[object Object]';function HandlebarsEnvironment(helpers,partials,decorators){this.helpers=helpers||{};this.partials=partials||{};this.decorators=decorators||{};_helpers.registerDefaultHelpers(this);_decorators.registerDefaultDecorators(this);}
HandlebarsEnvironment.prototype={constructor:HandlebarsEnvironment,logger:_logger2['default'],log:_logger2['default'].log,registerHelper:function registerHelper(name,fn){if(_utils.toString.call(name)===objectType){if(fn){throw new _exception2['default']('Arg not supported with multiple helpers');}
_utils.extend(this.helpers,name);}else{this.helpers[name]=fn;}},unregisterHelper:function unregisterHelper(name){delete this.helpers[name];},registerPartial:function registerPartial(name,partial){if(_utils.toString.call(name)===objectType){_utils.extend(this.partials,name);}else{if(typeof partial==='undefined'){throw new _exception2['default']('Attempting to register a partial called "'+name+'" as undefined');}
this.partials[name]=partial;}},unregisterPartial:function unregisterPartial(name){delete this.partials[name];},registerDecorator:function registerDecorator(name,fn){if(_utils.toString.call(name)===objectType){if(fn){throw new _exception2['default']('Arg not supported with multiple decorators');}
_utils.extend(this.decorators,name);}else{this.decorators[name]=fn;}},unregisterDecorator:function unregisterDecorator(name){delete this.decorators[name];}};var log=_logger2['default'].log;exports.log=log;exports.createFrame=_utils.createFrame;exports.logger=_logger2['default'];},{"./decorators":260,"./exception":262,"./helpers":263,"./logger":271,"./utils":275}],250:[function(require,module,exports){'use strict';exports.__esModule=true;var AST={helpers:{helperExpression:function helperExpression(node){return node.type==='SubExpression'||(node.type==='MustacheStatement'||node.type==='BlockStatement')&&!!(node.params&&node.params.length||node.hash);},scopedId:function scopedId(path){return(/^\.|this\b/.test(path.original));},simpleId:function simpleId(path){return path.parts.length===1&&!AST.helpers.scopedId(path)&&!path.depth;}}};exports['default']=AST;module.exports=exports['default'];},{}],251:[function(require,module,exports){'use strict';exports.__esModule=true;exports.parse=parse;function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj['default']=obj;return newObj;}}
function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{'default':obj};}
var _parser=require('./parser');var _parser2=_interopRequireDefault(_parser);var _whitespaceControl=require('./whitespace-control');var _whitespaceControl2=_interopRequireDefault(_whitespaceControl);var _helpers=require('./helpers');var Helpers=_interopRequireWildcard(_helpers);var _utils=require('../utils');exports.parser=_parser2['default'];var yy={};_utils.extend(yy,Helpers);function parse(input,options){if(input.type==='Program'){return input;}
_parser2['default'].yy=yy;yy.locInfo=function(locInfo){return new yy.SourceLocation(options&&options.srcName,locInfo);};var strip=new _whitespaceControl2['default'](options);return strip.accept(_parser2['default'].parse(input));}},{"../utils":275,"./helpers":254,"./parser":256,"./whitespace-control":259}],252:[function(require,module,exports){'use strict';exports.__esModule=true;var _utils=require('../utils');var SourceNode=undefined;try{if(typeof define!=='function'||!define.amd){var SourceMap=require('source-map');SourceNode=SourceMap.SourceNode;}}catch(err){}
if(!SourceNode){SourceNode=function(line,column,srcFile,chunks){this.src='';if(chunks){this.add(chunks);}};SourceNode.prototype={add:function add(chunks){if(_utils.isArray(chunks)){chunks=chunks.join('');}
this.src+=chunks;},prepend:function prepend(chunks){if(_utils.isArray(chunks)){chunks=chunks.join('');}
this.src=chunks+this.src;},toStringWithSourceMap:function toStringWithSourceMap(){return{code:this.toString()};},toString:function toString(){return this.src;}};}
function castChunk(chunk,codeGen,loc){if(_utils.isArray(chunk)){var ret=[];for(var i=0,len=chunk.length;i<len;i++){ret.push(codeGen.wrap(chunk[i],loc));}
return ret;}else if(typeof chunk==='boolean'||typeof chunk==='number'){return chunk+'';}
return chunk;}
function CodeGen(srcFile){this.srcFile=srcFile;this.source=[];}
CodeGen.prototype={isEmpty:function isEmpty(){return!this.source.length;},prepend:function prepend(source,loc){this.source.unshift(this.wrap(source,loc));},push:function push(source,loc){this.source.push(this.wrap(source,loc));},merge:function merge(){var source=this.empty();this.each(function(line){source.add(['  ',line,'\n']);});return source;},each:function each(iter){for(var i=0,len=this.source.length;i<len;i++){iter(this.source[i]);}},empty:function empty(){var loc=this.currentLocation||{start:{}};return new SourceNode(loc.start.line,loc.start.column,this.srcFile);},wrap:function wrap(chunk){var loc=arguments.length<=1||arguments[1]===undefined?this.currentLocation||{start:{}}:arguments[1];if(chunk instanceof SourceNode){return chunk;}
chunk=castChunk(chunk,this,loc);return new SourceNode(loc.start.line,loc.start.column,this.srcFile,chunk);},functionCall:function functionCall(fn,type,params){params=this.generateList(params);return this.wrap([fn,type?'.'+type+'(':'(',params,')']);},quotedString:function quotedString(str){return'"'+(str+'').replace(/\\/g,'\\\\').replace(/"/g,'\\"').replace(/\n/g,'\\n').replace(/\r/g,'\\r').replace(/\u2028/g,'\\u2028').replace(/\u2029/g,'\\u2029')+'"';},objectLiteral:function objectLiteral(obj){var pairs=[];for(var key in obj){if(obj.hasOwnProperty(key)){var value=castChunk(obj[key],this);if(value!=='undefined'){pairs.push([this.quotedString(key),':',value]);}}}
var ret=this.generateList(pairs);ret.prepend('{');ret.add('}');return ret;},generateList:function generateList(entries){var ret=this.empty();for(var i=0,len=entries.length;i<len;i++){if(i){ret.add(',');}
ret.add(castChunk(entries[i],this));}
return ret;},generateArray:function generateArray(entries){var ret=this.generateList(entries);ret.prepend('[');ret.add(']');return ret;}};exports['default']=CodeGen;module.exports=exports['default'];},{"../utils":275,"source-map":199}],253:[function(require,module,exports){'use strict';exports.__esModule=true;exports.Compiler=Compiler;exports.precompile=precompile;exports.compile=compile;function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{'default':obj};}
var _exception=require('../exception');var _exception2=_interopRequireDefault(_exception);var _utils=require('../utils');var _ast=require('./ast');var _ast2=_interopRequireDefault(_ast);var slice=[].slice;function Compiler(){}
Compiler.prototype={compiler:Compiler,equals:function equals(other){var len=this.opcodes.length;if(other.opcodes.length!==len){return false;}
for(var i=0;i<len;i++){var opcode=this.opcodes[i],otherOpcode=other.opcodes[i];if(opcode.opcode!==otherOpcode.opcode||!argEquals(opcode.args,otherOpcode.args)){return false;}}
len=this.children.length;for(var i=0;i<len;i++){if(!this.children[i].equals(other.children[i])){return false;}}
return true;},guid:0,compile:function compile(program,options){this.sourceNode=[];this.opcodes=[];this.children=[];this.options=options;this.stringParams=options.stringParams;this.trackIds=options.trackIds;options.blockParams=options.blockParams||[];var knownHelpers=options.knownHelpers;options.knownHelpers={'helperMissing':true,'blockHelperMissing':true,'each':true,'if':true,'unless':true,'with':true,'log':true,'lookup':true};if(knownHelpers){for(var _name in knownHelpers){if(_name in knownHelpers){options.knownHelpers[_name]=knownHelpers[_name];}}}
return this.accept(program);},compileProgram:function compileProgram(program){var childCompiler=new this.compiler(),result=childCompiler.compile(program,this.options),guid=this.guid++;this.usePartial=this.usePartial||result.usePartial;this.children[guid]=result;this.useDepths=this.useDepths||result.useDepths;return guid;},accept:function accept(node){if(!this[node.type]){throw new _exception2['default']('Unknown type: '+node.type,node);}
this.sourceNode.unshift(node);var ret=this[node.type](node);this.sourceNode.shift();return ret;},Program:function Program(program){this.options.blockParams.unshift(program.blockParams);var body=program.body,bodyLength=body.length;for(var i=0;i<bodyLength;i++){this.accept(body[i]);}
this.options.blockParams.shift();this.isSimple=bodyLength===1;this.blockParams=program.blockParams?program.blockParams.length:0;return this;},BlockStatement:function BlockStatement(block){transformLiteralToPath(block);var program=block.program,inverse=block.inverse;program=program&&this.compileProgram(program);inverse=inverse&&this.compileProgram(inverse);var type=this.classifySexpr(block);if(type==='helper'){this.helperSexpr(block,program,inverse);}else if(type==='simple'){this.simpleSexpr(block);this.opcode('pushProgram',program);this.opcode('pushProgram',inverse);this.opcode('emptyHash');this.opcode('blockValue',block.path.original);}else{this.ambiguousSexpr(block,program,inverse);this.opcode('pushProgram',program);this.opcode('pushProgram',inverse);this.opcode('emptyHash');this.opcode('ambiguousBlockValue');}
this.opcode('append');},DecoratorBlock:function DecoratorBlock(decorator){var program=decorator.program&&this.compileProgram(decorator.program);var params=this.setupFullMustacheParams(decorator,program,undefined),path=decorator.path;this.useDecorators=true;this.opcode('registerDecorator',params.length,path.original);},PartialStatement:function PartialStatement(partial){this.usePartial=true;var program=partial.program;if(program){program=this.compileProgram(partial.program);}
var params=partial.params;if(params.length>1){throw new _exception2['default']('Unsupported number of partial arguments: '+params.length,partial);}else if(!params.length){if(this.options.explicitPartialContext){this.opcode('pushLiteral','undefined');}else{params.push({type:'PathExpression',parts:[],depth:0});}}
var partialName=partial.name.original,isDynamic=partial.name.type==='SubExpression';if(isDynamic){this.accept(partial.name);}
this.setupFullMustacheParams(partial,program,undefined,true);var indent=partial.indent||'';if(this.options.preventIndent&&indent){this.opcode('appendContent',indent);indent='';}
this.opcode('invokePartial',isDynamic,partialName,indent);this.opcode('append');},PartialBlockStatement:function PartialBlockStatement(partialBlock){this.PartialStatement(partialBlock);},MustacheStatement:function MustacheStatement(mustache){this.SubExpression(mustache);if(mustache.escaped&&!this.options.noEscape){this.opcode('appendEscaped');}else{this.opcode('append');}},Decorator:function Decorator(decorator){this.DecoratorBlock(decorator);},ContentStatement:function ContentStatement(content){if(content.value){this.opcode('appendContent',content.value);}},CommentStatement:function CommentStatement(){},SubExpression:function SubExpression(sexpr){transformLiteralToPath(sexpr);var type=this.classifySexpr(sexpr);if(type==='simple'){this.simpleSexpr(sexpr);}else if(type==='helper'){this.helperSexpr(sexpr);}else{this.ambiguousSexpr(sexpr);}},ambiguousSexpr:function ambiguousSexpr(sexpr,program,inverse){var path=sexpr.path,name=path.parts[0],isBlock=program!=null||inverse!=null;this.opcode('getContext',path.depth);this.opcode('pushProgram',program);this.opcode('pushProgram',inverse);path.strict=true;this.accept(path);this.opcode('invokeAmbiguous',name,isBlock);},simpleSexpr:function simpleSexpr(sexpr){var path=sexpr.path;path.strict=true;this.accept(path);this.opcode('resolvePossibleLambda');},helperSexpr:function helperSexpr(sexpr,program,inverse){var params=this.setupFullMustacheParams(sexpr,program,inverse),path=sexpr.path,name=path.parts[0];if(this.options.knownHelpers[name]){this.opcode('invokeKnownHelper',params.length,name);}else if(this.options.knownHelpersOnly){throw new _exception2['default']('You specified knownHelpersOnly, but used the unknown helper '+name,sexpr);}else{path.strict=true;path.falsy=true;this.accept(path);this.opcode('invokeHelper',params.length,path.original,_ast2['default'].helpers.simpleId(path));}},PathExpression:function PathExpression(path){this.addDepth(path.depth);this.opcode('getContext',path.depth);var name=path.parts[0],scoped=_ast2['default'].helpers.scopedId(path),blockParamId=!path.depth&&!scoped&&this.blockParamIndex(name);if(blockParamId){this.opcode('lookupBlockParam',blockParamId,path.parts);}else if(!name){this.opcode('pushContext');}else if(path.data){this.options.data=true;this.opcode('lookupData',path.depth,path.parts,path.strict);}else{this.opcode('lookupOnContext',path.parts,path.falsy,path.strict,scoped);}},StringLiteral:function StringLiteral(string){this.opcode('pushString',string.value);},NumberLiteral:function NumberLiteral(number){this.opcode('pushLiteral',number.value);},BooleanLiteral:function BooleanLiteral(bool){this.opcode('pushLiteral',bool.value);},UndefinedLiteral:function UndefinedLiteral(){this.opcode('pushLiteral','undefined');},NullLiteral:function NullLiteral(){this.opcode('pushLiteral','null');},Hash:function Hash(hash){var pairs=hash.pairs,i=0,l=pairs.length;this.opcode('pushHash');for(;i<l;i++){this.pushParam(pairs[i].value);}
while(i--){this.opcode('assignToHash',pairs[i].key);}
this.opcode('popHash');},opcode:function opcode(name){this.opcodes.push({opcode:name,args:slice.call(arguments,1),loc:this.sourceNode[0].loc});},addDepth:function addDepth(depth){if(!depth){return;}
this.useDepths=true;},classifySexpr:function classifySexpr(sexpr){var isSimple=_ast2['default'].helpers.simpleId(sexpr.path);var isBlockParam=isSimple&&!!this.blockParamIndex(sexpr.path.parts[0]);var isHelper=!isBlockParam&&_ast2['default'].helpers.helperExpression(sexpr);var isEligible=!isBlockParam&&(isHelper||isSimple);if(isEligible&&!isHelper){var _name2=sexpr.path.parts[0],options=this.options;if(options.knownHelpers[_name2]){isHelper=true;}else if(options.knownHelpersOnly){isEligible=false;}}
if(isHelper){return'helper';}else if(isEligible){return'ambiguous';}else{return'simple';}},pushParams:function pushParams(params){for(var i=0,l=params.length;i<l;i++){this.pushParam(params[i]);}},pushParam:function pushParam(val){var value=val.value!=null?val.value:val.original||'';if(this.stringParams){if(value.replace){value=value.replace(/^(\.?\.\/)*/g,'').replace(/\//g,'.');}
if(val.depth){this.addDepth(val.depth);}
this.opcode('getContext',val.depth||0);this.opcode('pushStringParam',value,val.type);if(val.type==='SubExpression'){this.accept(val);}}else{if(this.trackIds){var blockParamIndex=undefined;if(val.parts&&!_ast2['default'].helpers.scopedId(val)&&!val.depth){blockParamIndex=this.blockParamIndex(val.parts[0]);}
if(blockParamIndex){var blockParamChild=val.parts.slice(1).join('.');this.opcode('pushId','BlockParam',blockParamIndex,blockParamChild);}else{value=val.original||value;if(value.replace){value=value.replace(/^this(?:\.|$)/,'').replace(/^\.\//,'').replace(/^\.$/,'');}
this.opcode('pushId',val.type,value);}}
this.accept(val);}},setupFullMustacheParams:function setupFullMustacheParams(sexpr,program,inverse,omitEmpty){var params=sexpr.params;this.pushParams(params);this.opcode('pushProgram',program);this.opcode('pushProgram',inverse);if(sexpr.hash){this.accept(sexpr.hash);}else{this.opcode('emptyHash',omitEmpty);}
return params;},blockParamIndex:function blockParamIndex(name){for(var depth=0,len=this.options.blockParams.length;depth<len;depth++){var blockParams=this.options.blockParams[depth],param=blockParams&&_utils.indexOf(blockParams,name);if(blockParams&&param>=0){return[depth,param];}}}};function precompile(input,options,env){if(input==null||typeof input!=='string'&&input.type!=='Program'){throw new _exception2['default']('You must pass a string or Handlebars AST to Handlebars.precompile. You passed '+input);}
options=options||{};if(!('data'in options)){options.data=true;}
if(options.compat){options.useDepths=true;}
var ast=env.parse(input,options),environment=new env.Compiler().compile(ast,options);return new env.JavaScriptCompiler().compile(environment,options);}
function compile(input,options,env){if(options===undefined)options={};if(input==null||typeof input!=='string'&&input.type!=='Program'){throw new _exception2['default']('You must pass a string or Handlebars AST to Handlebars.compile. You passed '+input);}
if(!('data'in options)){options.data=true;}
if(options.compat){options.useDepths=true;}
var compiled=undefined;function compileInput(){var ast=env.parse(input,options),environment=new env.Compiler().compile(ast,options),templateSpec=new env.JavaScriptCompiler().compile(environment,options,undefined,true);return env.template(templateSpec);}
function ret(context,execOptions){if(!compiled){compiled=compileInput();}
return compiled.call(this,context,execOptions);}
ret._setup=function(setupOptions){if(!compiled){compiled=compileInput();}
return compiled._setup(setupOptions);};ret._child=function(i,data,blockParams,depths){if(!compiled){compiled=compileInput();}
return compiled._child(i,data,blockParams,depths);};return ret;}
function argEquals(a,b){if(a===b){return true;}
if(_utils.isArray(a)&&_utils.isArray(b)&&a.length===b.length){for(var i=0;i<a.length;i++){if(!argEquals(a[i],b[i])){return false;}}
return true;}}
function transformLiteralToPath(sexpr){if(!sexpr.path.parts){var literal=sexpr.path;sexpr.path={type:'PathExpression',data:false,depth:0,parts:[literal.original+''],original:literal.original+'',loc:literal.loc};}}},{"../exception":262,"../utils":275,"./ast":250}],254:[function(require,module,exports){'use strict';exports.__esModule=true;exports.SourceLocation=SourceLocation;exports.id=id;exports.stripFlags=stripFlags;exports.stripComment=stripComment;exports.preparePath=preparePath;exports.prepareMustache=prepareMustache;exports.prepareRawBlock=prepareRawBlock;exports.prepareBlock=prepareBlock;exports.prepareProgram=prepareProgram;exports.preparePartialBlock=preparePartialBlock;function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{'default':obj};}
var _exception=require('../exception');var _exception2=_interopRequireDefault(_exception);function validateClose(open,close){close=close.path?close.path.original:close;if(open.path.original!==close){var errorNode={loc:open.path.loc};throw new _exception2['default'](open.path.original+" doesn't match "+close,errorNode);}}
function SourceLocation(source,locInfo){this.source=source;this.start={line:locInfo.first_line,column:locInfo.first_column};this.end={line:locInfo.last_line,column:locInfo.last_column};}
function id(token){if(/^\[.*\]$/.test(token)){return token.substr(1,token.length-2);}else{return token;}}
function stripFlags(open,close){return{open:open.charAt(2)==='~',close:close.charAt(close.length-3)==='~'};}
function stripComment(comment){return comment.replace(/^\{\{~?\!-?-?/,'').replace(/-?-?~?\}\}$/,'');}
function preparePath(data,parts,loc){loc=this.locInfo(loc);var original=data?'@':'',dig=[],depth=0,depthString='';for(var i=0,l=parts.length;i<l;i++){var part=parts[i].part,isLiteral=parts[i].original!==part;original+=(parts[i].separator||'')+part;if(!isLiteral&&(part==='..'||part==='.'||part==='this')){if(dig.length>0){throw new _exception2['default']('Invalid path: '+original,{loc:loc});}else if(part==='..'){depth++;depthString+='../';}}else{dig.push(part);}}
return{type:'PathExpression',data:data,depth:depth,parts:dig,original:original,loc:loc};}
function prepareMustache(path,params,hash,open,strip,locInfo){var escapeFlag=open.charAt(3)||open.charAt(2),escaped=escapeFlag!=='{'&&escapeFlag!=='&';var decorator=/\*/.test(open);return{type:decorator?'Decorator':'MustacheStatement',path:path,params:params,hash:hash,escaped:escaped,strip:strip,loc:this.locInfo(locInfo)};}
function prepareRawBlock(openRawBlock,contents,close,locInfo){validateClose(openRawBlock,close);locInfo=this.locInfo(locInfo);var program={type:'Program',body:contents,strip:{},loc:locInfo};return{type:'BlockStatement',path:openRawBlock.path,params:openRawBlock.params,hash:openRawBlock.hash,program:program,openStrip:{},inverseStrip:{},closeStrip:{},loc:locInfo};}
function prepareBlock(openBlock,program,inverseAndProgram,close,inverted,locInfo){if(close&&close.path){validateClose(openBlock,close);}
var decorator=/\*/.test(openBlock.open);program.blockParams=openBlock.blockParams;var inverse=undefined,inverseStrip=undefined;if(inverseAndProgram){if(decorator){throw new _exception2['default']('Unexpected inverse block on decorator',inverseAndProgram);}
if(inverseAndProgram.chain){inverseAndProgram.program.body[0].closeStrip=close.strip;}
inverseStrip=inverseAndProgram.strip;inverse=inverseAndProgram.program;}
if(inverted){inverted=inverse;inverse=program;program=inverted;}
return{type:decorator?'DecoratorBlock':'BlockStatement',path:openBlock.path,params:openBlock.params,hash:openBlock.hash,program:program,inverse:inverse,openStrip:openBlock.strip,inverseStrip:inverseStrip,closeStrip:close&&close.strip,loc:this.locInfo(locInfo)};}
function prepareProgram(statements,loc){if(!loc&&statements.length){var firstLoc=statements[0].loc,lastLoc=statements[statements.length-1].loc;if(firstLoc&&lastLoc){loc={source:firstLoc.source,start:{line:firstLoc.start.line,column:firstLoc.start.column},end:{line:lastLoc.end.line,column:lastLoc.end.column}};}}
return{type:'Program',body:statements,strip:{},loc:loc};}
function preparePartialBlock(open,program,close,locInfo){validateClose(open,close);return{type:'PartialBlockStatement',name:open.path,params:open.params,hash:open.hash,program:program,openStrip:open.strip,closeStrip:close&&close.strip,loc:this.locInfo(locInfo)};}},{"../exception":262}],255:[function(require,module,exports){'use strict';exports.__esModule=true;function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{'default':obj};}
var _base=require('../base');var _exception=require('../exception');var _exception2=_interopRequireDefault(_exception);var _utils=require('../utils');var _codeGen=require('./code-gen');var _codeGen2=_interopRequireDefault(_codeGen);function Literal(value){this.value=value;}
function JavaScriptCompiler(){}
JavaScriptCompiler.prototype={nameLookup:function nameLookup(parent,name){if(JavaScriptCompiler.isValidJavaScriptVariableName(name)){return[parent,'.',name];}else{return[parent,'[',JSON.stringify(name),']'];}},depthedLookup:function depthedLookup(name){return[this.aliasable('container.lookup'),'(depths, "',name,'")'];},compilerInfo:function compilerInfo(){var revision=_base.COMPILER_REVISION,versions=_base.REVISION_CHANGES[revision];return[revision,versions];},appendToBuffer:function appendToBuffer(source,location,explicit){if(!_utils.isArray(source)){source=[source];}
source=this.source.wrap(source,location);if(this.environment.isSimple){return['return ',source,';'];}else if(explicit){return['buffer += ',source,';'];}else{source.appendToBuffer=true;return source;}},initializeBuffer:function initializeBuffer(){return this.quotedString('');},compile:function compile(environment,options,context,asObject){this.environment=environment;this.options=options;this.stringParams=this.options.stringParams;this.trackIds=this.options.trackIds;this.precompile=!asObject;this.name=this.environment.name;this.isChild=!!context;this.context=context||{decorators:[],programs:[],environments:[]};this.preamble();this.stackSlot=0;this.stackVars=[];this.aliases={};this.registers={list:[]};this.hashes=[];this.compileStack=[];this.inlineStack=[];this.blockParams=[];this.compileChildren(environment,options);this.useDepths=this.useDepths||environment.useDepths||environment.useDecorators||this.options.compat;this.useBlockParams=this.useBlockParams||environment.useBlockParams;var opcodes=environment.opcodes,opcode=undefined,firstLoc=undefined,i=undefined,l=undefined;for(i=0,l=opcodes.length;i<l;i++){opcode=opcodes[i];this.source.currentLocation=opcode.loc;firstLoc=firstLoc||opcode.loc;this[opcode.opcode].apply(this,opcode.args);}
this.source.currentLocation=firstLoc;this.pushSource('');if(this.stackSlot||this.inlineStack.length||this.compileStack.length){throw new _exception2['default']('Compile completed with content left on stack');}
if(!this.decorators.isEmpty()){this.useDecorators=true;this.decorators.prepend('var decorators = container.decorators;\n');this.decorators.push('return fn;');if(asObject){this.decorators=Function.apply(this,['fn','props','container','depth0','data','blockParams','depths',this.decorators.merge()]);}else{this.decorators.prepend('function(fn, props, container, depth0, data, blockParams, depths) {\n');this.decorators.push('}\n');this.decorators=this.decorators.merge();}}else{this.decorators=undefined;}
var fn=this.createFunctionContext(asObject);if(!this.isChild){var ret={compiler:this.compilerInfo(),main:fn};if(this.decorators){ret.main_d=this.decorators;ret.useDecorators=true;}
var _context=this.context;var programs=_context.programs;var decorators=_context.decorators;for(i=0,l=programs.length;i<l;i++){if(programs[i]){ret[i]=programs[i];if(decorators[i]){ret[i+'_d']=decorators[i];ret.useDecorators=true;}}}
if(this.environment.usePartial){ret.usePartial=true;}
if(this.options.data){ret.useData=true;}
if(this.useDepths){ret.useDepths=true;}
if(this.useBlockParams){ret.useBlockParams=true;}
if(this.options.compat){ret.compat=true;}
if(!asObject){ret.compiler=JSON.stringify(ret.compiler);this.source.currentLocation={start:{line:1,column:0}};ret=this.objectLiteral(ret);if(options.srcName){ret=ret.toStringWithSourceMap({file:options.destName});ret.map=ret.map&&ret.map.toString();}else{ret=ret.toString();}}else{ret.compilerOptions=this.options;}
return ret;}else{return fn;}},preamble:function preamble(){this.lastContext=0;this.source=new _codeGen2['default'](this.options.srcName);this.decorators=new _codeGen2['default'](this.options.srcName);},createFunctionContext:function createFunctionContext(asObject){var varDeclarations='';var locals=this.stackVars.concat(this.registers.list);if(locals.length>0){varDeclarations+=', '+locals.join(', ');}
var aliasCount=0;for(var alias in this.aliases){var node=this.aliases[alias];if(this.aliases.hasOwnProperty(alias)&&node.children&&node.referenceCount>1){varDeclarations+=', alias'+ ++aliasCount+'='+alias;node.children[0]='alias'+aliasCount;}}
var params=['container','depth0','helpers','partials','data'];if(this.useBlockParams||this.useDepths){params.push('blockParams');}
if(this.useDepths){params.push('depths');}
var source=this.mergeSource(varDeclarations);if(asObject){params.push(source);return Function.apply(this,params);}else{return this.source.wrap(['function(',params.join(','),') {\n  ',source,'}']);}},mergeSource:function mergeSource(varDeclarations){var isSimple=this.environment.isSimple,appendOnly=!this.forceBuffer,appendFirst=undefined,sourceSeen=undefined,bufferStart=undefined,bufferEnd=undefined;this.source.each(function(line){if(line.appendToBuffer){if(bufferStart){line.prepend('  + ');}else{bufferStart=line;}
bufferEnd=line;}else{if(bufferStart){if(!sourceSeen){appendFirst=true;}else{bufferStart.prepend('buffer += ');}
bufferEnd.add(';');bufferStart=bufferEnd=undefined;}
sourceSeen=true;if(!isSimple){appendOnly=false;}}});if(appendOnly){if(bufferStart){bufferStart.prepend('return ');bufferEnd.add(';');}else if(!sourceSeen){this.source.push('return "";');}}else{varDeclarations+=', buffer = '+(appendFirst?'':this.initializeBuffer());if(bufferStart){bufferStart.prepend('return buffer + ');bufferEnd.add(';');}else{this.source.push('return buffer;');}}
if(varDeclarations){this.source.prepend('var '+varDeclarations.substring(2)+(appendFirst?'':';\n'));}
return this.source.merge();},blockValue:function blockValue(name){var blockHelperMissing=this.aliasable('helpers.blockHelperMissing'),params=[this.contextName(0)];this.setupHelperArgs(name,0,params);var blockName=this.popStack();params.splice(1,0,blockName);this.push(this.source.functionCall(blockHelperMissing,'call',params));},ambiguousBlockValue:function ambiguousBlockValue(){var blockHelperMissing=this.aliasable('helpers.blockHelperMissing'),params=[this.contextName(0)];this.setupHelperArgs('',0,params,true);this.flushInline();var current=this.topStack();params.splice(1,0,current);this.pushSource(['if (!',this.lastHelper,') { ',current,' = ',this.source.functionCall(blockHelperMissing,'call',params),'}']);},appendContent:function appendContent(content){if(this.pendingContent){content=this.pendingContent+content;}else{this.pendingLocation=this.source.currentLocation;}
this.pendingContent=content;},append:function append(){if(this.isInline()){this.replaceStack(function(current){return[' != null ? ',current,' : ""'];});this.pushSource(this.appendToBuffer(this.popStack()));}else{var local=this.popStack();this.pushSource(['if (',local,' != null) { ',this.appendToBuffer(local,undefined,true),' }']);if(this.environment.isSimple){this.pushSource(['else { ',this.appendToBuffer("''",undefined,true),' }']);}}},appendEscaped:function appendEscaped(){this.pushSource(this.appendToBuffer([this.aliasable('container.escapeExpression'),'(',this.popStack(),')']));},getContext:function getContext(depth){this.lastContext=depth;},pushContext:function pushContext(){this.pushStackLiteral(this.contextName(this.lastContext));},lookupOnContext:function lookupOnContext(parts,falsy,strict,scoped){var i=0;if(!scoped&&this.options.compat&&!this.lastContext){this.push(this.depthedLookup(parts[i++]));}else{this.pushContext();}
this.resolvePath('context',parts,i,falsy,strict);},lookupBlockParam:function lookupBlockParam(blockParamId,parts){this.useBlockParams=true;this.push(['blockParams[',blockParamId[0],'][',blockParamId[1],']']);this.resolvePath('context',parts,1);},lookupData:function lookupData(depth,parts,strict){if(!depth){this.pushStackLiteral('data');}else{this.pushStackLiteral('container.data(data, '+depth+')');}
this.resolvePath('data',parts,0,true,strict);},resolvePath:function resolvePath(type,parts,i,falsy,strict){var _this=this;if(this.options.strict||this.options.assumeObjects){this.push(strictLookup(this.options.strict&&strict,this,parts,type));return;}
var len=parts.length;for(;i<len;i++){this.replaceStack(function(current){var lookup=_this.nameLookup(current,parts[i],type);if(!falsy){return[' != null ? ',lookup,' : ',current];}else{return[' && ',lookup];}});}},resolvePossibleLambda:function resolvePossibleLambda(){this.push([this.aliasable('container.lambda'),'(',this.popStack(),', ',this.contextName(0),')']);},pushStringParam:function pushStringParam(string,type){this.pushContext();this.pushString(type);if(type!=='SubExpression'){if(typeof string==='string'){this.pushString(string);}else{this.pushStackLiteral(string);}}},emptyHash:function emptyHash(omitEmpty){if(this.trackIds){this.push('{}');}
if(this.stringParams){this.push('{}');this.push('{}');}
this.pushStackLiteral(omitEmpty?'undefined':'{}');},pushHash:function pushHash(){if(this.hash){this.hashes.push(this.hash);}
this.hash={values:[],types:[],contexts:[],ids:[]};},popHash:function popHash(){var hash=this.hash;this.hash=this.hashes.pop();if(this.trackIds){this.push(this.objectLiteral(hash.ids));}
if(this.stringParams){this.push(this.objectLiteral(hash.contexts));this.push(this.objectLiteral(hash.types));}
this.push(this.objectLiteral(hash.values));},pushString:function pushString(string){this.pushStackLiteral(this.quotedString(string));},pushLiteral:function pushLiteral(value){this.pushStackLiteral(value);},pushProgram:function pushProgram(guid){if(guid!=null){this.pushStackLiteral(this.programExpression(guid));}else{this.pushStackLiteral(null);}},registerDecorator:function registerDecorator(paramSize,name){var foundDecorator=this.nameLookup('decorators',name,'decorator'),options=this.setupHelperArgs(name,paramSize);this.decorators.push(['fn = ',this.decorators.functionCall(foundDecorator,'',['fn','props','container',options]),' || fn;']);},invokeHelper:function invokeHelper(paramSize,name,isSimple){var nonHelper=this.popStack(),helper=this.setupHelper(paramSize,name),simple=isSimple?[helper.name,' || ']:'';var lookup=['('].concat(simple,nonHelper);if(!this.options.strict){lookup.push(' || ',this.aliasable('helpers.helperMissing'));}
lookup.push(')');this.push(this.source.functionCall(lookup,'call',helper.callParams));},invokeKnownHelper:function invokeKnownHelper(paramSize,name){var helper=this.setupHelper(paramSize,name);this.push(this.source.functionCall(helper.name,'call',helper.callParams));},invokeAmbiguous:function invokeAmbiguous(name,helperCall){this.useRegister('helper');var nonHelper=this.popStack();this.emptyHash();var helper=this.setupHelper(0,name,helperCall);var helperName=this.lastHelper=this.nameLookup('helpers',name,'helper');var lookup=['(','(helper = ',helperName,' || ',nonHelper,')'];if(!this.options.strict){lookup[0]='(helper = ';lookup.push(' != null ? helper : ',this.aliasable('helpers.helperMissing'));}
this.push(['(',lookup,helper.paramsInit?['),(',helper.paramsInit]:[],'),','(typeof helper === ',this.aliasable('"function"'),' ? ',this.source.functionCall('helper','call',helper.callParams),' : helper))']);},invokePartial:function invokePartial(isDynamic,name,indent){var params=[],options=this.setupParams(name,1,params);if(isDynamic){name=this.popStack();delete options.name;}
if(indent){options.indent=JSON.stringify(indent);}
options.helpers='helpers';options.partials='partials';options.decorators='container.decorators';if(!isDynamic){params.unshift(this.nameLookup('partials',name,'partial'));}else{params.unshift(name);}
if(this.options.compat){options.depths='depths';}
options=this.objectLiteral(options);params.push(options);this.push(this.source.functionCall('container.invokePartial','',params));},assignToHash:function assignToHash(key){var value=this.popStack(),context=undefined,type=undefined,id=undefined;if(this.trackIds){id=this.popStack();}
if(this.stringParams){type=this.popStack();context=this.popStack();}
var hash=this.hash;if(context){hash.contexts[key]=context;}
if(type){hash.types[key]=type;}
if(id){hash.ids[key]=id;}
hash.values[key]=value;},pushId:function pushId(type,name,child){if(type==='BlockParam'){this.pushStackLiteral('blockParams['+name[0]+'].path['+name[1]+']'+(child?' + '+JSON.stringify('.'+child):''));}else if(type==='PathExpression'){this.pushString(name);}else if(type==='SubExpression'){this.pushStackLiteral('true');}else{this.pushStackLiteral('null');}},compiler:JavaScriptCompiler,compileChildren:function compileChildren(environment,options){var children=environment.children,child=undefined,compiler=undefined;for(var i=0,l=children.length;i<l;i++){child=children[i];compiler=new this.compiler();var index=this.matchExistingProgram(child);if(index==null){this.context.programs.push('');index=this.context.programs.length;child.index=index;child.name='program'+index;this.context.programs[index]=compiler.compile(child,options,this.context,!this.precompile);this.context.decorators[index]=compiler.decorators;this.context.environments[index]=child;this.useDepths=this.useDepths||compiler.useDepths;this.useBlockParams=this.useBlockParams||compiler.useBlockParams;}else{child.index=index;child.name='program'+index;this.useDepths=this.useDepths||child.useDepths;this.useBlockParams=this.useBlockParams||child.useBlockParams;}}},matchExistingProgram:function matchExistingProgram(child){for(var i=0,len=this.context.environments.length;i<len;i++){var environment=this.context.environments[i];if(environment&&environment.equals(child)){return i;}}},programExpression:function programExpression(guid){var child=this.environment.children[guid],programParams=[child.index,'data',child.blockParams];if(this.useBlockParams||this.useDepths){programParams.push('blockParams');}
if(this.useDepths){programParams.push('depths');}
return'container.program('+programParams.join(', ')+')';},useRegister:function useRegister(name){if(!this.registers[name]){this.registers[name]=true;this.registers.list.push(name);}},push:function push(expr){if(!(expr instanceof Literal)){expr=this.source.wrap(expr);}
this.inlineStack.push(expr);return expr;},pushStackLiteral:function pushStackLiteral(item){this.push(new Literal(item));},pushSource:function pushSource(source){if(this.pendingContent){this.source.push(this.appendToBuffer(this.source.quotedString(this.pendingContent),this.pendingLocation));this.pendingContent=undefined;}
if(source){this.source.push(source);}},replaceStack:function replaceStack(callback){var prefix=['('],stack=undefined,createdStack=undefined,usedLiteral=undefined;if(!this.isInline()){throw new _exception2['default']('replaceStack on non-inline');}
var top=this.popStack(true);if(top instanceof Literal){stack=[top.value];prefix=['(',stack];usedLiteral=true;}else{createdStack=true;var _name=this.incrStack();prefix=['((',this.push(_name),' = ',top,')'];stack=this.topStack();}
var item=callback.call(this,stack);if(!usedLiteral){this.popStack();}
if(createdStack){this.stackSlot--;}
this.push(prefix.concat(item,')'));},incrStack:function incrStack(){this.stackSlot++;if(this.stackSlot>this.stackVars.length){this.stackVars.push('stack'+this.stackSlot);}
return this.topStackName();},topStackName:function topStackName(){return'stack'+this.stackSlot;},flushInline:function flushInline(){var inlineStack=this.inlineStack;this.inlineStack=[];for(var i=0,len=inlineStack.length;i<len;i++){var entry=inlineStack[i];if(entry instanceof Literal){this.compileStack.push(entry);}else{var stack=this.incrStack();this.pushSource([stack,' = ',entry,';']);this.compileStack.push(stack);}}},isInline:function isInline(){return this.inlineStack.length;},popStack:function popStack(wrapped){var inline=this.isInline(),item=(inline?this.inlineStack:this.compileStack).pop();if(!wrapped&&item instanceof Literal){return item.value;}else{if(!inline){if(!this.stackSlot){throw new _exception2['default']('Invalid stack pop');}
this.stackSlot--;}
return item;}},topStack:function topStack(){var stack=this.isInline()?this.inlineStack:this.compileStack,item=stack[stack.length-1];if(item instanceof Literal){return item.value;}else{return item;}},contextName:function contextName(context){if(this.useDepths&&context){return'depths['+context+']';}else{return'depth'+context;}},quotedString:function quotedString(str){return this.source.quotedString(str);},objectLiteral:function objectLiteral(obj){return this.source.objectLiteral(obj);},aliasable:function aliasable(name){var ret=this.aliases[name];if(ret){ret.referenceCount++;return ret;}
ret=this.aliases[name]=this.source.wrap(name);ret.aliasable=true;ret.referenceCount=1;return ret;},setupHelper:function setupHelper(paramSize,name,blockHelper){var params=[],paramsInit=this.setupHelperArgs(name,paramSize,params,blockHelper);var foundHelper=this.nameLookup('helpers',name,'helper'),callContext=this.aliasable(this.contextName(0)+' != null ? '+this.contextName(0)+' : {}');return{params:params,paramsInit:paramsInit,name:foundHelper,callParams:[callContext].concat(params)};},setupParams:function setupParams(helper,paramSize,params){var options={},contexts=[],types=[],ids=[],objectArgs=!params,param=undefined;if(objectArgs){params=[];}
options.name=this.quotedString(helper);options.hash=this.popStack();if(this.trackIds){options.hashIds=this.popStack();}
if(this.stringParams){options.hashTypes=this.popStack();options.hashContexts=this.popStack();}
var inverse=this.popStack(),program=this.popStack();if(program||inverse){options.fn=program||'container.noop';options.inverse=inverse||'container.noop';}
var i=paramSize;while(i--){param=this.popStack();params[i]=param;if(this.trackIds){ids[i]=this.popStack();}
if(this.stringParams){types[i]=this.popStack();contexts[i]=this.popStack();}}
if(objectArgs){options.args=this.source.generateArray(params);}
if(this.trackIds){options.ids=this.source.generateArray(ids);}
if(this.stringParams){options.types=this.source.generateArray(types);options.contexts=this.source.generateArray(contexts);}
if(this.options.data){options.data='data';}
if(this.useBlockParams){options.blockParams='blockParams';}
return options;},setupHelperArgs:function setupHelperArgs(helper,paramSize,params,useRegister){var options=this.setupParams(helper,paramSize,params);options=this.objectLiteral(options);if(useRegister){this.useRegister('options');params.push('options');return['options=',options];}else if(params){params.push(options);return'';}else{return options;}}};(function(){var reservedWords=('break else new var'+' case finally return void'+' catch for switch while'+' continue function this with'+' default if throw'+' delete in try'+' do instanceof typeof'+' abstract enum int short'+' boolean export interface static'+' byte extends long super'+' char final native synchronized'+' class float package throws'+' const goto private transient'+' debugger implements protected volatile'+' double import public let yield await'+' null true false').split(' ');var compilerWords=JavaScriptCompiler.RESERVED_WORDS={};for(var i=0,l=reservedWords.length;i<l;i++){compilerWords[reservedWords[i]]=true;}})();JavaScriptCompiler.isValidJavaScriptVariableName=function(name){return!JavaScriptCompiler.RESERVED_WORDS[name]&&/^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(name);};function strictLookup(requireTerminal,compiler,parts,type){var stack=compiler.popStack(),i=0,len=parts.length;if(requireTerminal){len--;}
for(;i<len;i++){stack=compiler.nameLookup(stack,parts[i],type);}
if(requireTerminal){return[compiler.aliasable('container.strict'),'(',stack,', ',compiler.quotedString(parts[i]),')'];}else{return stack;}}
exports['default']=JavaScriptCompiler;module.exports=exports['default'];},{"../base":249,"../exception":262,"../utils":275,"./code-gen":252}],256:[function(require,module,exports){"use strict";var handlebars=(function(){var parser={trace:function trace(){},yy:{},symbols_:{"error":2,"root":3,"program":4,"EOF":5,"program_repetition0":6,"statement":7,"mustache":8,"block":9,"rawBlock":10,"partial":11,"partialBlock":12,"content":13,"COMMENT":14,"CONTENT":15,"openRawBlock":16,"rawBlock_repetition_plus0":17,"END_RAW_BLOCK":18,"OPEN_RAW_BLOCK":19,"helperName":20,"openRawBlock_repetition0":21,"openRawBlock_option0":22,"CLOSE_RAW_BLOCK":23,"openBlock":24,"block_option0":25,"closeBlock":26,"openInverse":27,"block_option1":28,"OPEN_BLOCK":29,"openBlock_repetition0":30,"openBlock_option0":31,"openBlock_option1":32,"CLOSE":33,"OPEN_INVERSE":34,"openInverse_repetition0":35,"openInverse_option0":36,"openInverse_option1":37,"openInverseChain":38,"OPEN_INVERSE_CHAIN":39,"openInverseChain_repetition0":40,"openInverseChain_option0":41,"openInverseChain_option1":42,"inverseAndProgram":43,"INVERSE":44,"inverseChain":45,"inverseChain_option0":46,"OPEN_ENDBLOCK":47,"OPEN":48,"mustache_repetition0":49,"mustache_option0":50,"OPEN_UNESCAPED":51,"mustache_repetition1":52,"mustache_option1":53,"CLOSE_UNESCAPED":54,"OPEN_PARTIAL":55,"partialName":56,"partial_repetition0":57,"partial_option0":58,"openPartialBlock":59,"OPEN_PARTIAL_BLOCK":60,"openPartialBlock_repetition0":61,"openPartialBlock_option0":62,"param":63,"sexpr":64,"OPEN_SEXPR":65,"sexpr_repetition0":66,"sexpr_option0":67,"CLOSE_SEXPR":68,"hash":69,"hash_repetition_plus0":70,"hashSegment":71,"ID":72,"EQUALS":73,"blockParams":74,"OPEN_BLOCK_PARAMS":75,"blockParams_repetition_plus0":76,"CLOSE_BLOCK_PARAMS":77,"path":78,"dataName":79,"STRING":80,"NUMBER":81,"BOOLEAN":82,"UNDEFINED":83,"NULL":84,"DATA":85,"pathSegments":86,"SEP":87,"$accept":0,"$end":1},terminals_:{2:"error",5:"EOF",14:"COMMENT",15:"CONTENT",18:"END_RAW_BLOCK",19:"OPEN_RAW_BLOCK",23:"CLOSE_RAW_BLOCK",29:"OPEN_BLOCK",33:"CLOSE",34:"OPEN_INVERSE",39:"OPEN_INVERSE_CHAIN",44:"INVERSE",47:"OPEN_ENDBLOCK",48:"OPEN",51:"OPEN_UNESCAPED",54:"CLOSE_UNESCAPED",55:"OPEN_PARTIAL",60:"OPEN_PARTIAL_BLOCK",65:"OPEN_SEXPR",68:"CLOSE_SEXPR",72:"ID",73:"EQUALS",75:"OPEN_BLOCK_PARAMS",77:"CLOSE_BLOCK_PARAMS",80:"STRING",81:"NUMBER",82:"BOOLEAN",83:"UNDEFINED",84:"NULL",85:"DATA",87:"SEP"},productions_:[0,[3,2],[4,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[13,1],[10,3],[16,5],[9,4],[9,4],[24,6],[27,6],[38,6],[43,2],[45,3],[45,1],[26,3],[8,5],[8,5],[11,5],[12,3],[59,5],[63,1],[63,1],[64,5],[69,1],[71,3],[74,3],[20,1],[20,1],[20,1],[20,1],[20,1],[20,1],[20,1],[56,1],[56,1],[79,2],[78,1],[86,3],[86,1],[6,0],[6,2],[17,1],[17,2],[21,0],[21,2],[22,0],[22,1],[25,0],[25,1],[28,0],[28,1],[30,0],[30,2],[31,0],[31,1],[32,0],[32,1],[35,0],[35,2],[36,0],[36,1],[37,0],[37,1],[40,0],[40,2],[41,0],[41,1],[42,0],[42,1],[46,0],[46,1],[49,0],[49,2],[50,0],[50,1],[52,0],[52,2],[53,0],[53,1],[57,0],[57,2],[58,0],[58,1],[61,0],[61,2],[62,0],[62,1],[66,0],[66,2],[67,0],[67,1],[70,1],[70,2],[76,1],[76,2]],performAction:function anonymous(yytext,yyleng,yylineno,yy,yystate,$$,_$){var $0=$$.length-1;switch(yystate){case 1:return $$[$0-1];break;case 2:this.$=yy.prepareProgram($$[$0]);break;case 3:this.$=$$[$0];break;case 4:this.$=$$[$0];break;case 5:this.$=$$[$0];break;case 6:this.$=$$[$0];break;case 7:this.$=$$[$0];break;case 8:this.$=$$[$0];break;case 9:this.$={type:'CommentStatement',value:yy.stripComment($$[$0]),strip:yy.stripFlags($$[$0],$$[$0]),loc:yy.locInfo(this._$)};break;case 10:this.$={type:'ContentStatement',original:$$[$0],value:$$[$0],loc:yy.locInfo(this._$)};break;case 11:this.$=yy.prepareRawBlock($$[$0-2],$$[$0-1],$$[$0],this._$);break;case 12:this.$={path:$$[$0-3],params:$$[$0-2],hash:$$[$0-1]};break;case 13:this.$=yy.prepareBlock($$[$0-3],$$[$0-2],$$[$0-1],$$[$0],false,this._$);break;case 14:this.$=yy.prepareBlock($$[$0-3],$$[$0-2],$$[$0-1],$$[$0],true,this._$);break;case 15:this.$={open:$$[$0-5],path:$$[$0-4],params:$$[$0-3],hash:$$[$0-2],blockParams:$$[$0-1],strip:yy.stripFlags($$[$0-5],$$[$0])};break;case 16:this.$={path:$$[$0-4],params:$$[$0-3],hash:$$[$0-2],blockParams:$$[$0-1],strip:yy.stripFlags($$[$0-5],$$[$0])};break;case 17:this.$={path:$$[$0-4],params:$$[$0-3],hash:$$[$0-2],blockParams:$$[$0-1],strip:yy.stripFlags($$[$0-5],$$[$0])};break;case 18:this.$={strip:yy.stripFlags($$[$0-1],$$[$0-1]),program:$$[$0]};break;case 19:var inverse=yy.prepareBlock($$[$0-2],$$[$0-1],$$[$0],$$[$0],false,this._$),program=yy.prepareProgram([inverse],$$[$0-1].loc);program.chained=true;this.$={strip:$$[$0-2].strip,program:program,chain:true};break;case 20:this.$=$$[$0];break;case 21:this.$={path:$$[$0-1],strip:yy.stripFlags($$[$0-2],$$[$0])};break;case 22:this.$=yy.prepareMustache($$[$0-3],$$[$0-2],$$[$0-1],$$[$0-4],yy.stripFlags($$[$0-4],$$[$0]),this._$);break;case 23:this.$=yy.prepareMustache($$[$0-3],$$[$0-2],$$[$0-1],$$[$0-4],yy.stripFlags($$[$0-4],$$[$0]),this._$);break;case 24:this.$={type:'PartialStatement',name:$$[$0-3],params:$$[$0-2],hash:$$[$0-1],indent:'',strip:yy.stripFlags($$[$0-4],$$[$0]),loc:yy.locInfo(this._$)};break;case 25:this.$=yy.preparePartialBlock($$[$0-2],$$[$0-1],$$[$0],this._$);break;case 26:this.$={path:$$[$0-3],params:$$[$0-2],hash:$$[$0-1],strip:yy.stripFlags($$[$0-4],$$[$0])};break;case 27:this.$=$$[$0];break;case 28:this.$=$$[$0];break;case 29:this.$={type:'SubExpression',path:$$[$0-3],params:$$[$0-2],hash:$$[$0-1],loc:yy.locInfo(this._$)};break;case 30:this.$={type:'Hash',pairs:$$[$0],loc:yy.locInfo(this._$)};break;case 31:this.$={type:'HashPair',key:yy.id($$[$0-2]),value:$$[$0],loc:yy.locInfo(this._$)};break;case 32:this.$=yy.id($$[$0-1]);break;case 33:this.$=$$[$0];break;case 34:this.$=$$[$0];break;case 35:this.$={type:'StringLiteral',value:$$[$0],original:$$[$0],loc:yy.locInfo(this._$)};break;case 36:this.$={type:'NumberLiteral',value:Number($$[$0]),original:Number($$[$0]),loc:yy.locInfo(this._$)};break;case 37:this.$={type:'BooleanLiteral',value:$$[$0]==='true',original:$$[$0]==='true',loc:yy.locInfo(this._$)};break;case 38:this.$={type:'UndefinedLiteral',original:undefined,value:undefined,loc:yy.locInfo(this._$)};break;case 39:this.$={type:'NullLiteral',original:null,value:null,loc:yy.locInfo(this._$)};break;case 40:this.$=$$[$0];break;case 41:this.$=$$[$0];break;case 42:this.$=yy.preparePath(true,$$[$0],this._$);break;case 43:this.$=yy.preparePath(false,$$[$0],this._$);break;case 44:$$[$0-2].push({part:yy.id($$[$0]),original:$$[$0],separator:$$[$0-1]});this.$=$$[$0-2];break;case 45:this.$=[{part:yy.id($$[$0]),original:$$[$0]}];break;case 46:this.$=[];break;case 47:$$[$0-1].push($$[$0]);break;case 48:this.$=[$$[$0]];break;case 49:$$[$0-1].push($$[$0]);break;case 50:this.$=[];break;case 51:$$[$0-1].push($$[$0]);break;case 58:this.$=[];break;case 59:$$[$0-1].push($$[$0]);break;case 64:this.$=[];break;case 65:$$[$0-1].push($$[$0]);break;case 70:this.$=[];break;case 71:$$[$0-1].push($$[$0]);break;case 78:this.$=[];break;case 79:$$[$0-1].push($$[$0]);break;case 82:this.$=[];break;case 83:$$[$0-1].push($$[$0]);break;case 86:this.$=[];break;case 87:$$[$0-1].push($$[$0]);break;case 90:this.$=[];break;case 91:$$[$0-1].push($$[$0]);break;case 94:this.$=[];break;case 95:$$[$0-1].push($$[$0]);break;case 98:this.$=[$$[$0]];break;case 99:$$[$0-1].push($$[$0]);break;case 100:this.$=[$$[$0]];break;case 101:$$[$0-1].push($$[$0]);break;}},table:[{3:1,4:2,5:[2,46],6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{1:[3]},{5:[1,4]},{5:[2,2],7:5,8:6,9:7,10:8,11:9,12:10,13:11,14:[1,12],15:[1,20],16:17,19:[1,23],24:15,27:16,29:[1,21],34:[1,22],39:[2,2],44:[2,2],47:[2,2],48:[1,13],51:[1,14],55:[1,18],59:19,60:[1,24]},{1:[2,1]},{5:[2,47],14:[2,47],15:[2,47],19:[2,47],29:[2,47],34:[2,47],39:[2,47],44:[2,47],47:[2,47],48:[2,47],51:[2,47],55:[2,47],60:[2,47]},{5:[2,3],14:[2,3],15:[2,3],19:[2,3],29:[2,3],34:[2,3],39:[2,3],44:[2,3],47:[2,3],48:[2,3],51:[2,3],55:[2,3],60:[2,3]},{5:[2,4],14:[2,4],15:[2,4],19:[2,4],29:[2,4],34:[2,4],39:[2,4],44:[2,4],47:[2,4],48:[2,4],51:[2,4],55:[2,4],60:[2,4]},{5:[2,5],14:[2,5],15:[2,5],19:[2,5],29:[2,5],34:[2,5],39:[2,5],44:[2,5],47:[2,5],48:[2,5],51:[2,5],55:[2,5],60:[2,5]},{5:[2,6],14:[2,6],15:[2,6],19:[2,6],29:[2,6],34:[2,6],39:[2,6],44:[2,6],47:[2,6],48:[2,6],51:[2,6],55:[2,6],60:[2,6]},{5:[2,7],14:[2,7],15:[2,7],19:[2,7],29:[2,7],34:[2,7],39:[2,7],44:[2,7],47:[2,7],48:[2,7],51:[2,7],55:[2,7],60:[2,7]},{5:[2,8],14:[2,8],15:[2,8],19:[2,8],29:[2,8],34:[2,8],39:[2,8],44:[2,8],47:[2,8],48:[2,8],51:[2,8],55:[2,8],60:[2,8]},{5:[2,9],14:[2,9],15:[2,9],19:[2,9],29:[2,9],34:[2,9],39:[2,9],44:[2,9],47:[2,9],48:[2,9],51:[2,9],55:[2,9],60:[2,9]},{20:25,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:36,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{4:37,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],39:[2,46],44:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{4:38,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],44:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{13:40,15:[1,20],17:39},{20:42,56:41,64:43,65:[1,44],72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{4:45,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{5:[2,10],14:[2,10],15:[2,10],18:[2,10],19:[2,10],29:[2,10],34:[2,10],39:[2,10],44:[2,10],47:[2,10],48:[2,10],51:[2,10],55:[2,10],60:[2,10]},{20:46,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:47,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:48,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:42,56:49,64:43,65:[1,44],72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{33:[2,78],49:50,65:[2,78],72:[2,78],80:[2,78],81:[2,78],82:[2,78],83:[2,78],84:[2,78],85:[2,78]},{23:[2,33],33:[2,33],54:[2,33],65:[2,33],68:[2,33],72:[2,33],75:[2,33],80:[2,33],81:[2,33],82:[2,33],83:[2,33],84:[2,33],85:[2,33]},{23:[2,34],33:[2,34],54:[2,34],65:[2,34],68:[2,34],72:[2,34],75:[2,34],80:[2,34],81:[2,34],82:[2,34],83:[2,34],84:[2,34],85:[2,34]},{23:[2,35],33:[2,35],54:[2,35],65:[2,35],68:[2,35],72:[2,35],75:[2,35],80:[2,35],81:[2,35],82:[2,35],83:[2,35],84:[2,35],85:[2,35]},{23:[2,36],33:[2,36],54:[2,36],65:[2,36],68:[2,36],72:[2,36],75:[2,36],80:[2,36],81:[2,36],82:[2,36],83:[2,36],84:[2,36],85:[2,36]},{23:[2,37],33:[2,37],54:[2,37],65:[2,37],68:[2,37],72:[2,37],75:[2,37],80:[2,37],81:[2,37],82:[2,37],83:[2,37],84:[2,37],85:[2,37]},{23:[2,38],33:[2,38],54:[2,38],65:[2,38],68:[2,38],72:[2,38],75:[2,38],80:[2,38],81:[2,38],82:[2,38],83:[2,38],84:[2,38],85:[2,38]},{23:[2,39],33:[2,39],54:[2,39],65:[2,39],68:[2,39],72:[2,39],75:[2,39],80:[2,39],81:[2,39],82:[2,39],83:[2,39],84:[2,39],85:[2,39]},{23:[2,43],33:[2,43],54:[2,43],65:[2,43],68:[2,43],72:[2,43],75:[2,43],80:[2,43],81:[2,43],82:[2,43],83:[2,43],84:[2,43],85:[2,43],87:[1,51]},{72:[1,35],86:52},{23:[2,45],33:[2,45],54:[2,45],65:[2,45],68:[2,45],72:[2,45],75:[2,45],80:[2,45],81:[2,45],82:[2,45],83:[2,45],84:[2,45],85:[2,45],87:[2,45]},{52:53,54:[2,82],65:[2,82],72:[2,82],80:[2,82],81:[2,82],82:[2,82],83:[2,82],84:[2,82],85:[2,82]},{25:54,38:56,39:[1,58],43:57,44:[1,59],45:55,47:[2,54]},{28:60,43:61,44:[1,59],47:[2,56]},{13:63,15:[1,20],18:[1,62]},{15:[2,48],18:[2,48]},{33:[2,86],57:64,65:[2,86],72:[2,86],80:[2,86],81:[2,86],82:[2,86],83:[2,86],84:[2,86],85:[2,86]},{33:[2,40],65:[2,40],72:[2,40],80:[2,40],81:[2,40],82:[2,40],83:[2,40],84:[2,40],85:[2,40]},{33:[2,41],65:[2,41],72:[2,41],80:[2,41],81:[2,41],82:[2,41],83:[2,41],84:[2,41],85:[2,41]},{20:65,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{26:66,47:[1,67]},{30:68,33:[2,58],65:[2,58],72:[2,58],75:[2,58],80:[2,58],81:[2,58],82:[2,58],83:[2,58],84:[2,58],85:[2,58]},{33:[2,64],35:69,65:[2,64],72:[2,64],75:[2,64],80:[2,64],81:[2,64],82:[2,64],83:[2,64],84:[2,64],85:[2,64]},{21:70,23:[2,50],65:[2,50],72:[2,50],80:[2,50],81:[2,50],82:[2,50],83:[2,50],84:[2,50],85:[2,50]},{33:[2,90],61:71,65:[2,90],72:[2,90],80:[2,90],81:[2,90],82:[2,90],83:[2,90],84:[2,90],85:[2,90]},{20:75,33:[2,80],50:72,63:73,64:76,65:[1,44],69:74,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{72:[1,80]},{23:[2,42],33:[2,42],54:[2,42],65:[2,42],68:[2,42],72:[2,42],75:[2,42],80:[2,42],81:[2,42],82:[2,42],83:[2,42],84:[2,42],85:[2,42],87:[1,51]},{20:75,53:81,54:[2,84],63:82,64:76,65:[1,44],69:83,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{26:84,47:[1,67]},{47:[2,55]},{4:85,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],39:[2,46],44:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{47:[2,20]},{20:86,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{4:87,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{26:88,47:[1,67]},{47:[2,57]},{5:[2,11],14:[2,11],15:[2,11],19:[2,11],29:[2,11],34:[2,11],39:[2,11],44:[2,11],47:[2,11],48:[2,11],51:[2,11],55:[2,11],60:[2,11]},{15:[2,49],18:[2,49]},{20:75,33:[2,88],58:89,63:90,64:76,65:[1,44],69:91,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{65:[2,94],66:92,68:[2,94],72:[2,94],80:[2,94],81:[2,94],82:[2,94],83:[2,94],84:[2,94],85:[2,94]},{5:[2,25],14:[2,25],15:[2,25],19:[2,25],29:[2,25],34:[2,25],39:[2,25],44:[2,25],47:[2,25],48:[2,25],51:[2,25],55:[2,25],60:[2,25]},{20:93,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:75,31:94,33:[2,60],63:95,64:76,65:[1,44],69:96,70:77,71:78,72:[1,79],75:[2,60],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:75,33:[2,66],36:97,63:98,64:76,65:[1,44],69:99,70:77,71:78,72:[1,79],75:[2,66],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:75,22:100,23:[2,52],63:101,64:76,65:[1,44],69:102,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:75,33:[2,92],62:103,63:104,64:76,65:[1,44],69:105,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{33:[1,106]},{33:[2,79],65:[2,79],72:[2,79],80:[2,79],81:[2,79],82:[2,79],83:[2,79],84:[2,79],85:[2,79]},{33:[2,81]},{23:[2,27],33:[2,27],54:[2,27],65:[2,27],68:[2,27],72:[2,27],75:[2,27],80:[2,27],81:[2,27],82:[2,27],83:[2,27],84:[2,27],85:[2,27]},{23:[2,28],33:[2,28],54:[2,28],65:[2,28],68:[2,28],72:[2,28],75:[2,28],80:[2,28],81:[2,28],82:[2,28],83:[2,28],84:[2,28],85:[2,28]},{23:[2,30],33:[2,30],54:[2,30],68:[2,30],71:107,72:[1,108],75:[2,30]},{23:[2,98],33:[2,98],54:[2,98],68:[2,98],72:[2,98],75:[2,98]},{23:[2,45],33:[2,45],54:[2,45],65:[2,45],68:[2,45],72:[2,45],73:[1,109],75:[2,45],80:[2,45],81:[2,45],82:[2,45],83:[2,45],84:[2,45],85:[2,45],87:[2,45]},{23:[2,44],33:[2,44],54:[2,44],65:[2,44],68:[2,44],72:[2,44],75:[2,44],80:[2,44],81:[2,44],82:[2,44],83:[2,44],84:[2,44],85:[2,44],87:[2,44]},{54:[1,110]},{54:[2,83],65:[2,83],72:[2,83],80:[2,83],81:[2,83],82:[2,83],83:[2,83],84:[2,83],85:[2,83]},{54:[2,85]},{5:[2,13],14:[2,13],15:[2,13],19:[2,13],29:[2,13],34:[2,13],39:[2,13],44:[2,13],47:[2,13],48:[2,13],51:[2,13],55:[2,13],60:[2,13]},{38:56,39:[1,58],43:57,44:[1,59],45:112,46:111,47:[2,76]},{33:[2,70],40:113,65:[2,70],72:[2,70],75:[2,70],80:[2,70],81:[2,70],82:[2,70],83:[2,70],84:[2,70],85:[2,70]},{47:[2,18]},{5:[2,14],14:[2,14],15:[2,14],19:[2,14],29:[2,14],34:[2,14],39:[2,14],44:[2,14],47:[2,14],48:[2,14],51:[2,14],55:[2,14],60:[2,14]},{33:[1,114]},{33:[2,87],65:[2,87],72:[2,87],80:[2,87],81:[2,87],82:[2,87],83:[2,87],84:[2,87],85:[2,87]},{33:[2,89]},{20:75,63:116,64:76,65:[1,44],67:115,68:[2,96],69:117,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{33:[1,118]},{32:119,33:[2,62],74:120,75:[1,121]},{33:[2,59],65:[2,59],72:[2,59],75:[2,59],80:[2,59],81:[2,59],82:[2,59],83:[2,59],84:[2,59],85:[2,59]},{33:[2,61],75:[2,61]},{33:[2,68],37:122,74:123,75:[1,121]},{33:[2,65],65:[2,65],72:[2,65],75:[2,65],80:[2,65],81:[2,65],82:[2,65],83:[2,65],84:[2,65],85:[2,65]},{33:[2,67],75:[2,67]},{23:[1,124]},{23:[2,51],65:[2,51],72:[2,51],80:[2,51],81:[2,51],82:[2,51],83:[2,51],84:[2,51],85:[2,51]},{23:[2,53]},{33:[1,125]},{33:[2,91],65:[2,91],72:[2,91],80:[2,91],81:[2,91],82:[2,91],83:[2,91],84:[2,91],85:[2,91]},{33:[2,93]},{5:[2,22],14:[2,22],15:[2,22],19:[2,22],29:[2,22],34:[2,22],39:[2,22],44:[2,22],47:[2,22],48:[2,22],51:[2,22],55:[2,22],60:[2,22]},{23:[2,99],33:[2,99],54:[2,99],68:[2,99],72:[2,99],75:[2,99]},{73:[1,109]},{20:75,63:126,64:76,65:[1,44],72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{5:[2,23],14:[2,23],15:[2,23],19:[2,23],29:[2,23],34:[2,23],39:[2,23],44:[2,23],47:[2,23],48:[2,23],51:[2,23],55:[2,23],60:[2,23]},{47:[2,19]},{47:[2,77]},{20:75,33:[2,72],41:127,63:128,64:76,65:[1,44],69:129,70:77,71:78,72:[1,79],75:[2,72],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{5:[2,24],14:[2,24],15:[2,24],19:[2,24],29:[2,24],34:[2,24],39:[2,24],44:[2,24],47:[2,24],48:[2,24],51:[2,24],55:[2,24],60:[2,24]},{68:[1,130]},{65:[2,95],68:[2,95],72:[2,95],80:[2,95],81:[2,95],82:[2,95],83:[2,95],84:[2,95],85:[2,95]},{68:[2,97]},{5:[2,21],14:[2,21],15:[2,21],19:[2,21],29:[2,21],34:[2,21],39:[2,21],44:[2,21],47:[2,21],48:[2,21],51:[2,21],55:[2,21],60:[2,21]},{33:[1,131]},{33:[2,63]},{72:[1,133],76:132},{33:[1,134]},{33:[2,69]},{15:[2,12]},{14:[2,26],15:[2,26],19:[2,26],29:[2,26],34:[2,26],47:[2,26],48:[2,26],51:[2,26],55:[2,26],60:[2,26]},{23:[2,31],33:[2,31],54:[2,31],68:[2,31],72:[2,31],75:[2,31]},{33:[2,74],42:135,74:136,75:[1,121]},{33:[2,71],65:[2,71],72:[2,71],75:[2,71],80:[2,71],81:[2,71],82:[2,71],83:[2,71],84:[2,71],85:[2,71]},{33:[2,73],75:[2,73]},{23:[2,29],33:[2,29],54:[2,29],65:[2,29],68:[2,29],72:[2,29],75:[2,29],80:[2,29],81:[2,29],82:[2,29],83:[2,29],84:[2,29],85:[2,29]},{14:[2,15],15:[2,15],19:[2,15],29:[2,15],34:[2,15],39:[2,15],44:[2,15],47:[2,15],48:[2,15],51:[2,15],55:[2,15],60:[2,15]},{72:[1,138],77:[1,137]},{72:[2,100],77:[2,100]},{14:[2,16],15:[2,16],19:[2,16],29:[2,16],34:[2,16],44:[2,16],47:[2,16],48:[2,16],51:[2,16],55:[2,16],60:[2,16]},{33:[1,139]},{33:[2,75]},{33:[2,32]},{72:[2,101],77:[2,101]},{14:[2,17],15:[2,17],19:[2,17],29:[2,17],34:[2,17],39:[2,17],44:[2,17],47:[2,17],48:[2,17],51:[2,17],55:[2,17],60:[2,17]}],defaultActions:{4:[2,1],55:[2,55],57:[2,20],61:[2,57],74:[2,81],83:[2,85],87:[2,18],91:[2,89],102:[2,53],105:[2,93],111:[2,19],112:[2,77],117:[2,97],120:[2,63],123:[2,69],124:[2,12],136:[2,75],137:[2,32]},parseError:function parseError(str,hash){throw new Error(str);},parse:function parse(input){var self=this,stack=[0],vstack=[null],lstack=[],table=this.table,yytext="",yylineno=0,yyleng=0,recovering=0,TERROR=2,EOF=1;this.lexer.setInput(input);this.lexer.yy=this.yy;this.yy.lexer=this.lexer;this.yy.parser=this;if(typeof this.lexer.yylloc=="undefined")this.lexer.yylloc={};var yyloc=this.lexer.yylloc;lstack.push(yyloc);var ranges=this.lexer.options&&this.lexer.options.ranges;if(typeof this.yy.parseError==="function")this.parseError=this.yy.parseError;function popStack(n){stack.length=stack.length-2*n;vstack.length=vstack.length-n;lstack.length=lstack.length-n;}
function lex(){var token;token=self.lexer.lex()||1;if(typeof token!=="number"){token=self.symbols_[token]||token;}
return token;}
var symbol,preErrorSymbol,state,action,a,r,yyval={},p,len,newState,expected;while(true){state=stack[stack.length-1];if(this.defaultActions[state]){action=this.defaultActions[state];}else{if(symbol===null||typeof symbol=="undefined"){symbol=lex();}
action=table[state]&&table[state][symbol];}
if(typeof action==="undefined"||!action.length||!action[0]){var errStr="";if(!recovering){expected=[];for(p in table[state])if(this.terminals_[p]&&p>2){expected.push("'"+this.terminals_[p]+"'");}
if(this.lexer.showPosition){errStr="Parse error on line "+(yylineno+1)+":\n"+this.lexer.showPosition()+"\nExpecting "+expected.join(", ")+", got '"+(this.terminals_[symbol]||symbol)+"'";}else{errStr="Parse error on line "+(yylineno+1)+": Unexpected "+(symbol==1?"end of input":"'"+(this.terminals_[symbol]||symbol)+"'");}
this.parseError(errStr,{text:this.lexer.match,token:this.terminals_[symbol]||symbol,line:this.lexer.yylineno,loc:yyloc,expected:expected});}}
if(action[0]instanceof Array&&action.length>1){throw new Error("Parse Error: multiple actions possible at state: "+state+", token: "+symbol);}
switch(action[0]){case 1:stack.push(symbol);vstack.push(this.lexer.yytext);lstack.push(this.lexer.yylloc);stack.push(action[1]);symbol=null;if(!preErrorSymbol){yyleng=this.lexer.yyleng;yytext=this.lexer.yytext;yylineno=this.lexer.yylineno;yyloc=this.lexer.yylloc;if(recovering>0)recovering--;}else{symbol=preErrorSymbol;preErrorSymbol=null;}
break;case 2:len=this.productions_[action[1]][1];yyval.$=vstack[vstack.length-len];yyval._$={first_line:lstack[lstack.length-(len||1)].first_line,last_line:lstack[lstack.length-1].last_line,first_column:lstack[lstack.length-(len||1)].first_column,last_column:lstack[lstack.length-1].last_column};if(ranges){yyval._$.range=[lstack[lstack.length-(len||1)].range[0],lstack[lstack.length-1].range[1]];}
r=this.performAction.call(yyval,yytext,yyleng,yylineno,this.yy,action[1],vstack,lstack);if(typeof r!=="undefined"){return r;}
if(len){stack=stack.slice(0,-1*len*2);vstack=vstack.slice(0,-1*len);lstack=lstack.slice(0,-1*len);}
stack.push(this.productions_[action[1]][0]);vstack.push(yyval.$);lstack.push(yyval._$);newState=table[stack[stack.length-2]][stack[stack.length-1]];stack.push(newState);break;case 3:return true;}}
return true;}};var lexer=(function(){var lexer={EOF:1,parseError:function parseError(str,hash){if(this.yy.parser){this.yy.parser.parseError(str,hash);}else{throw new Error(str);}},setInput:function setInput(input){this._input=input;this._more=this._less=this.done=false;this.yylineno=this.yyleng=0;this.yytext=this.matched=this.match='';this.conditionStack=['INITIAL'];this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0};if(this.options.ranges)this.yylloc.range=[0,0];this.offset=0;return this;},input:function input(){var ch=this._input[0];this.yytext+=ch;this.yyleng++;this.offset++;this.match+=ch;this.matched+=ch;var lines=ch.match(/(?:\r\n?|\n).*/g);if(lines){this.yylineno++;this.yylloc.last_line++;}else{this.yylloc.last_column++;}
if(this.options.ranges)this.yylloc.range[1]++;this._input=this._input.slice(1);return ch;},unput:function unput(ch){var len=ch.length;var lines=ch.split(/(?:\r\n?|\n)/g);this._input=ch+this._input;this.yytext=this.yytext.substr(0,this.yytext.length-len-1);this.offset-=len;var oldLines=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1);this.matched=this.matched.substr(0,this.matched.length-1);if(lines.length-1)this.yylineno-=lines.length-1;var r=this.yylloc.range;this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:lines?(lines.length===oldLines.length?this.yylloc.first_column:0)+oldLines[oldLines.length-lines.length].length-lines[0].length:this.yylloc.first_column-len};if(this.options.ranges){this.yylloc.range=[r[0],r[0]+this.yyleng-len];}
return this;},more:function more(){this._more=true;return this;},less:function less(n){this.unput(this.match.slice(n));},pastInput:function pastInput(){var past=this.matched.substr(0,this.matched.length-this.match.length);return(past.length>20?'...':'')+past.substr(-20).replace(/\n/g,"");},upcomingInput:function upcomingInput(){var next=this.match;if(next.length<20){next+=this._input.substr(0,20-next.length);}
return(next.substr(0,20)+(next.length>20?'...':'')).replace(/\n/g,"");},showPosition:function showPosition(){var pre=this.pastInput();var c=new Array(pre.length+1).join("-");return pre+this.upcomingInput()+"\n"+c+"^";},next:function next(){if(this.done){return this.EOF;}
if(!this._input)this.done=true;var token,match,tempMatch,index,col,lines;if(!this._more){this.yytext='';this.match='';}
var rules=this._currentRules();for(var i=0;i<rules.length;i++){tempMatch=this._input.match(this.rules[rules[i]]);if(tempMatch&&(!match||tempMatch[0].length>match[0].length)){match=tempMatch;index=i;if(!this.options.flex)break;}}
if(match){lines=match[0].match(/(?:\r\n?|\n).*/g);if(lines)this.yylineno+=lines.length;this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:lines?lines[lines.length-1].length-lines[lines.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+match[0].length};this.yytext+=match[0];this.match+=match[0];this.matches=match;this.yyleng=this.yytext.length;if(this.options.ranges){this.yylloc.range=[this.offset,this.offset+=this.yyleng];}
this._more=false;this._input=this._input.slice(match[0].length);this.matched+=match[0];token=this.performAction.call(this,this.yy,this,rules[index],this.conditionStack[this.conditionStack.length-1]);if(this.done&&this._input)this.done=false;if(token)return token;else return;}
if(this._input===""){return this.EOF;}else{return this.parseError('Lexical error on line '+(this.yylineno+1)+'. Unrecognized text.\n'+this.showPosition(),{text:"",token:null,line:this.yylineno});}},lex:function lex(){var r=this.next();if(typeof r!=='undefined'){return r;}else{return this.lex();}},begin:function begin(condition){this.conditionStack.push(condition);},popState:function popState(){return this.conditionStack.pop();},_currentRules:function _currentRules(){return this.conditions[this.conditionStack[this.conditionStack.length-1]].rules;},topState:function topState(){return this.conditionStack[this.conditionStack.length-2];},pushState:function begin(condition){this.begin(condition);}};lexer.options={};lexer.performAction=function anonymous(yy,yy_,$avoiding_name_collisions,YY_START){function strip(start,end){return yy_.yytext=yy_.yytext.substr(start,yy_.yyleng-end);}
var YYSTATE=YY_START;switch($avoiding_name_collisions){case 0:if(yy_.yytext.slice(-2)==="\\\\"){strip(0,1);this.begin("mu");}else if(yy_.yytext.slice(-1)==="\\"){strip(0,1);this.begin("emu");}else{this.begin("mu");}
if(yy_.yytext)return 15;break;case 1:return 15;break;case 2:this.popState();return 15;break;case 3:this.begin('raw');return 15;break;case 4:this.popState();if(this.conditionStack[this.conditionStack.length-1]==='raw'){return 15;}else{yy_.yytext=yy_.yytext.substr(5,yy_.yyleng-9);return'END_RAW_BLOCK';}
break;case 5:return 15;break;case 6:this.popState();return 14;break;case 7:return 65;break;case 8:return 68;break;case 9:return 19;break;case 10:this.popState();this.begin('raw');return 23;break;case 11:return 55;break;case 12:return 60;break;case 13:return 29;break;case 14:return 47;break;case 15:this.popState();return 44;break;case 16:this.popState();return 44;break;case 17:return 34;break;case 18:return 39;break;case 19:return 51;break;case 20:return 48;break;case 21:this.unput(yy_.yytext);this.popState();this.begin('com');break;case 22:this.popState();return 14;break;case 23:return 48;break;case 24:return 73;break;case 25:return 72;break;case 26:return 72;break;case 27:return 87;break;case 28:break;case 29:this.popState();return 54;break;case 30:this.popState();return 33;break;case 31:yy_.yytext=strip(1,2).replace(/\\"/g,'"');return 80;break;case 32:yy_.yytext=strip(1,2).replace(/\\'/g,"'");return 80;break;case 33:return 85;break;case 34:return 82;break;case 35:return 82;break;case 36:return 83;break;case 37:return 84;break;case 38:return 81;break;case 39:return 75;break;case 40:return 77;break;case 41:return 72;break;case 42:yy_.yytext=yy_.yytext.replace(/\\([\\\]])/g,'$1');return 72;break;case 43:return'INVALID';break;case 44:return 5;break;}};lexer.rules=[/^(?:[^\x00]*?(?=(\{\{)))/,/^(?:[^\x00]+)/,/^(?:[^\x00]{2,}?(?=(\{\{|\\\{\{|\\\\\{\{|$)))/,/^(?:\{\{\{\{(?=[^\/]))/,/^(?:\{\{\{\{\/[^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=[=}\s\/.])\}\}\}\})/,/^(?:[^\x00]*?(?=(\{\{\{\{)))/,/^(?:[\s\S]*?--(~)?\}\})/,/^(?:\()/,/^(?:\))/,/^(?:\{\{\{\{)/,/^(?:\}\}\}\})/,/^(?:\{\{(~)?>)/,/^(?:\{\{(~)?#>)/,/^(?:\{\{(~)?#\*?)/,/^(?:\{\{(~)?\/)/,/^(?:\{\{(~)?\^\s*(~)?\}\})/,/^(?:\{\{(~)?\s*else\s*(~)?\}\})/,/^(?:\{\{(~)?\^)/,/^(?:\{\{(~)?\s*else\b)/,/^(?:\{\{(~)?\{)/,/^(?:\{\{(~)?&)/,/^(?:\{\{(~)?!--)/,/^(?:\{\{(~)?![\s\S]*?\}\})/,/^(?:\{\{(~)?\*?)/,/^(?:=)/,/^(?:\.\.)/,/^(?:\.(?=([=~}\s\/.)|])))/,/^(?:[\/.])/,/^(?:\s+)/,/^(?:\}(~)?\}\})/,/^(?:(~)?\}\})/,/^(?:"(\\["]|[^"])*")/,/^(?:'(\\[']|[^'])*')/,/^(?:@)/,/^(?:true(?=([~}\s)])))/,/^(?:false(?=([~}\s)])))/,/^(?:undefined(?=([~}\s)])))/,/^(?:null(?=([~}\s)])))/,/^(?:-?[0-9]+(?:\.[0-9]+)?(?=([~}\s)])))/,/^(?:as\s+\|)/,/^(?:\|)/,/^(?:([^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=([=~}\s\/.)|]))))/,/^(?:\[(\\\]|[^\]])*\])/,/^(?:.)/,/^(?:$)/];lexer.conditions={"mu":{"rules":[7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44],"inclusive":false},"emu":{"rules":[2],"inclusive":false},"com":{"rules":[6],"inclusive":false},"raw":{"rules":[3,4,5],"inclusive":false},"INITIAL":{"rules":[0,1,44],"inclusive":true}};return lexer;})();parser.lexer=lexer;function Parser(){this.yy={};}Parser.prototype=parser;parser.Parser=Parser;return new Parser();})();exports.__esModule=true;exports['default']=handlebars;},{}],257:[function(require,module,exports){'use strict';exports.__esModule=true;exports.print=print;exports.PrintVisitor=PrintVisitor;function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{'default':obj};}
var _visitor=require('./visitor');var _visitor2=_interopRequireDefault(_visitor);function print(ast){return new PrintVisitor().accept(ast);}
function PrintVisitor(){this.padding=0;}
PrintVisitor.prototype=new _visitor2['default']();PrintVisitor.prototype.pad=function(string){var out='';for(var i=0,l=this.padding;i<l;i++){out+='  ';}
out+=string+'\n';return out;};PrintVisitor.prototype.Program=function(program){var out='',body=program.body,i=undefined,l=undefined;if(program.blockParams){var blockParams='BLOCK PARAMS: [';for(i=0,l=program.blockParams.length;i<l;i++){blockParams+=' '+program.blockParams[i];}
blockParams+=' ]';out+=this.pad(blockParams);}
for(i=0,l=body.length;i<l;i++){out+=this.accept(body[i]);}
this.padding--;return out;};PrintVisitor.prototype.MustacheStatement=function(mustache){return this.pad('{{ '+this.SubExpression(mustache)+' }}');};PrintVisitor.prototype.Decorator=function(mustache){return this.pad('{{ DIRECTIVE '+this.SubExpression(mustache)+' }}');};PrintVisitor.prototype.BlockStatement=PrintVisitor.prototype.DecoratorBlock=function(block){var out='';out+=this.pad((block.type==='DecoratorBlock'?'DIRECTIVE ':'')+'BLOCK:');this.padding++;out+=this.pad(this.SubExpression(block));if(block.program){out+=this.pad('PROGRAM:');this.padding++;out+=this.accept(block.program);this.padding--;}
if(block.inverse){if(block.program){this.padding++;}
out+=this.pad('{{^}}');this.padding++;out+=this.accept(block.inverse);this.padding--;if(block.program){this.padding--;}}
this.padding--;return out;};PrintVisitor.prototype.PartialStatement=function(partial){var content='PARTIAL:'+partial.name.original;if(partial.params[0]){content+=' '+this.accept(partial.params[0]);}
if(partial.hash){content+=' '+this.accept(partial.hash);}
return this.pad('{{> '+content+' }}');};PrintVisitor.prototype.PartialBlockStatement=function(partial){var content='PARTIAL BLOCK:'+partial.name.original;if(partial.params[0]){content+=' '+this.accept(partial.params[0]);}
if(partial.hash){content+=' '+this.accept(partial.hash);}
content+=' '+this.pad('PROGRAM:');this.padding++;content+=this.accept(partial.program);this.padding--;return this.pad('{{> '+content+' }}');};PrintVisitor.prototype.ContentStatement=function(content){return this.pad("CONTENT[ '"+content.value+"' ]");};PrintVisitor.prototype.CommentStatement=function(comment){return this.pad("{{! '"+comment.value+"' }}");};PrintVisitor.prototype.SubExpression=function(sexpr){var params=sexpr.params,paramStrings=[],hash=undefined;for(var i=0,l=params.length;i<l;i++){paramStrings.push(this.accept(params[i]));}
params='['+paramStrings.join(', ')+']';hash=sexpr.hash?' '+this.accept(sexpr.hash):'';return this.accept(sexpr.path)+' '+params+hash;};PrintVisitor.prototype.PathExpression=function(id){var path=id.parts.join('/');return(id.data?'@':'')+'PATH:'+path;};PrintVisitor.prototype.StringLiteral=function(string){return'"'+string.value+'"';};PrintVisitor.prototype.NumberLiteral=function(number){return'NUMBER{'+number.value+'}';};PrintVisitor.prototype.BooleanLiteral=function(bool){return'BOOLEAN{'+bool.value+'}';};PrintVisitor.prototype.UndefinedLiteral=function(){return'UNDEFINED';};PrintVisitor.prototype.NullLiteral=function(){return'NULL';};PrintVisitor.prototype.Hash=function(hash){var pairs=hash.pairs,joinedPairs=[];for(var i=0,l=pairs.length;i<l;i++){joinedPairs.push(this.accept(pairs[i]));}
return'HASH{'+joinedPairs.join(', ')+'}';};PrintVisitor.prototype.HashPair=function(pair){return pair.key+'='+this.accept(pair.value);};},{"./visitor":258}],258:[function(require,module,exports){'use strict';exports.__esModule=true;function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{'default':obj};}
var _exception=require('../exception');var _exception2=_interopRequireDefault(_exception);function Visitor(){this.parents=[];}
Visitor.prototype={constructor:Visitor,mutating:false,acceptKey:function acceptKey(node,name){var value=this.accept(node[name]);if(this.mutating){if(value&&!Visitor.prototype[value.type]){throw new _exception2['default']('Unexpected node type "'+value.type+'" found when accepting '+name+' on '+node.type);}
node[name]=value;}},acceptRequired:function acceptRequired(node,name){this.acceptKey(node,name);if(!node[name]){throw new _exception2['default'](node.type+' requires '+name);}},acceptArray:function acceptArray(array){for(var i=0,l=array.length;i<l;i++){this.acceptKey(array,i);if(!array[i]){array.splice(i,1);i--;l--;}}},accept:function accept(object){if(!object){return;}
if(!this[object.type]){throw new _exception2['default']('Unknown type: '+object.type,object);}
if(this.current){this.parents.unshift(this.current);}
this.current=object;var ret=this[object.type](object);this.current=this.parents.shift();if(!this.mutating||ret){return ret;}else if(ret!==false){return object;}},Program:function Program(program){this.acceptArray(program.body);},MustacheStatement:visitSubExpression,Decorator:visitSubExpression,BlockStatement:visitBlock,DecoratorBlock:visitBlock,PartialStatement:visitPartial,PartialBlockStatement:function PartialBlockStatement(partial){visitPartial.call(this,partial);this.acceptKey(partial,'program');},ContentStatement:function ContentStatement(){},CommentStatement:function CommentStatement(){},SubExpression:visitSubExpression,PathExpression:function PathExpression(){},StringLiteral:function StringLiteral(){},NumberLiteral:function NumberLiteral(){},BooleanLiteral:function BooleanLiteral(){},UndefinedLiteral:function UndefinedLiteral(){},NullLiteral:function NullLiteral(){},Hash:function Hash(hash){this.acceptArray(hash.pairs);},HashPair:function HashPair(pair){this.acceptRequired(pair,'value');}};function visitSubExpression(mustache){this.acceptRequired(mustache,'path');this.acceptArray(mustache.params);this.acceptKey(mustache,'hash');}
function visitBlock(block){visitSubExpression.call(this,block);this.acceptKey(block,'program');this.acceptKey(block,'inverse');}
function visitPartial(partial){this.acceptRequired(partial,'name');this.acceptArray(partial.params);this.acceptKey(partial,'hash');}
exports['default']=Visitor;module.exports=exports['default'];},{"../exception":262}],259:[function(require,module,exports){'use strict';exports.__esModule=true;function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{'default':obj};}
var _visitor=require('./visitor');var _visitor2=_interopRequireDefault(_visitor);function WhitespaceControl(){var options=arguments.length<=0||arguments[0]===undefined?{}:arguments[0];this.options=options;}
WhitespaceControl.prototype=new _visitor2['default']();WhitespaceControl.prototype.Program=function(program){var doStandalone=!this.options.ignoreStandalone;var isRoot=!this.isRootSeen;this.isRootSeen=true;var body=program.body;for(var i=0,l=body.length;i<l;i++){var current=body[i],strip=this.accept(current);if(!strip){continue;}
var _isPrevWhitespace=isPrevWhitespace(body,i,isRoot),_isNextWhitespace=isNextWhitespace(body,i,isRoot),openStandalone=strip.openStandalone&&_isPrevWhitespace,closeStandalone=strip.closeStandalone&&_isNextWhitespace,inlineStandalone=strip.inlineStandalone&&_isPrevWhitespace&&_isNextWhitespace;if(strip.close){omitRight(body,i,true);}
if(strip.open){omitLeft(body,i,true);}
if(doStandalone&&inlineStandalone){omitRight(body,i);if(omitLeft(body,i)){if(current.type==='PartialStatement'){current.indent=/([ \t]+$)/.exec(body[i-1].original)[1];}}}
if(doStandalone&&openStandalone){omitRight((current.program||current.inverse).body);omitLeft(body,i);}
if(doStandalone&&closeStandalone){omitRight(body,i);omitLeft((current.inverse||current.program).body);}}
return program;};WhitespaceControl.prototype.BlockStatement=WhitespaceControl.prototype.DecoratorBlock=WhitespaceControl.prototype.PartialBlockStatement=function(block){this.accept(block.program);this.accept(block.inverse);var program=block.program||block.inverse,inverse=block.program&&block.inverse,firstInverse=inverse,lastInverse=inverse;if(inverse&&inverse.chained){firstInverse=inverse.body[0].program;while(lastInverse.chained){lastInverse=lastInverse.body[lastInverse.body.length-1].program;}}
var strip={open:block.openStrip.open,close:block.closeStrip.close,openStandalone:isNextWhitespace(program.body),closeStandalone:isPrevWhitespace((firstInverse||program).body)};if(block.openStrip.close){omitRight(program.body,null,true);}
if(inverse){var inverseStrip=block.inverseStrip;if(inverseStrip.open){omitLeft(program.body,null,true);}
if(inverseStrip.close){omitRight(firstInverse.body,null,true);}
if(block.closeStrip.open){omitLeft(lastInverse.body,null,true);}
if(!this.options.ignoreStandalone&&isPrevWhitespace(program.body)&&isNextWhitespace(firstInverse.body)){omitLeft(program.body);omitRight(firstInverse.body);}}else if(block.closeStrip.open){omitLeft(program.body,null,true);}
return strip;};WhitespaceControl.prototype.Decorator=WhitespaceControl.prototype.MustacheStatement=function(mustache){return mustache.strip;};WhitespaceControl.prototype.PartialStatement=WhitespaceControl.prototype.CommentStatement=function(node){var strip=node.strip||{};return{inlineStandalone:true,open:strip.open,close:strip.close};};function isPrevWhitespace(body,i,isRoot){if(i===undefined){i=body.length;}
var prev=body[i-1],sibling=body[i-2];if(!prev){return isRoot;}
if(prev.type==='ContentStatement'){return(sibling||!isRoot?/\r?\n\s*?$/:/(^|\r?\n)\s*?$/).test(prev.original);}}
function isNextWhitespace(body,i,isRoot){if(i===undefined){i=-1;}
var next=body[i+1],sibling=body[i+2];if(!next){return isRoot;}
if(next.type==='ContentStatement'){return(sibling||!isRoot?/^\s*?\r?\n/:/^\s*?(\r?\n|$)/).test(next.original);}}
function omitRight(body,i,multiple){var current=body[i==null?0:i+1];if(!current||current.type!=='ContentStatement'||!multiple&&current.rightStripped){return;}
var original=current.value;current.value=current.value.replace(multiple?/^\s+/:/^[ \t]*\r?\n?/,'');current.rightStripped=current.value!==original;}
function omitLeft(body,i,multiple){var current=body[i==null?body.length-1:i-1];if(!current||current.type!=='ContentStatement'||!multiple&&current.leftStripped){return;}
var original=current.value;current.value=current.value.replace(multiple?/\s+$/:/[ \t]+$/,'');current.leftStripped=current.value!==original;return current.leftStripped;}
exports['default']=WhitespaceControl;module.exports=exports['default'];},{"./visitor":258}],260:[function(require,module,exports){'use strict';exports.__esModule=true;exports.registerDefaultDecorators=registerDefaultDecorators;function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{'default':obj};}
var _decoratorsInline=require('./decorators/inline');var _decoratorsInline2=_interopRequireDefault(_decoratorsInline);function registerDefaultDecorators(instance){_decoratorsInline2['default'](instance);}},{"./decorators/inline":261}],261:[function(require,module,exports){'use strict';exports.__esModule=true;var _utils=require('../utils');exports['default']=function(instance){instance.registerDecorator('inline',function(fn,props,container,options){var ret=fn;if(!props.partials){props.partials={};ret=function(context,options){var original=container.partials;container.partials=_utils.extend({},original,props.partials);var ret=fn(context,options);container.partials=original;return ret;};}
props.partials[options.args[0]]=options.fn;return ret;});};module.exports=exports['default'];},{"../utils":275}],262:[function(require,module,exports){'use strict';exports.__esModule=true;var errorProps=['description','fileName','lineNumber','message','name','number','stack'];function Exception(message,node){var loc=node&&node.loc,line=undefined,column=undefined;if(loc){line=loc.start.line;column=loc.start.column;message+=' - '+line+':'+column;}
var tmp=Error.prototype.constructor.call(this,message);for(var idx=0;idx<errorProps.length;idx++){this[errorProps[idx]]=tmp[errorProps[idx]];}
if(Error.captureStackTrace){Error.captureStackTrace(this,Exception);}
if(loc){this.lineNumber=line;this.column=column;}}
Exception.prototype=new Error();exports['default']=Exception;module.exports=exports['default'];},{}],263:[function(require,module,exports){'use strict';exports.__esModule=true;exports.registerDefaultHelpers=registerDefaultHelpers;function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{'default':obj};}
var _helpersBlockHelperMissing=require('./helpers/block-helper-missing');var _helpersBlockHelperMissing2=_interopRequireDefault(_helpersBlockHelperMissing);var _helpersEach=require('./helpers/each');var _helpersEach2=_interopRequireDefault(_helpersEach);var _helpersHelperMissing=require('./helpers/helper-missing');var _helpersHelperMissing2=_interopRequireDefault(_helpersHelperMissing);var _helpersIf=require('./helpers/if');var _helpersIf2=_interopRequireDefault(_helpersIf);var _helpersLog=require('./helpers/log');var _helpersLog2=_interopRequireDefault(_helpersLog);var _helpersLookup=require('./helpers/lookup');var _helpersLookup2=_interopRequireDefault(_helpersLookup);var _helpersWith=require('./helpers/with');var _helpersWith2=_interopRequireDefault(_helpersWith);function registerDefaultHelpers(instance){_helpersBlockHelperMissing2['default'](instance);_helpersEach2['default'](instance);_helpersHelperMissing2['default'](instance);_helpersIf2['default'](instance);_helpersLog2['default'](instance);_helpersLookup2['default'](instance);_helpersWith2['default'](instance);}},{"./helpers/block-helper-missing":264,"./helpers/each":265,"./helpers/helper-missing":266,"./helpers/if":267,"./helpers/log":268,"./helpers/lookup":269,"./helpers/with":270}],264:[function(require,module,exports){'use strict';exports.__esModule=true;var _utils=require('../utils');exports['default']=function(instance){instance.registerHelper('blockHelperMissing',function(context,options){var inverse=options.inverse,fn=options.fn;if(context===true){return fn(this);}else if(context===false||context==null){return inverse(this);}else if(_utils.isArray(context)){if(context.length>0){if(options.ids){options.ids=[options.name];}
return instance.helpers.each(context,options);}else{return inverse(this);}}else{if(options.data&&options.ids){var data=_utils.createFrame(options.data);data.contextPath=_utils.appendContextPath(options.data.contextPath,options.name);options={data:data};}
return fn(context,options);}});};module.exports=exports['default'];},{"../utils":275}],265:[function(require,module,exports){'use strict';exports.__esModule=true;function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{'default':obj};}
var _utils=require('../utils');var _exception=require('../exception');var _exception2=_interopRequireDefault(_exception);exports['default']=function(instance){instance.registerHelper('each',function(context,options){if(!options){throw new _exception2['default']('Must pass iterator to #each');}
var fn=options.fn,inverse=options.inverse,i=0,ret='',data=undefined,contextPath=undefined;if(options.data&&options.ids){contextPath=_utils.appendContextPath(options.data.contextPath,options.ids[0])+'.';}
if(_utils.isFunction(context)){context=context.call(this);}
if(options.data){data=_utils.createFrame(options.data);}
function execIteration(field,index,last){if(data){data.key=field;data.index=index;data.first=index===0;data.last=!!last;if(contextPath){data.contextPath=contextPath+field;}}
ret=ret+fn(context[field],{data:data,blockParams:_utils.blockParams([context[field],field],[contextPath+field,null])});}
if(context&&typeof context==='object'){if(_utils.isArray(context)){for(var j=context.length;i<j;i++){if(i in context){execIteration(i,i,i===context.length-1);}}}else{var priorKey=undefined;for(var key in context){if(context.hasOwnProperty(key)){if(priorKey!==undefined){execIteration(priorKey,i-1);}
priorKey=key;i++;}}
if(priorKey!==undefined){execIteration(priorKey,i-1,true);}}}
if(i===0){ret=inverse(this);}
return ret;});};module.exports=exports['default'];},{"../exception":262,"../utils":275}],266:[function(require,module,exports){'use strict';exports.__esModule=true;function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{'default':obj};}
var _exception=require('../exception');var _exception2=_interopRequireDefault(_exception);exports['default']=function(instance){instance.registerHelper('helperMissing',function(){if(arguments.length===1){return undefined;}else{throw new _exception2['default']('Missing helper: "'+arguments[arguments.length-1].name+'"');}});};module.exports=exports['default'];},{"../exception":262}],267:[function(require,module,exports){'use strict';exports.__esModule=true;var _utils=require('../utils');exports['default']=function(instance){instance.registerHelper('if',function(conditional,options){if(_utils.isFunction(conditional)){conditional=conditional.call(this);}
if(!options.hash.includeZero&&!conditional||_utils.isEmpty(conditional)){return options.inverse(this);}else{return options.fn(this);}});instance.registerHelper('unless',function(conditional,options){return instance.helpers['if'].call(this,conditional,{fn:options.inverse,inverse:options.fn,hash:options.hash});});};module.exports=exports['default'];},{"../utils":275}],268:[function(require,module,exports){'use strict';exports.__esModule=true;exports['default']=function(instance){instance.registerHelper('log',function(){var args=[undefined],options=arguments[arguments.length-1];for(var i=0;i<arguments.length-1;i++){args.push(arguments[i]);}
var level=1;if(options.hash.level!=null){level=options.hash.level;}else if(options.data&&options.data.level!=null){level=options.data.level;}
args[0]=level;instance.log.apply(instance,args);});};module.exports=exports['default'];},{}],269:[function(require,module,exports){'use strict';exports.__esModule=true;exports['default']=function(instance){instance.registerHelper('lookup',function(obj,field){return obj&&obj[field];});};module.exports=exports['default'];},{}],270:[function(require,module,exports){'use strict';exports.__esModule=true;var _utils=require('../utils');exports['default']=function(instance){instance.registerHelper('with',function(context,options){if(_utils.isFunction(context)){context=context.call(this);}
var fn=options.fn;if(!_utils.isEmpty(context)){var data=options.data;if(options.data&&options.ids){data=_utils.createFrame(options.data);data.contextPath=_utils.appendContextPath(options.data.contextPath,options.ids[0]);}
return fn(context,{data:data,blockParams:_utils.blockParams([context],[data&&data.contextPath])});}else{return options.inverse(this);}});};module.exports=exports['default'];},{"../utils":275}],271:[function(require,module,exports){'use strict';exports.__esModule=true;var _utils=require('./utils');var logger={methodMap:['debug','info','warn','error'],level:'info',lookupLevel:function lookupLevel(level){if(typeof level==='string'){var levelMap=_utils.indexOf(logger.methodMap,level.toLowerCase());if(levelMap>=0){level=levelMap;}else{level=parseInt(level,10);}}
return level;},log:function log(level){level=logger.lookupLevel(level);if(typeof console!=='undefined'&&logger.lookupLevel(logger.level)<=level){var method=logger.methodMap[level];if(!console[method]){method='log';}
for(var _len=arguments.length,message=Array(_len>1?_len-1:0),_key=1;_key<_len;_key++){message[_key-1]=arguments[_key];}
console[method].apply(console,message);}}};exports['default']=logger;module.exports=exports['default'];},{"./utils":275}],272:[function(require,module,exports){(function(global){'use strict';exports.__esModule=true;exports['default']=function(Handlebars){var root=typeof global!=='undefined'?global:window,$Handlebars=root.Handlebars;Handlebars.noConflict=function(){if(root.Handlebars===Handlebars){root.Handlebars=$Handlebars;}
return Handlebars;};};module.exports=exports['default'];}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],273:[function(require,module,exports){'use strict';exports.__esModule=true;exports.checkRevision=checkRevision;exports.template=template;exports.wrapProgram=wrapProgram;exports.resolvePartial=resolvePartial;exports.invokePartial=invokePartial;exports.noop=noop;function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{'default':obj};}
function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj['default']=obj;return newObj;}}
var _utils=require('./utils');var Utils=_interopRequireWildcard(_utils);var _exception=require('./exception');var _exception2=_interopRequireDefault(_exception);var _base=require('./base');function checkRevision(compilerInfo){var compilerRevision=compilerInfo&&compilerInfo[0]||1,currentRevision=_base.COMPILER_REVISION;if(compilerRevision!==currentRevision){if(compilerRevision<currentRevision){var runtimeVersions=_base.REVISION_CHANGES[currentRevision],compilerVersions=_base.REVISION_CHANGES[compilerRevision];throw new _exception2['default']('Template was precompiled with an older version of Handlebars than the current runtime. '+'Please update your precompiler to a newer version ('+runtimeVersions+') or downgrade your runtime to an older version ('+compilerVersions+').');}else{throw new _exception2['default']('Template was precompiled with a newer version of Handlebars than the current runtime. '+'Please update your runtime to a newer version ('+compilerInfo[1]+').');}}}
function template(templateSpec,env){if(!env){throw new _exception2['default']('No environment passed to template');}
if(!templateSpec||!templateSpec.main){throw new _exception2['default']('Unknown template object: '+typeof templateSpec);}
templateSpec.main.decorator=templateSpec.main_d;env.VM.checkRevision(templateSpec.compiler);function invokePartialWrapper(partial,context,options){if(options.hash){context=Utils.extend({},context,options.hash);if(options.ids){options.ids[0]=true;}}
partial=env.VM.resolvePartial.call(this,partial,context,options);var result=env.VM.invokePartial.call(this,partial,context,options);if(result==null&&env.compile){options.partials[options.name]=env.compile(partial,templateSpec.compilerOptions,env);result=options.partials[options.name](context,options);}
if(result!=null){if(options.indent){var lines=result.split('\n');for(var i=0,l=lines.length;i<l;i++){if(!lines[i]&&i+1===l){break;}
lines[i]=options.indent+lines[i];}
result=lines.join('\n');}
return result;}else{throw new _exception2['default']('The partial '+options.name+' could not be compiled when running in runtime-only mode');}}
var container={strict:function strict(obj,name){if(!(name in obj)){throw new _exception2['default']('"'+name+'" not defined in '+obj);}
return obj[name];},lookup:function lookup(depths,name){var len=depths.length;for(var i=0;i<len;i++){if(depths[i]&&depths[i][name]!=null){return depths[i][name];}}},lambda:function lambda(current,context){return typeof current==='function'?current.call(context):current;},escapeExpression:Utils.escapeExpression,invokePartial:invokePartialWrapper,fn:function fn(i){var ret=templateSpec[i];ret.decorator=templateSpec[i+'_d'];return ret;},programs:[],program:function program(i,data,declaredBlockParams,blockParams,depths){var programWrapper=this.programs[i],fn=this.fn(i);if(data||depths||blockParams||declaredBlockParams){programWrapper=wrapProgram(this,i,fn,data,declaredBlockParams,blockParams,depths);}else if(!programWrapper){programWrapper=this.programs[i]=wrapProgram(this,i,fn);}
return programWrapper;},data:function data(value,depth){while(value&&depth--){value=value._parent;}
return value;},merge:function merge(param,common){var obj=param||common;if(param&&common&&param!==common){obj=Utils.extend({},common,param);}
return obj;},noop:env.VM.noop,compilerInfo:templateSpec.compiler};function ret(context){var options=arguments.length<=1||arguments[1]===undefined?{}:arguments[1];var data=options.data;ret._setup(options);if(!options.partial&&templateSpec.useData){data=initData(context,data);}
var depths=undefined,blockParams=templateSpec.useBlockParams?[]:undefined;if(templateSpec.useDepths){if(options.depths){depths=context!==options.depths[0]?[context].concat(options.depths):options.depths;}else{depths=[context];}}
function main(context){return''+templateSpec.main(container,context,container.helpers,container.partials,data,blockParams,depths);}
main=executeDecorators(templateSpec.main,main,container,options.depths||[],data,blockParams);return main(context,options);}
ret.isTop=true;ret._setup=function(options){if(!options.partial){container.helpers=container.merge(options.helpers,env.helpers);if(templateSpec.usePartial){container.partials=container.merge(options.partials,env.partials);}
if(templateSpec.usePartial||templateSpec.useDecorators){container.decorators=container.merge(options.decorators,env.decorators);}}else{container.helpers=options.helpers;container.partials=options.partials;container.decorators=options.decorators;}};ret._child=function(i,data,blockParams,depths){if(templateSpec.useBlockParams&&!blockParams){throw new _exception2['default']('must pass block params');}
if(templateSpec.useDepths&&!depths){throw new _exception2['default']('must pass parent depths');}
return wrapProgram(container,i,templateSpec[i],data,0,blockParams,depths);};return ret;}
function wrapProgram(container,i,fn,data,declaredBlockParams,blockParams,depths){function prog(context){var options=arguments.length<=1||arguments[1]===undefined?{}:arguments[1];var currentDepths=depths;if(depths&&context!==depths[0]){currentDepths=[context].concat(depths);}
return fn(container,context,container.helpers,container.partials,options.data||data,blockParams&&[options.blockParams].concat(blockParams),currentDepths);}
prog=executeDecorators(fn,prog,container,depths,data,blockParams);prog.program=i;prog.depth=depths?depths.length:0;prog.blockParams=declaredBlockParams||0;return prog;}
function resolvePartial(partial,context,options){if(!partial){if(options.name==='@partial-block'){partial=options.data['partial-block'];}else{partial=options.partials[options.name];}}else if(!partial.call&&!options.name){options.name=partial;partial=options.partials[partial];}
return partial;}
function invokePartial(partial,context,options){options.partial=true;if(options.ids){options.data.contextPath=options.ids[0]||options.data.contextPath;}
var partialBlock=undefined;if(options.fn&&options.fn!==noop){options.data=_base.createFrame(options.data);partialBlock=options.data['partial-block']=options.fn;if(partialBlock.partials){options.partials=Utils.extend({},options.partials,partialBlock.partials);}}
if(partial===undefined&&partialBlock){partial=partialBlock;}
if(partial===undefined){throw new _exception2['default']('The partial '+options.name+' could not be found');}else if(partial instanceof Function){return partial(context,options);}}
function noop(){return'';}
function initData(context,data){if(!data||!('root'in data)){data=data?_base.createFrame(data):{};data.root=context;}
return data;}
function executeDecorators(fn,prog,container,depths,data,blockParams){if(fn.decorator){var props={};prog=fn.decorator(prog,props,container,depths&&depths[0],data,blockParams,depths);Utils.extend(prog,props);}
return prog;}},{"./base":249,"./exception":262,"./utils":275}],274:[function(require,module,exports){'use strict';exports.__esModule=true;function SafeString(string){this.string=string;}
SafeString.prototype.toString=SafeString.prototype.toHTML=function(){return''+this.string;};exports['default']=SafeString;module.exports=exports['default'];},{}],275:[function(require,module,exports){'use strict';exports.__esModule=true;exports.extend=extend;exports.indexOf=indexOf;exports.escapeExpression=escapeExpression;exports.isEmpty=isEmpty;exports.createFrame=createFrame;exports.blockParams=blockParams;exports.appendContextPath=appendContextPath;var escape={'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#x27;','`':'&#x60;','=':'&#x3D;'};var badChars=/[&<>"'`=]/g,possible=/[&<>"'`=]/;function escapeChar(chr){return escape[chr];}
function extend(obj){for(var i=1;i<arguments.length;i++){for(var key in arguments[i]){if(Object.prototype.hasOwnProperty.call(arguments[i],key)){obj[key]=arguments[i][key];}}}
return obj;}
var toString=Object.prototype.toString;exports.toString=toString;var isFunction=function isFunction(value){return typeof value==='function';};if(isFunction(/x/)){exports.isFunction=isFunction=function(value){return typeof value==='function'&&toString.call(value)==='[object Function]';};}
exports.isFunction=isFunction;var isArray=Array.isArray||function(value){return value&&typeof value==='object'?toString.call(value)==='[object Array]':false;};exports.isArray=isArray;function indexOf(array,value){for(var i=0,len=array.length;i<len;i++){if(array[i]===value){return i;}}
return-1;}
function escapeExpression(string){if(typeof string!=='string'){if(string&&string.toHTML){return string.toHTML();}else if(string==null){return'';}else if(!string){return string+'';}
string=''+string;}
if(!possible.test(string)){return string;}
return string.replace(badChars,escapeChar);}
function isEmpty(value){if(!value&&value!==0){return true;}else if(isArray(value)&&value.length===0){return true;}else{return false;}}
function createFrame(object){var frame=extend({},object);frame._parent=object;return frame;}
function blockParams(params,ids){params.path=ids;return params;}
function appendContextPath(contextPath,id){return(contextPath?contextPath+'.':'')+id;}},{}],276:[function(require,module,exports){var handlebars=require('../dist/cjs/handlebars')['default'];var printer=require('../dist/cjs/handlebars/compiler/printer');handlebars.PrintVisitor=printer.PrintVisitor;handlebars.print=printer.print;module.exports=handlebars;function extension(module,filename){var templateString=fs.readFileSync(filename,'utf8');module.exports=handlebars.compile(templateString);}
if(typeof require!=='undefined'&&require.extensions){require.extensions['.handlebars']=extension;require.extensions['.hbs']=extension;}},{"../dist/cjs/handlebars":247,"../dist/cjs/handlebars/compiler/printer":257}],277:[function(require,module,exports){var ImageSSIM;(function(ImageSSIM){'use strict';(function(Channels){Channels[Channels["Grey"]=1]="Grey";Channels[Channels["GreyAlpha"]=2]="GreyAlpha";Channels[Channels["RGB"]=3]="RGB";Channels[Channels["RGBAlpha"]=4]="RGBAlpha";})(ImageSSIM.Channels||(ImageSSIM.Channels={}));var Channels=ImageSSIM.Channels;function compare(image1,image2,windowSize,K1,K2,luminance,bitsPerComponent){if(windowSize===void 0){windowSize=8;}
if(K1===void 0){K1=0.01;}
if(K2===void 0){K2=0.03;}
if(luminance===void 0){luminance=true;}
if(bitsPerComponent===void 0){bitsPerComponent=8;}
if(image1.width!==image2.width||image1.height!==image2.height){throw new Error('Images have different sizes!');}
var L=(1<<bitsPerComponent)-1;var c1=Math.pow((K1*L),2),c2=Math.pow((K2*L),2),numWindows=0,mssim=0.0;var mcs=0.0;function iteration(lumaValues1,lumaValues2,averageLumaValue1,averageLumaValue2){var sigxy,sigsqx,sigsqy;sigxy=sigsqx=sigsqy=0.0;for(var i=0;i<lumaValues1.length;i++){sigsqx+=Math.pow((lumaValues1[i]-averageLumaValue1),2);sigsqy+=Math.pow((lumaValues2[i]-averageLumaValue2),2);sigxy+=(lumaValues1[i]-averageLumaValue1)*(lumaValues2[i]-averageLumaValue2);}
var numPixelsInWin=lumaValues1.length-1;sigsqx/=numPixelsInWin;sigsqy/=numPixelsInWin;sigxy/=numPixelsInWin;var numerator=(2*averageLumaValue1*averageLumaValue2+c1)*(2*sigxy+c2);var denominator=(Math.pow(averageLumaValue1,2)+Math.pow(averageLumaValue2,2)+c1)*(sigsqx+sigsqy+c2);mssim+=numerator/denominator;mcs+=(2*sigxy+c2)/(sigsqx+sigsqy+c2);numWindows++;}
Internals._iterate(image1,image2,windowSize,luminance,iteration);return{ssim:mssim/numWindows,mcs:mcs/numWindows};}
ImageSSIM.compare=compare;var Internals;(function(Internals){function _iterate(image1,image2,windowSize,luminance,callback){var width=image1.width,height=image1.height;for(var y=0;y<height;y+=windowSize){for(var x=0;x<width;x+=windowSize){var windowWidth=Math.min(windowSize,width-x),windowHeight=Math.min(windowSize,height-y);var lumaValues1=_lumaValuesForWindow(image1,x,y,windowWidth,windowHeight,luminance),lumaValues2=_lumaValuesForWindow(image2,x,y,windowWidth,windowHeight,luminance),averageLuma1=_averageLuma(lumaValues1),averageLuma2=_averageLuma(lumaValues2);callback(lumaValues1,lumaValues2,averageLuma1,averageLuma2);}}}
Internals._iterate=_iterate;function _lumaValuesForWindow(image,x,y,width,height,luminance){var array=image.data,lumaValues=new Float32Array(new ArrayBuffer(width*height*4)),counter=0;var maxj=y+height;for(var j=y;j<maxj;j++){var offset=j*image.width;var i=(offset+x)*image.channels;var maxi=(offset+x+width)*image.channels;switch(image.channels){case 1:while(i<maxi){lumaValues[counter++]=array[i++];}
break;case 2:while(i<maxi){lumaValues[counter++]=array[i++]*(array[i++]/255);}
break;case 3:if(luminance){while(i<maxi){lumaValues[counter++]=(array[i++]*0.212655+array[i++]*0.715158+array[i++]*0.072187);}}
else{while(i<maxi){lumaValues[counter++]=(array[i++]+array[i++]+array[i++]);}}
break;case 4:if(luminance){while(i<maxi){lumaValues[counter++]=(array[i++]*0.212655+array[i++]*0.715158+array[i++]*0.072187)*(array[i++]/255);}}
else{while(i<maxi){lumaValues[counter++]=(array[i++]+array[i++]+array[i++])*(array[i++]/255);}}
break;}}
return lumaValues;}
function _averageLuma(lumaValues){var sumLuma=0.0;for(var i=0;i<lumaValues.length;i++){sumLuma+=lumaValues[i];}
return sumLuma/lumaValues.length;}})(Internals||(Internals={}));})(ImageSSIM||(ImageSSIM={}));module.exports=ImageSSIM;},{}],278:[function(require,module,exports){var encode=require('./lib/encoder'),decode=require('./lib/decoder');module.exports={encode:encode,decode:decode};},{"./lib/decoder":279,"./lib/encoder":280}],279:[function(require,module,exports){(function(Buffer){var JpegImage=(function jpegImage(){"use strict";var dctZigZag=new Int32Array([0,1,8,16,9,2,3,10,17,24,32,25,18,11,4,5,12,19,26,33,40,48,41,34,27,20,13,6,7,14,21,28,35,42,49,56,57,50,43,36,29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54,47,55,62,63]);var dctCos1=4017
var dctSin1=799
var dctCos3=3406
var dctSin3=2276
var dctCos6=1567
var dctSin6=3784
var dctSqrt2=5793
var dctSqrt1d2=2896
function constructor(){}
function buildHuffmanTable(codeLengths,values){var k=0,code=[],i,j,length=16;while(length>0&&!codeLengths[length-1])
length--;code.push({children:[],index:0});var p=code[0],q;for(i=0;i<length;i++){for(j=0;j<codeLengths[i];j++){p=code.pop();p.children[p.index]=values[k];while(p.index>0){p=code.pop();}
p.index++;code.push(p);while(code.length<=i){code.push(q={children:[],index:0});p.children[p.index]=q.children;p=q;}
k++;}
if(i+1<length){code.push(q={children:[],index:0});p.children[p.index]=q.children;p=q;}}
return code[0].children;}
function decodeScan(data,offset,frame,components,resetInterval,spectralStart,spectralEnd,successivePrev,successive){var precision=frame.precision;var samplesPerLine=frame.samplesPerLine;var scanLines=frame.scanLines;var mcusPerLine=frame.mcusPerLine;var progressive=frame.progressive;var maxH=frame.maxH,maxV=frame.maxV;var startOffset=offset,bitsData=0,bitsCount=0;function readBit(){if(bitsCount>0){bitsCount--;return(bitsData>>bitsCount)&1;}
bitsData=data[offset++];if(bitsData==0xFF){var nextByte=data[offset++];if(nextByte){throw"unexpected marker: "+((bitsData<<8)|nextByte).toString(16);}}
bitsCount=7;return bitsData>>>7;}
function decodeHuffman(tree){var node=tree,bit;while((bit=readBit())!==null){node=node[bit];if(typeof node==='number')
return node;if(typeof node!=='object')
throw"invalid huffman sequence";}
return null;}
function receive(length){var n=0;while(length>0){var bit=readBit();if(bit===null)return;n=(n<<1)|bit;length--;}
return n;}
function receiveAndExtend(length){var n=receive(length);if(n>=1<<(length-1))
return n;return n+(-1<<length)+1;}
function decodeBaseline(component,zz){var t=decodeHuffman(component.huffmanTableDC);var diff=t===0?0:receiveAndExtend(t);zz[0]=(component.pred+=diff);var k=1;while(k<64){var rs=decodeHuffman(component.huffmanTableAC);var s=rs&15,r=rs>>4;if(s===0){if(r<15)
break;k+=16;continue;}
k+=r;var z=dctZigZag[k];zz[z]=receiveAndExtend(s);k++;}}
function decodeDCFirst(component,zz){var t=decodeHuffman(component.huffmanTableDC);var diff=t===0?0:(receiveAndExtend(t)<<successive);zz[0]=(component.pred+=diff);}
function decodeDCSuccessive(component,zz){zz[0]|=readBit()<<successive;}
var eobrun=0;function decodeACFirst(component,zz){if(eobrun>0){eobrun--;return;}
var k=spectralStart,e=spectralEnd;while(k<=e){var rs=decodeHuffman(component.huffmanTableAC);var s=rs&15,r=rs>>4;if(s===0){if(r<15){eobrun=receive(r)+(1<<r)-1;break;}
k+=16;continue;}
k+=r;var z=dctZigZag[k];zz[z]=receiveAndExtend(s)*(1<<successive);k++;}}
var successiveACState=0,successiveACNextValue;function decodeACSuccessive(component,zz){var k=spectralStart,e=spectralEnd,r=0;while(k<=e){var z=dctZigZag[k];switch(successiveACState){case 0:var rs=decodeHuffman(component.huffmanTableAC);var s=rs&15,r=rs>>4;if(s===0){if(r<15){eobrun=receive(r)+(1<<r);successiveACState=4;}else{r=16;successiveACState=1;}}else{if(s!==1)
throw"invalid ACn encoding";successiveACNextValue=receiveAndExtend(s);successiveACState=r?2:3;}
continue;case 1:case 2:if(zz[z])
zz[z]+=(readBit()<<successive);else{r--;if(r===0)
successiveACState=successiveACState==2?3:0;}
break;case 3:if(zz[z])
zz[z]+=(readBit()<<successive);else{zz[z]=successiveACNextValue<<successive;successiveACState=0;}
break;case 4:if(zz[z])
zz[z]+=(readBit()<<successive);break;}
k++;}
if(successiveACState===4){eobrun--;if(eobrun===0)
successiveACState=0;}}
function decodeMcu(component,decode,mcu,row,col){var mcuRow=(mcu/mcusPerLine)|0;var mcuCol=mcu%mcusPerLine;var blockRow=mcuRow*component.v+row;var blockCol=mcuCol*component.h+col;decode(component,component.blocks[blockRow][blockCol]);}
function decodeBlock(component,decode,mcu){var blockRow=(mcu/component.blocksPerLine)|0;var blockCol=mcu%component.blocksPerLine;decode(component,component.blocks[blockRow][blockCol]);}
var componentsLength=components.length;var component,i,j,k,n;var decodeFn;if(progressive){if(spectralStart===0)
decodeFn=successivePrev===0?decodeDCFirst:decodeDCSuccessive;else
decodeFn=successivePrev===0?decodeACFirst:decodeACSuccessive;}else{decodeFn=decodeBaseline;}
var mcu=0,marker;var mcuExpected;if(componentsLength==1){mcuExpected=components[0].blocksPerLine*components[0].blocksPerColumn;}else{mcuExpected=mcusPerLine*frame.mcusPerColumn;}
if(!resetInterval)resetInterval=mcuExpected;var h,v;while(mcu<mcuExpected){for(i=0;i<componentsLength;i++)
components[i].pred=0;eobrun=0;if(componentsLength==1){component=components[0];for(n=0;n<resetInterval;n++){decodeBlock(component,decodeFn,mcu);mcu++;}}else{for(n=0;n<resetInterval;n++){for(i=0;i<componentsLength;i++){component=components[i];h=component.h;v=component.v;for(j=0;j<v;j++){for(k=0;k<h;k++){decodeMcu(component,decodeFn,mcu,j,k);}}}
mcu++;if(mcu===mcuExpected)break;}}
bitsCount=0;marker=(data[offset]<<8)|data[offset+1];if(marker<0xFF00){throw"marker was not found";}
if(marker>=0xFFD0&&marker<=0xFFD7){offset+=2;}
else
break;}
return offset-startOffset;}
function buildComponentData(frame,component){var lines=[];var blocksPerLine=component.blocksPerLine;var blocksPerColumn=component.blocksPerColumn;var samplesPerLine=blocksPerLine<<3;var R=new Int32Array(64),r=new Uint8Array(64);function quantizeAndInverse(zz,dataOut,dataIn){var qt=component.quantizationTable;var v0,v1,v2,v3,v4,v5,v6,v7,t;var p=dataIn;var i;for(i=0;i<64;i++)
p[i]=zz[i]*qt[i];for(i=0;i<8;++i){var row=8*i;if(p[1+row]==0&&p[2+row]==0&&p[3+row]==0&&p[4+row]==0&&p[5+row]==0&&p[6+row]==0&&p[7+row]==0){t=(dctSqrt2*p[0+row]+512)>>10;p[0+row]=t;p[1+row]=t;p[2+row]=t;p[3+row]=t;p[4+row]=t;p[5+row]=t;p[6+row]=t;p[7+row]=t;continue;}
v0=(dctSqrt2*p[0+row]+128)>>8;v1=(dctSqrt2*p[4+row]+128)>>8;v2=p[2+row];v3=p[6+row];v4=(dctSqrt1d2*(p[1+row]-p[7+row])+128)>>8;v7=(dctSqrt1d2*(p[1+row]+p[7+row])+128)>>8;v5=p[3+row]<<4;v6=p[5+row]<<4;t=(v0-v1+1)>>1;v0=(v0+v1+1)>>1;v1=t;t=(v2*dctSin6+v3*dctCos6+128)>>8;v2=(v2*dctCos6-v3*dctSin6+128)>>8;v3=t;t=(v4-v6+1)>>1;v4=(v4+v6+1)>>1;v6=t;t=(v7+v5+1)>>1;v5=(v7-v5+1)>>1;v7=t;t=(v0-v3+1)>>1;v0=(v0+v3+1)>>1;v3=t;t=(v1-v2+1)>>1;v1=(v1+v2+1)>>1;v2=t;t=(v4*dctSin3+v7*dctCos3+2048)>>12;v4=(v4*dctCos3-v7*dctSin3+2048)>>12;v7=t;t=(v5*dctSin1+v6*dctCos1+2048)>>12;v5=(v5*dctCos1-v6*dctSin1+2048)>>12;v6=t;p[0+row]=v0+v7;p[7+row]=v0-v7;p[1+row]=v1+v6;p[6+row]=v1-v6;p[2+row]=v2+v5;p[5+row]=v2-v5;p[3+row]=v3+v4;p[4+row]=v3-v4;}
for(i=0;i<8;++i){var col=i;if(p[1*8+col]==0&&p[2*8+col]==0&&p[3*8+col]==0&&p[4*8+col]==0&&p[5*8+col]==0&&p[6*8+col]==0&&p[7*8+col]==0){t=(dctSqrt2*dataIn[i+0]+8192)>>14;p[0*8+col]=t;p[1*8+col]=t;p[2*8+col]=t;p[3*8+col]=t;p[4*8+col]=t;p[5*8+col]=t;p[6*8+col]=t;p[7*8+col]=t;continue;}
v0=(dctSqrt2*p[0*8+col]+2048)>>12;v1=(dctSqrt2*p[4*8+col]+2048)>>12;v2=p[2*8+col];v3=p[6*8+col];v4=(dctSqrt1d2*(p[1*8+col]-p[7*8+col])+2048)>>12;v7=(dctSqrt1d2*(p[1*8+col]+p[7*8+col])+2048)>>12;v5=p[3*8+col];v6=p[5*8+col];t=(v0-v1+1)>>1;v0=(v0+v1+1)>>1;v1=t;t=(v2*dctSin6+v3*dctCos6+2048)>>12;v2=(v2*dctCos6-v3*dctSin6+2048)>>12;v3=t;t=(v4-v6+1)>>1;v4=(v4+v6+1)>>1;v6=t;t=(v7+v5+1)>>1;v5=(v7-v5+1)>>1;v7=t;t=(v0-v3+1)>>1;v0=(v0+v3+1)>>1;v3=t;t=(v1-v2+1)>>1;v1=(v1+v2+1)>>1;v2=t;t=(v4*dctSin3+v7*dctCos3+2048)>>12;v4=(v4*dctCos3-v7*dctSin3+2048)>>12;v7=t;t=(v5*dctSin1+v6*dctCos1+2048)>>12;v5=(v5*dctCos1-v6*dctSin1+2048)>>12;v6=t;p[0*8+col]=v0+v7;p[7*8+col]=v0-v7;p[1*8+col]=v1+v6;p[6*8+col]=v1-v6;p[2*8+col]=v2+v5;p[5*8+col]=v2-v5;p[3*8+col]=v3+v4;p[4*8+col]=v3-v4;}
for(i=0;i<64;++i){var sample=128+((p[i]+8)>>4);dataOut[i]=sample<0?0:sample>0xFF?0xFF:sample;}}
var i,j;for(var blockRow=0;blockRow<blocksPerColumn;blockRow++){var scanLine=blockRow<<3;for(i=0;i<8;i++)
lines.push(new Uint8Array(samplesPerLine));for(var blockCol=0;blockCol<blocksPerLine;blockCol++){quantizeAndInverse(component.blocks[blockRow][blockCol],r,R);var offset=0,sample=blockCol<<3;for(j=0;j<8;j++){var line=lines[scanLine+j];for(i=0;i<8;i++)
line[sample+i]=r[offset++];}}}
return lines;}
function clampTo8bit(a){return a<0?0:a>255?255:a;}
constructor.prototype={load:function load(path){var xhr=new XMLHttpRequest();xhr.open("GET",path,true);xhr.responseType="arraybuffer";xhr.onload=(function(){var data=new Uint8Array(xhr.response||xhr.mozResponseArrayBuffer);this.parse(data);if(this.onload)
this.onload();}).bind(this);xhr.send(null);},parse:function parse(data){var offset=0,length=data.length;function readUint16(){var value=(data[offset]<<8)|data[offset+1];offset+=2;return value;}
function readDataBlock(){var length=readUint16();var array=data.subarray(offset,offset+length-2);offset+=array.length;return array;}
function prepareComponents(frame){var maxH=0,maxV=0;var component,componentId;for(componentId in frame.components){if(frame.components.hasOwnProperty(componentId)){component=frame.components[componentId];if(maxH<component.h)maxH=component.h;if(maxV<component.v)maxV=component.v;}}
var mcusPerLine=Math.ceil(frame.samplesPerLine/8/maxH);var mcusPerColumn=Math.ceil(frame.scanLines/8/maxV);for(componentId in frame.components){if(frame.components.hasOwnProperty(componentId)){component=frame.components[componentId];var blocksPerLine=Math.ceil(Math.ceil(frame.samplesPerLine/8)*component.h/maxH);var blocksPerColumn=Math.ceil(Math.ceil(frame.scanLines/8)*component.v/maxV);var blocksPerLineForMcu=mcusPerLine*component.h;var blocksPerColumnForMcu=mcusPerColumn*component.v;var blocks=[];for(var i=0;i<blocksPerColumnForMcu;i++){var row=[];for(var j=0;j<blocksPerLineForMcu;j++)
row.push(new Int32Array(64));blocks.push(row);}
component.blocksPerLine=blocksPerLine;component.blocksPerColumn=blocksPerColumn;component.blocks=blocks;}}
frame.maxH=maxH;frame.maxV=maxV;frame.mcusPerLine=mcusPerLine;frame.mcusPerColumn=mcusPerColumn;}
var jfif=null;var adobe=null;var pixels=null;var frame,resetInterval;var quantizationTables=[],frames=[];var huffmanTablesAC=[],huffmanTablesDC=[];var fileMarker=readUint16();if(fileMarker!=0xFFD8){throw"SOI not found";}
fileMarker=readUint16();while(fileMarker!=0xFFD9){var i,j,l;switch(fileMarker){case 0xFF00:break;case 0xFFE0:case 0xFFE1:case 0xFFE2:case 0xFFE3:case 0xFFE4:case 0xFFE5:case 0xFFE6:case 0xFFE7:case 0xFFE8:case 0xFFE9:case 0xFFEA:case 0xFFEB:case 0xFFEC:case 0xFFED:case 0xFFEE:case 0xFFEF:case 0xFFFE:var appData=readDataBlock();if(fileMarker===0xFFE0){if(appData[0]===0x4A&&appData[1]===0x46&&appData[2]===0x49&&appData[3]===0x46&&appData[4]===0){jfif={version:{major:appData[5],minor:appData[6]},densityUnits:appData[7],xDensity:(appData[8]<<8)|appData[9],yDensity:(appData[10]<<8)|appData[11],thumbWidth:appData[12],thumbHeight:appData[13],thumbData:appData.subarray(14,14+3*appData[12]*appData[13])};}}
if(fileMarker===0xFFEE){if(appData[0]===0x41&&appData[1]===0x64&&appData[2]===0x6F&&appData[3]===0x62&&appData[4]===0x65&&appData[5]===0){adobe={version:appData[6],flags0:(appData[7]<<8)|appData[8],flags1:(appData[9]<<8)|appData[10],transformCode:appData[11]};}}
break;case 0xFFDB:var quantizationTablesLength=readUint16();var quantizationTablesEnd=quantizationTablesLength+offset-2;while(offset<quantizationTablesEnd){var quantizationTableSpec=data[offset++];var tableData=new Int32Array(64);if((quantizationTableSpec>>4)===0){for(j=0;j<64;j++){var z=dctZigZag[j];tableData[z]=data[offset++];}}else if((quantizationTableSpec>>4)===1){for(j=0;j<64;j++){var z=dctZigZag[j];tableData[z]=readUint16();}}else
throw"DQT: invalid table spec";quantizationTables[quantizationTableSpec&15]=tableData;}
break;case 0xFFC0:case 0xFFC1:case 0xFFC2:readUint16();frame={};frame.extended=(fileMarker===0xFFC1);frame.progressive=(fileMarker===0xFFC2);frame.precision=data[offset++];frame.scanLines=readUint16();frame.samplesPerLine=readUint16();frame.components={};frame.componentsOrder=[];var componentsCount=data[offset++],componentId;var maxH=0,maxV=0;for(i=0;i<componentsCount;i++){componentId=data[offset];var h=data[offset+1]>>4;var v=data[offset+1]&15;var qId=data[offset+2];frame.componentsOrder.push(componentId);frame.components[componentId]={h:h,v:v,quantizationIdx:qId};offset+=3;}
prepareComponents(frame);frames.push(frame);break;case 0xFFC4:var huffmanLength=readUint16();for(i=2;i<huffmanLength;){var huffmanTableSpec=data[offset++];var codeLengths=new Uint8Array(16);var codeLengthSum=0;for(j=0;j<16;j++,offset++)
codeLengthSum+=(codeLengths[j]=data[offset]);var huffmanValues=new Uint8Array(codeLengthSum);for(j=0;j<codeLengthSum;j++,offset++)
huffmanValues[j]=data[offset];i+=17+codeLengthSum;((huffmanTableSpec>>4)===0?huffmanTablesDC:huffmanTablesAC)[huffmanTableSpec&15]=buildHuffmanTable(codeLengths,huffmanValues);}
break;case 0xFFDD:readUint16();resetInterval=readUint16();break;case 0xFFDA:var scanLength=readUint16();var selectorsCount=data[offset++];var components=[],component;for(i=0;i<selectorsCount;i++){component=frame.components[data[offset++]];var tableSpec=data[offset++];component.huffmanTableDC=huffmanTablesDC[tableSpec>>4];component.huffmanTableAC=huffmanTablesAC[tableSpec&15];components.push(component);}
var spectralStart=data[offset++];var spectralEnd=data[offset++];var successiveApproximation=data[offset++];var processed=decodeScan(data,offset,frame,components,resetInterval,spectralStart,spectralEnd,successiveApproximation>>4,successiveApproximation&15);offset+=processed;break;default:if(data[offset-3]==0xFF&&data[offset-2]>=0xC0&&data[offset-2]<=0xFE){offset-=3;break;}
throw"unknown JPEG marker "+fileMarker.toString(16);}
fileMarker=readUint16();}
if(frames.length!=1)
throw"only single frame JPEGs supported";for(var i=0;i<frames.length;i++){var cp=frames[i].components;for(var j in cp){cp[j].quantizationTable=quantizationTables[cp[j].quantizationIdx];delete cp[j].quantizationIdx;}}
this.width=frame.samplesPerLine;this.height=frame.scanLines;this.jfif=jfif;this.adobe=adobe;this.components=[];for(var i=0;i<frame.componentsOrder.length;i++){var component=frame.components[frame.componentsOrder[i]];this.components.push({lines:buildComponentData(frame,component),scaleX:component.h/frame.maxH,scaleY:component.v/frame.maxV});}},getData:function getData(width,height){var scaleX=this.width/width,scaleY=this.height/height;var component1,component2,component3,component4;var component1Line,component2Line,component3Line,component4Line;var x,y;var offset=0;var Y,Cb,Cr,K,C,M,Ye,R,G,B;var colorTransform;var dataLength=width*height*this.components.length;var data=new Uint8Array(dataLength);switch(this.components.length){case 1:component1=this.components[0];for(y=0;y<height;y++){component1Line=component1.lines[0|(y*component1.scaleY*scaleY)];for(x=0;x<width;x++){Y=component1Line[0|(x*component1.scaleX*scaleX)];data[offset++]=Y;}}
break;case 2:component1=this.components[0];component2=this.components[1];for(y=0;y<height;y++){component1Line=component1.lines[0|(y*component1.scaleY*scaleY)];component2Line=component2.lines[0|(y*component2.scaleY*scaleY)];for(x=0;x<width;x++){Y=component1Line[0|(x*component1.scaleX*scaleX)];data[offset++]=Y;Y=component2Line[0|(x*component2.scaleX*scaleX)];data[offset++]=Y;}}
break;case 3:colorTransform=true;if(this.adobe&&this.adobe.transformCode)
colorTransform=true;else if(typeof this.colorTransform!=='undefined')
colorTransform=!!this.colorTransform;component1=this.components[0];component2=this.components[1];component3=this.components[2];for(y=0;y<height;y++){component1Line=component1.lines[0|(y*component1.scaleY*scaleY)];component2Line=component2.lines[0|(y*component2.scaleY*scaleY)];component3Line=component3.lines[0|(y*component3.scaleY*scaleY)];for(x=0;x<width;x++){if(!colorTransform){R=component1Line[0|(x*component1.scaleX*scaleX)];G=component2Line[0|(x*component2.scaleX*scaleX)];B=component3Line[0|(x*component3.scaleX*scaleX)];}else{Y=component1Line[0|(x*component1.scaleX*scaleX)];Cb=component2Line[0|(x*component2.scaleX*scaleX)];Cr=component3Line[0|(x*component3.scaleX*scaleX)];R=clampTo8bit(Y+1.402*(Cr-128));G=clampTo8bit(Y-0.3441363*(Cb-128)-0.71413636*(Cr-128));B=clampTo8bit(Y+1.772*(Cb-128));}
data[offset++]=R;data[offset++]=G;data[offset++]=B;}}
break;case 4:if(!this.adobe)
throw'Unsupported color mode (4 components)';colorTransform=false;if(this.adobe&&this.adobe.transformCode)
colorTransform=true;else if(typeof this.colorTransform!=='undefined')
colorTransform=!!this.colorTransform;component1=this.components[0];component2=this.components[1];component3=this.components[2];component4=this.components[3];for(y=0;y<height;y++){component1Line=component1.lines[0|(y*component1.scaleY*scaleY)];component2Line=component2.lines[0|(y*component2.scaleY*scaleY)];component3Line=component3.lines[0|(y*component3.scaleY*scaleY)];component4Line=component4.lines[0|(y*component4.scaleY*scaleY)];for(x=0;x<width;x++){if(!colorTransform){C=component1Line[0|(x*component1.scaleX*scaleX)];M=component2Line[0|(x*component2.scaleX*scaleX)];Ye=component3Line[0|(x*component3.scaleX*scaleX)];K=component4Line[0|(x*component4.scaleX*scaleX)];}else{Y=component1Line[0|(x*component1.scaleX*scaleX)];Cb=component2Line[0|(x*component2.scaleX*scaleX)];Cr=component3Line[0|(x*component3.scaleX*scaleX)];K=component4Line[0|(x*component4.scaleX*scaleX)];C=255-clampTo8bit(Y+1.402*(Cr-128));M=255-clampTo8bit(Y-0.3441363*(Cb-128)-0.71413636*(Cr-128));Ye=255-clampTo8bit(Y+1.772*(Cb-128));}
data[offset++]=255-C;data[offset++]=255-M;data[offset++]=255-Ye;data[offset++]=255-K;}}
break;default:throw'Unsupported color mode';}
return data;},copyToImageData:function copyToImageData(imageData){var width=imageData.width,height=imageData.height;var imageDataArray=imageData.data;var data=this.getData(width,height);var i=0,j=0,x,y;var Y,K,C,M,R,G,B;switch(this.components.length){case 1:for(y=0;y<height;y++){for(x=0;x<width;x++){Y=data[i++];imageDataArray[j++]=Y;imageDataArray[j++]=Y;imageDataArray[j++]=Y;imageDataArray[j++]=255;}}
break;case 3:for(y=0;y<height;y++){for(x=0;x<width;x++){R=data[i++];G=data[i++];B=data[i++];imageDataArray[j++]=R;imageDataArray[j++]=G;imageDataArray[j++]=B;imageDataArray[j++]=255;}}
break;case 4:for(y=0;y<height;y++){for(x=0;x<width;x++){C=data[i++];M=data[i++];Y=data[i++];K=data[i++];R=255-clampTo8bit(C*(1-K/255)+K);G=255-clampTo8bit(M*(1-K/255)+K);B=255-clampTo8bit(Y*(1-K/255)+K);imageDataArray[j++]=R;imageDataArray[j++]=G;imageDataArray[j++]=B;imageDataArray[j++]=255;}}
break;default:throw'Unsupported color mode';}}};return constructor;})();module.exports=decode;function decode(jpegData){var arr=new Uint8Array(jpegData);var decoder=new JpegImage();decoder.parse(arr);var image={width:decoder.width,height:decoder.height,data:new Buffer(decoder.width*decoder.height*4)};decoder.copyToImageData(image);return image;}}).call(this,require("buffer").Buffer)},{"buffer":200}],280:[function(require,module,exports){(function(Buffer){var btoa=btoa||function(buf){return new Buffer(buf).toString('base64');};function JPEGEncoder(quality){var self=this;var fround=Math.round;var ffloor=Math.floor;var YTable=new Array(64);var UVTable=new Array(64);var fdtbl_Y=new Array(64);var fdtbl_UV=new Array(64);var YDC_HT;var UVDC_HT;var YAC_HT;var UVAC_HT;var bitcode=new Array(65535);var category=new Array(65535);var outputfDCTQuant=new Array(64);var DU=new Array(64);var byteout=[];var bytenew=0;var bytepos=7;var YDU=new Array(64);var UDU=new Array(64);var VDU=new Array(64);var clt=new Array(256);var RGB_YUV_TABLE=new Array(2048);var currentQuality;var ZigZag=[0,1,5,6,14,15,27,28,2,4,7,13,16,26,29,42,3,8,12,17,25,30,41,43,9,11,18,24,31,40,44,53,10,19,23,32,39,45,52,54,20,22,33,38,46,51,55,60,21,34,37,47,50,56,59,61,35,36,48,49,57,58,62,63];var std_dc_luminance_nrcodes=[0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0];var std_dc_luminance_values=[0,1,2,3,4,5,6,7,8,9,10,11];var std_ac_luminance_nrcodes=[0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,0x7d];var std_ac_luminance_values=[0x01,0x02,0x03,0x00,0x04,0x11,0x05,0x12,0x21,0x31,0x41,0x06,0x13,0x51,0x61,0x07,0x22,0x71,0x14,0x32,0x81,0x91,0xa1,0x08,0x23,0x42,0xb1,0xc1,0x15,0x52,0xd1,0xf0,0x24,0x33,0x62,0x72,0x82,0x09,0x0a,0x16,0x17,0x18,0x19,0x1a,0x25,0x26,0x27,0x28,0x29,0x2a,0x34,0x35,0x36,0x37,0x38,0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xe1,0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,0xf1,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,0xf9,0xfa];var std_dc_chrominance_nrcodes=[0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0];var std_dc_chrominance_values=[0,1,2,3,4,5,6,7,8,9,10,11];var std_ac_chrominance_nrcodes=[0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,0x77];var std_ac_chrominance_values=[0x00,0x01,0x02,0x03,0x11,0x04,0x05,0x21,0x31,0x06,0x12,0x41,0x51,0x07,0x61,0x71,0x13,0x22,0x32,0x81,0x08,0x14,0x42,0x91,0xa1,0xb1,0xc1,0x09,0x23,0x33,0x52,0xf0,0x15,0x62,0x72,0xd1,0x0a,0x16,0x24,0x34,0xe1,0x25,0xf1,0x17,0x18,0x19,0x1a,0x26,0x27,0x28,0x29,0x2a,0x35,0x36,0x37,0x38,0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,0xf9,0xfa];function initQuantTables(sf){var YQT=[16,11,10,16,24,40,51,61,12,12,14,19,26,58,60,55,14,13,16,24,40,57,69,56,14,17,22,29,51,87,80,62,18,22,37,56,68,109,103,77,24,35,55,64,81,104,113,92,49,64,78,87,103,121,120,101,72,92,95,98,112,100,103,99];for(var i=0;i<64;i++){var t=ffloor((YQT[i]*sf+50)/100);if(t<1){t=1;}else if(t>255){t=255;}
YTable[ZigZag[i]]=t;}
var UVQT=[17,18,24,47,99,99,99,99,18,21,26,66,99,99,99,99,24,26,56,99,99,99,99,99,47,66,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99];for(var j=0;j<64;j++){var u=ffloor((UVQT[j]*sf+50)/100);if(u<1){u=1;}else if(u>255){u=255;}
UVTable[ZigZag[j]]=u;}
var aasf=[1.0,1.387039845,1.306562965,1.175875602,1.0,0.785694958,0.541196100,0.275899379];var k=0;for(var row=0;row<8;row++)
{for(var col=0;col<8;col++)
{fdtbl_Y[k]=(1.0/(YTable[ZigZag[k]]*aasf[row]*aasf[col]*8.0));fdtbl_UV[k]=(1.0/(UVTable[ZigZag[k]]*aasf[row]*aasf[col]*8.0));k++;}}}
function computeHuffmanTbl(nrcodes,std_table){var codevalue=0;var pos_in_table=0;var HT=new Array();for(var k=1;k<=16;k++){for(var j=1;j<=nrcodes[k];j++){HT[std_table[pos_in_table]]=[];HT[std_table[pos_in_table]][0]=codevalue;HT[std_table[pos_in_table]][1]=k;pos_in_table++;codevalue++;}
codevalue*=2;}
return HT;}
function initHuffmanTbl()
{YDC_HT=computeHuffmanTbl(std_dc_luminance_nrcodes,std_dc_luminance_values);UVDC_HT=computeHuffmanTbl(std_dc_chrominance_nrcodes,std_dc_chrominance_values);YAC_HT=computeHuffmanTbl(std_ac_luminance_nrcodes,std_ac_luminance_values);UVAC_HT=computeHuffmanTbl(std_ac_chrominance_nrcodes,std_ac_chrominance_values);}
function initCategoryNumber()
{var nrlower=1;var nrupper=2;for(var cat=1;cat<=15;cat++){for(var nr=nrlower;nr<nrupper;nr++){category[32767+nr]=cat;bitcode[32767+nr]=[];bitcode[32767+nr][1]=cat;bitcode[32767+nr][0]=nr;}
for(var nrneg=-(nrupper-1);nrneg<=-nrlower;nrneg++){category[32767+nrneg]=cat;bitcode[32767+nrneg]=[];bitcode[32767+nrneg][1]=cat;bitcode[32767+nrneg][0]=nrupper-1+nrneg;}
nrlower<<=1;nrupper<<=1;}}
function initRGBYUVTable(){for(var i=0;i<256;i++){RGB_YUV_TABLE[i]=19595*i;RGB_YUV_TABLE[(i+256)>>0]=38470*i;RGB_YUV_TABLE[(i+512)>>0]=7471*i+0x8000;RGB_YUV_TABLE[(i+768)>>0]=-11059*i;RGB_YUV_TABLE[(i+1024)>>0]=-21709*i;RGB_YUV_TABLE[(i+1280)>>0]=32768*i+0x807FFF;RGB_YUV_TABLE[(i+1536)>>0]=-27439*i;RGB_YUV_TABLE[(i+1792)>>0]=-5329*i;}}
function writeBits(bs)
{var value=bs[0];var posval=bs[1]-1;while(posval>=0){if(value&(1<<posval)){bytenew|=(1<<bytepos);}
posval--;bytepos--;if(bytepos<0){if(bytenew==0xFF){writeByte(0xFF);writeByte(0);}
else{writeByte(bytenew);}
bytepos=7;bytenew=0;}}}
function writeByte(value)
{byteout.push(value);}
function writeWord(value)
{writeByte((value>>8)&0xFF);writeByte((value)&0xFF);}
function fDCTQuant(data,fdtbl)
{var d0,d1,d2,d3,d4,d5,d6,d7;var dataOff=0;var i;const I8=8;const I64=64;for(i=0;i<I8;++i)
{d0=data[dataOff];d1=data[dataOff+1];d2=data[dataOff+2];d3=data[dataOff+3];d4=data[dataOff+4];d5=data[dataOff+5];d6=data[dataOff+6];d7=data[dataOff+7];var tmp0=d0+d7;var tmp7=d0-d7;var tmp1=d1+d6;var tmp6=d1-d6;var tmp2=d2+d5;var tmp5=d2-d5;var tmp3=d3+d4;var tmp4=d3-d4;var tmp10=tmp0+tmp3;var tmp13=tmp0-tmp3;var tmp11=tmp1+tmp2;var tmp12=tmp1-tmp2;data[dataOff]=tmp10+tmp11;data[dataOff+4]=tmp10-tmp11;var z1=(tmp12+tmp13)*0.707106781;data[dataOff+2]=tmp13+z1;data[dataOff+6]=tmp13-z1;tmp10=tmp4+tmp5;tmp11=tmp5+tmp6;tmp12=tmp6+tmp7;var z5=(tmp10-tmp12)*0.382683433;var z2=0.541196100*tmp10+z5;var z4=1.306562965*tmp12+z5;var z3=tmp11*0.707106781;var z11=tmp7+z3;var z13=tmp7-z3;data[dataOff+5]=z13+z2;data[dataOff+3]=z13-z2;data[dataOff+1]=z11+z4;data[dataOff+7]=z11-z4;dataOff+=8;}
dataOff=0;for(i=0;i<I8;++i)
{d0=data[dataOff];d1=data[dataOff+8];d2=data[dataOff+16];d3=data[dataOff+24];d4=data[dataOff+32];d5=data[dataOff+40];d6=data[dataOff+48];d7=data[dataOff+56];var tmp0p2=d0+d7;var tmp7p2=d0-d7;var tmp1p2=d1+d6;var tmp6p2=d1-d6;var tmp2p2=d2+d5;var tmp5p2=d2-d5;var tmp3p2=d3+d4;var tmp4p2=d3-d4;var tmp10p2=tmp0p2+tmp3p2;var tmp13p2=tmp0p2-tmp3p2;var tmp11p2=tmp1p2+tmp2p2;var tmp12p2=tmp1p2-tmp2p2;data[dataOff]=tmp10p2+tmp11p2;data[dataOff+32]=tmp10p2-tmp11p2;var z1p2=(tmp12p2+tmp13p2)*0.707106781;data[dataOff+16]=tmp13p2+z1p2;data[dataOff+48]=tmp13p2-z1p2;tmp10p2=tmp4p2+tmp5p2;tmp11p2=tmp5p2+tmp6p2;tmp12p2=tmp6p2+tmp7p2;var z5p2=(tmp10p2-tmp12p2)*0.382683433;var z2p2=0.541196100*tmp10p2+z5p2;var z4p2=1.306562965*tmp12p2+z5p2;var z3p2=tmp11p2*0.707106781;var z11p2=tmp7p2+z3p2;var z13p2=tmp7p2-z3p2;data[dataOff+40]=z13p2+z2p2;data[dataOff+24]=z13p2-z2p2;data[dataOff+8]=z11p2+z4p2;data[dataOff+56]=z11p2-z4p2;dataOff++;}
var fDCTQuant;for(i=0;i<I64;++i)
{fDCTQuant=data[i]*fdtbl[i];outputfDCTQuant[i]=(fDCTQuant>0.0)?((fDCTQuant+0.5)|0):((fDCTQuant-0.5)|0);}
return outputfDCTQuant;}
function writeAPP0()
{writeWord(0xFFE0);writeWord(16);writeByte(0x4A);writeByte(0x46);writeByte(0x49);writeByte(0x46);writeByte(0);writeByte(1);writeByte(1);writeByte(0);writeWord(1);writeWord(1);writeByte(0);writeByte(0);}
function writeSOF0(width,height)
{writeWord(0xFFC0);writeWord(17);writeByte(8);writeWord(height);writeWord(width);writeByte(3);writeByte(1);writeByte(0x11);writeByte(0);writeByte(2);writeByte(0x11);writeByte(1);writeByte(3);writeByte(0x11);writeByte(1);}
function writeDQT()
{writeWord(0xFFDB);writeWord(132);writeByte(0);for(var i=0;i<64;i++){writeByte(YTable[i]);}
writeByte(1);for(var j=0;j<64;j++){writeByte(UVTable[j]);}}
function writeDHT()
{writeWord(0xFFC4);writeWord(0x01A2);writeByte(0);for(var i=0;i<16;i++){writeByte(std_dc_luminance_nrcodes[i+1]);}
for(var j=0;j<=11;j++){writeByte(std_dc_luminance_values[j]);}
writeByte(0x10);for(var k=0;k<16;k++){writeByte(std_ac_luminance_nrcodes[k+1]);}
for(var l=0;l<=161;l++){writeByte(std_ac_luminance_values[l]);}
writeByte(1);for(var m=0;m<16;m++){writeByte(std_dc_chrominance_nrcodes[m+1]);}
for(var n=0;n<=11;n++){writeByte(std_dc_chrominance_values[n]);}
writeByte(0x11);for(var o=0;o<16;o++){writeByte(std_ac_chrominance_nrcodes[o+1]);}
for(var p=0;p<=161;p++){writeByte(std_ac_chrominance_values[p]);}}
function writeSOS()
{writeWord(0xFFDA);writeWord(12);writeByte(3);writeByte(1);writeByte(0);writeByte(2);writeByte(0x11);writeByte(3);writeByte(0x11);writeByte(0);writeByte(0x3f);writeByte(0);}
function processDU(CDU,fdtbl,DC,HTDC,HTAC){var EOB=HTAC[0x00];var M16zeroes=HTAC[0xF0];var pos;const I16=16;const I63=63;const I64=64;var DU_DCT=fDCTQuant(CDU,fdtbl);for(var j=0;j<I64;++j){DU[ZigZag[j]]=DU_DCT[j];}
var Diff=DU[0]-DC;DC=DU[0];if(Diff==0){writeBits(HTDC[0]);}else{pos=32767+Diff;writeBits(HTDC[category[pos]]);writeBits(bitcode[pos]);}
var end0pos=63;for(;(end0pos>0)&&(DU[end0pos]==0);end0pos--){};if(end0pos==0){writeBits(EOB);return DC;}
var i=1;var lng;while(i<=end0pos){var startpos=i;for(;(DU[i]==0)&&(i<=end0pos);++i){}
var nrzeroes=i-startpos;if(nrzeroes>=I16){lng=nrzeroes>>4;for(var nrmarker=1;nrmarker<=lng;++nrmarker)
writeBits(M16zeroes);nrzeroes=nrzeroes&0xF;}
pos=32767+DU[i];writeBits(HTAC[(nrzeroes<<4)+category[pos]]);writeBits(bitcode[pos]);i++;}
if(end0pos!=I63){writeBits(EOB);}
return DC;}
function initCharLookupTable(){var sfcc=String.fromCharCode;for(var i=0;i<256;i++){clt[i]=sfcc(i);}}
this.encode=function(image,quality)
{var time_start=new Date().getTime();if(quality)setQuality(quality);byteout=new Array();bytenew=0;bytepos=7;writeWord(0xFFD8);writeAPP0();writeDQT();writeSOF0(image.width,image.height);writeDHT();writeSOS();var DCY=0;var DCU=0;var DCV=0;bytenew=0;bytepos=7;this.encode.displayName="_encode_";var imageData=image.data;var width=image.width;var height=image.height;var quadWidth=width*4;var tripleWidth=width*3;var x,y=0;var r,g,b;var start,p,col,row,pos;while(y<height){x=0;while(x<quadWidth){start=quadWidth*y+x;p=start;col=-1;row=0;for(pos=0;pos<64;pos++){row=pos>>3;col=(pos&7)*4;p=start+(row*quadWidth)+col;if(y+row>=height){p-=(quadWidth*(y+1+row-height));}
if(x+col>=quadWidth){p-=((x+col)-quadWidth+4)}
r=imageData[p++];g=imageData[p++];b=imageData[p++];YDU[pos]=((RGB_YUV_TABLE[r]+RGB_YUV_TABLE[(g+256)>>0]+RGB_YUV_TABLE[(b+512)>>0])>>16)-128;UDU[pos]=((RGB_YUV_TABLE[(r+768)>>0]+RGB_YUV_TABLE[(g+1024)>>0]+RGB_YUV_TABLE[(b+1280)>>0])>>16)-128;VDU[pos]=((RGB_YUV_TABLE[(r+1280)>>0]+RGB_YUV_TABLE[(g+1536)>>0]+RGB_YUV_TABLE[(b+1792)>>0])>>16)-128;}
DCY=processDU(YDU,fdtbl_Y,DCY,YDC_HT,YAC_HT);DCU=processDU(UDU,fdtbl_UV,DCU,UVDC_HT,UVAC_HT);DCV=processDU(VDU,fdtbl_UV,DCV,UVDC_HT,UVAC_HT);x+=32;}
y+=8;}
if(bytepos>=0){var fillbits=[];fillbits[1]=bytepos+1;fillbits[0]=(1<<(bytepos+1))-1;writeBits(fillbits);}
writeWord(0xFFD9);return new Buffer(byteout);var jpegDataUri='data:image/jpeg;base64,'+btoa(byteout.join(''));byteout=[];var duration=new Date().getTime()-time_start;return jpegDataUri}
function setQuality(quality){if(quality<=0){quality=1;}
if(quality>100){quality=100;}
if(currentQuality==quality)return
var sf=0;if(quality<50){sf=Math.floor(5000/quality);}else{sf=Math.floor(200-quality*2);}
initQuantTables(sf);currentQuality=quality;}
function init(){var time_start=new Date().getTime();if(!quality)quality=50;initCharLookupTable()
initHuffmanTbl();initCategoryNumber();initRGBYUVTable();setQuality(quality);var duration=new Date().getTime()-time_start;}
init();};module.exports=encode;function encode(imgData,qu){if(typeof qu==='undefined')qu=50;var encoder=new JPEGEncoder(qu);var data=encoder.encode(imgData,qu);return{data:data,width:imgData.width,height:imgData.height};}
function getImageDataFromImage(idOrElement){var theImg=(typeof(idOrElement)=='string')?document.getElementById(idOrElement):idOrElement;var cvs=document.createElement('canvas');cvs.width=theImg.width;cvs.height=theImg.height;var ctx=cvs.getContext("2d");ctx.drawImage(theImg,0,0);return(ctx.getImageData(0,0,cvs.width,cvs.height));}}).call(this,require("buffer").Buffer)},{"buffer":200}],281:[function(require,module,exports){(function(global){;(function(){var block={newline:/^\n+/,code:/^( {4}[^\n]+\n*)+/,fences:noop,hr:/^( *[-*_]){3,} *(?:\n+|$)/,heading:/^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/,nptable:noop,lheading:/^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/,blockquote:/^( *>[^\n]+(\n(?!def)[^\n]+)*\n*)+/,list:/^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,html:/^ *(?:comment *(?:\n|\s*$)|closed *(?:\n{2,}|\s*$)|closing *(?:\n{2,}|\s*$))/,def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/,table:noop,paragraph:/^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/,text:/^[^\n]+/};block.bullet=/(?:[*+-]|\d+\.)/;block.item=/^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/;block.item=replace(block.item,'gm')
(/bull/g,block.bullet)
();block.list=replace(block.list)
(/bull/g,block.bullet)
('hr','\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))')
('def','\\n+(?='+block.def.source+')')
();block.blockquote=replace(block.blockquote)
('def',block.def)
();block._tag='(?!(?:'
+'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code'
+'|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo'
+'|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b';block.html=replace(block.html)
('comment',/<!--[\s\S]*?-->/)
('closed',/<(tag)[\s\S]+?<\/\1>/)
('closing',/<tag(?:"[^"]*"|'[^']*'|[^'">])*?>/)
(/tag/g,block._tag)
();block.paragraph=replace(block.paragraph)
('hr',block.hr)
('heading',block.heading)
('lheading',block.lheading)
('blockquote',block.blockquote)
('tag','<'+block._tag)
('def',block.def)
();block.normal=merge({},block);block.gfm=merge({},block.normal,{fences:/^ *(`{3,}|~{3,})[ \.]*(\S+)? *\n([\s\S]*?)\s*\1 *(?:\n+|$)/,paragraph:/^/,heading:/^ *(#{1,6}) +([^\n]+?) *#* *(?:\n+|$)/});block.gfm.paragraph=replace(block.paragraph)
('(?!','(?!'
+block.gfm.fences.source.replace('\\1','\\2')+'|'
+block.list.source.replace('\\1','\\3')+'|')
();block.tables=merge({},block.gfm,{nptable:/^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/,table:/^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/});function Lexer(options){this.tokens=[];this.tokens.links={};this.options=options||marked.defaults;this.rules=block.normal;if(this.options.gfm){if(this.options.tables){this.rules=block.tables;}else{this.rules=block.gfm;}}}
Lexer.rules=block;Lexer.lex=function(src,options){var lexer=new Lexer(options);return lexer.lex(src);};Lexer.prototype.lex=function(src){src=src.replace(/\r\n|\r/g,'\n').replace(/\t/g,'    ').replace(/\u00a0/g,' ').replace(/\u2424/g,'\n');return this.token(src,true);};Lexer.prototype.token=function(src,top,bq){var src=src.replace(/^ +$/gm,''),next,loose,cap,bull,b,item,space,i,l;while(src){if(cap=this.rules.newline.exec(src)){src=src.substring(cap[0].length);if(cap[0].length>1){this.tokens.push({type:'space'});}}
if(cap=this.rules.code.exec(src)){src=src.substring(cap[0].length);cap=cap[0].replace(/^ {4}/gm,'');this.tokens.push({type:'code',text:!this.options.pedantic?cap.replace(/\n+$/,''):cap});continue;}
if(cap=this.rules.fences.exec(src)){src=src.substring(cap[0].length);this.tokens.push({type:'code',lang:cap[2],text:cap[3]||''});continue;}
if(cap=this.rules.heading.exec(src)){src=src.substring(cap[0].length);this.tokens.push({type:'heading',depth:cap[1].length,text:cap[2]});continue;}
if(top&&(cap=this.rules.nptable.exec(src))){src=src.substring(cap[0].length);item={type:'table',header:cap[1].replace(/^ *| *\| *$/g,'').split(/ *\| */),align:cap[2].replace(/^ *|\| *$/g,'').split(/ *\| */),cells:cap[3].replace(/\n$/,'').split('\n')};for(i=0;i<item.align.length;i++){if(/^ *-+: *$/.test(item.align[i])){item.align[i]='right';}else if(/^ *:-+: *$/.test(item.align[i])){item.align[i]='center';}else if(/^ *:-+ *$/.test(item.align[i])){item.align[i]='left';}else{item.align[i]=null;}}
for(i=0;i<item.cells.length;i++){item.cells[i]=item.cells[i].split(/ *\| */);}
this.tokens.push(item);continue;}
if(cap=this.rules.lheading.exec(src)){src=src.substring(cap[0].length);this.tokens.push({type:'heading',depth:cap[2]==='='?1:2,text:cap[1]});continue;}
if(cap=this.rules.hr.exec(src)){src=src.substring(cap[0].length);this.tokens.push({type:'hr'});continue;}
if(cap=this.rules.blockquote.exec(src)){src=src.substring(cap[0].length);this.tokens.push({type:'blockquote_start'});cap=cap[0].replace(/^ *> ?/gm,'');this.token(cap,top,true);this.tokens.push({type:'blockquote_end'});continue;}
if(cap=this.rules.list.exec(src)){src=src.substring(cap[0].length);bull=cap[2];this.tokens.push({type:'list_start',ordered:bull.length>1});cap=cap[0].match(this.rules.item);next=false;l=cap.length;i=0;for(;i<l;i++){item=cap[i];space=item.length;item=item.replace(/^ *([*+-]|\d+\.) +/,'');if(~item.indexOf('\n ')){space-=item.length;item=!this.options.pedantic?item.replace(new RegExp('^ {1,'+space+'}','gm'),''):item.replace(/^ {1,4}/gm,'');}
if(this.options.smartLists&&i!==l-1){b=block.bullet.exec(cap[i+1])[0];if(bull!==b&&!(bull.length>1&&b.length>1)){src=cap.slice(i+1).join('\n')+src;i=l-1;}}
loose=next||/\n\n(?!\s*$)/.test(item);if(i!==l-1){next=item.charAt(item.length-1)==='\n';if(!loose)loose=next;}
this.tokens.push({type:loose?'loose_item_start':'list_item_start'});this.token(item,false,bq);this.tokens.push({type:'list_item_end'});}
this.tokens.push({type:'list_end'});continue;}
if(cap=this.rules.html.exec(src)){src=src.substring(cap[0].length);this.tokens.push({type:this.options.sanitize?'paragraph':'html',pre:!this.options.sanitizer&&(cap[1]==='pre'||cap[1]==='script'||cap[1]==='style'),text:cap[0]});continue;}
if((!bq&&top)&&(cap=this.rules.def.exec(src))){src=src.substring(cap[0].length);this.tokens.links[cap[1].toLowerCase()]={href:cap[2],title:cap[3]};continue;}
if(top&&(cap=this.rules.table.exec(src))){src=src.substring(cap[0].length);item={type:'table',header:cap[1].replace(/^ *| *\| *$/g,'').split(/ *\| */),align:cap[2].replace(/^ *|\| *$/g,'').split(/ *\| */),cells:cap[3].replace(/(?: *\| *)?\n$/,'').split('\n')};for(i=0;i<item.align.length;i++){if(/^ *-+: *$/.test(item.align[i])){item.align[i]='right';}else if(/^ *:-+: *$/.test(item.align[i])){item.align[i]='center';}else if(/^ *:-+ *$/.test(item.align[i])){item.align[i]='left';}else{item.align[i]=null;}}
for(i=0;i<item.cells.length;i++){item.cells[i]=item.cells[i].replace(/^ *\| *| *\| *$/g,'').split(/ *\| */);}
this.tokens.push(item);continue;}
if(top&&(cap=this.rules.paragraph.exec(src))){src=src.substring(cap[0].length);this.tokens.push({type:'paragraph',text:cap[1].charAt(cap[1].length-1)==='\n'?cap[1].slice(0,-1):cap[1]});continue;}
if(cap=this.rules.text.exec(src)){src=src.substring(cap[0].length);this.tokens.push({type:'text',text:cap[0]});continue;}
if(src){throw new
Error('Infinite loop on byte: '+src.charCodeAt(0));}}
return this.tokens;};var inline={escape:/^\\([\\`*{}\[\]()#+\-.!_>])/,autolink:/^<([^ >]+(@|:\/)[^ >]+)>/,url:noop,tag:/^<!--[\s\S]*?-->|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/,link:/^!?\[(inside)\]\(href\)/,reflink:/^!?\[(inside)\]\s*\[([^\]]*)\]/,nolink:/^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/,strong:/^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/,em:/^\b_((?:[^_]|__)+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/,code:/^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/,br:/^ {2,}\n(?!\s*$)/,del:noop,text:/^[\s\S]+?(?=[\\<!\[_*`]| {2,}\n|$)/};inline._inside=/(?:\[[^\]]*\]|[^\[\]]|\](?=[^\[]*\]))*/;inline._href=/\s*<?([\s\S]*?)>?(?:\s+['"]([\s\S]*?)['"])?\s*/;inline.link=replace(inline.link)
('inside',inline._inside)
('href',inline._href)
();inline.reflink=replace(inline.reflink)
('inside',inline._inside)
();inline.normal=merge({},inline);inline.pedantic=merge({},inline.normal,{strong:/^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,em:/^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/});inline.gfm=merge({},inline.normal,{escape:replace(inline.escape)('])','~|])')(),url:/^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,del:/^~~(?=\S)([\s\S]*?\S)~~/,text:replace(inline.text)
(']|','~]|')
('|','|https?://|')
()});inline.breaks=merge({},inline.gfm,{br:replace(inline.br)('{2,}','*')(),text:replace(inline.gfm.text)('{2,}','*')()});function InlineLexer(links,options){this.options=options||marked.defaults;this.links=links;this.rules=inline.normal;this.renderer=this.options.renderer||new Renderer;this.renderer.options=this.options;if(!this.links){throw new
Error('Tokens array requires a `links` property.');}
if(this.options.gfm){if(this.options.breaks){this.rules=inline.breaks;}else{this.rules=inline.gfm;}}else if(this.options.pedantic){this.rules=inline.pedantic;}}
InlineLexer.rules=inline;InlineLexer.output=function(src,links,options){var inline=new InlineLexer(links,options);return inline.output(src);};InlineLexer.prototype.output=function(src){var out='',link,text,href,cap;while(src){if(cap=this.rules.escape.exec(src)){src=src.substring(cap[0].length);out+=cap[1];continue;}
if(cap=this.rules.autolink.exec(src)){src=src.substring(cap[0].length);if(cap[2]==='@'){text=cap[1].charAt(6)===':'?this.mangle(cap[1].substring(7)):this.mangle(cap[1]);href=this.mangle('mailto:')+text;}else{text=escape(cap[1]);href=text;}
out+=this.renderer.link(href,null,text);continue;}
if(!this.inLink&&(cap=this.rules.url.exec(src))){src=src.substring(cap[0].length);text=escape(cap[1]);href=text;out+=this.renderer.link(href,null,text);continue;}
if(cap=this.rules.tag.exec(src)){if(!this.inLink&&/^<a /i.test(cap[0])){this.inLink=true;}else if(this.inLink&&/^<\/a>/i.test(cap[0])){this.inLink=false;}
src=src.substring(cap[0].length);out+=this.options.sanitize?this.options.sanitizer?this.options.sanitizer(cap[0]):escape(cap[0]):cap[0]
continue;}
if(cap=this.rules.link.exec(src)){src=src.substring(cap[0].length);this.inLink=true;out+=this.outputLink(cap,{href:cap[2],title:cap[3]});this.inLink=false;continue;}
if((cap=this.rules.reflink.exec(src))||(cap=this.rules.nolink.exec(src))){src=src.substring(cap[0].length);link=(cap[2]||cap[1]).replace(/\s+/g,' ');link=this.links[link.toLowerCase()];if(!link||!link.href){out+=cap[0].charAt(0);src=cap[0].substring(1)+src;continue;}
this.inLink=true;out+=this.outputLink(cap,link);this.inLink=false;continue;}
if(cap=this.rules.strong.exec(src)){src=src.substring(cap[0].length);out+=this.renderer.strong(this.output(cap[2]||cap[1]));continue;}
if(cap=this.rules.em.exec(src)){src=src.substring(cap[0].length);out+=this.renderer.em(this.output(cap[2]||cap[1]));continue;}
if(cap=this.rules.code.exec(src)){src=src.substring(cap[0].length);out+=this.renderer.codespan(escape(cap[2],true));continue;}
if(cap=this.rules.br.exec(src)){src=src.substring(cap[0].length);out+=this.renderer.br();continue;}
if(cap=this.rules.del.exec(src)){src=src.substring(cap[0].length);out+=this.renderer.del(this.output(cap[1]));continue;}
if(cap=this.rules.text.exec(src)){src=src.substring(cap[0].length);out+=this.renderer.text(escape(this.smartypants(cap[0])));continue;}
if(src){throw new
Error('Infinite loop on byte: '+src.charCodeAt(0));}}
return out;};InlineLexer.prototype.outputLink=function(cap,link){var href=escape(link.href),title=link.title?escape(link.title):null;return cap[0].charAt(0)!=='!'?this.renderer.link(href,title,this.output(cap[1])):this.renderer.image(href,title,escape(cap[1]));};InlineLexer.prototype.smartypants=function(text){if(!this.options.smartypants)return text;return text.replace(/---/g,'\u2014').replace(/--/g,'\u2013').replace(/(^|[-\u2014/(\[{"\s])'/g,'$1\u2018').replace(/'/g,'\u2019').replace(/(^|[-\u2014/(\[{\u2018\s])"/g,'$1\u201c').replace(/"/g,'\u201d').replace(/\.{3}/g,'\u2026');};InlineLexer.prototype.mangle=function(text){if(!this.options.mangle)return text;var out='',l=text.length,i=0,ch;for(;i<l;i++){ch=text.charCodeAt(i);if(Math.random()>0.5){ch='x'+ch.toString(16);}
out+='&#'+ch+';';}
return out;};function Renderer(options){this.options=options||{};}
Renderer.prototype.code=function(code,lang,escaped){if(this.options.highlight){var out=this.options.highlight(code,lang);if(out!=null&&out!==code){escaped=true;code=out;}}
if(!lang){return'<pre><code>'
+(escaped?code:escape(code,true))
+'\n</code></pre>';}
return'<pre><code class="'
+this.options.langPrefix
+escape(lang,true)
+'">'
+(escaped?code:escape(code,true))
+'\n</code></pre>\n';};Renderer.prototype.blockquote=function(quote){return'<blockquote>\n'+quote+'</blockquote>\n';};Renderer.prototype.html=function(html){return html;};Renderer.prototype.heading=function(text,level,raw){return'<h'
+level
+' id="'
+this.options.headerPrefix
+raw.toLowerCase().replace(/[^\w]+/g,'-')
+'">'
+text
+'</h'
+level
+'>\n';};Renderer.prototype.hr=function(){return this.options.xhtml?'<hr/>\n':'<hr>\n';};Renderer.prototype.list=function(body,ordered){var type=ordered?'ol':'ul';return'<'+type+'>\n'+body+'</'+type+'>\n';};Renderer.prototype.listitem=function(text){return'<li>'+text+'</li>\n';};Renderer.prototype.paragraph=function(text){return'<p>'+text+'</p>\n';};Renderer.prototype.table=function(header,body){return'<table>\n'
+'<thead>\n'
+header
+'</thead>\n'
+'<tbody>\n'
+body
+'</tbody>\n'
+'</table>\n';};Renderer.prototype.tablerow=function(content){return'<tr>\n'+content+'</tr>\n';};Renderer.prototype.tablecell=function(content,flags){var type=flags.header?'th':'td';var tag=flags.align?'<'+type+' style="text-align:'+flags.align+'">':'<'+type+'>';return tag+content+'</'+type+'>\n';};Renderer.prototype.strong=function(text){return'<strong>'+text+'</strong>';};Renderer.prototype.em=function(text){return'<em>'+text+'</em>';};Renderer.prototype.codespan=function(text){return'<code>'+text+'</code>';};Renderer.prototype.br=function(){return this.options.xhtml?'<br/>':'<br>';};Renderer.prototype.del=function(text){return'<del>'+text+'</del>';};Renderer.prototype.link=function(href,title,text){if(this.options.sanitize){try{var prot=decodeURIComponent(unescape(href)).replace(/[^\w:]/g,'').toLowerCase();}catch(e){return'';}
if(prot.indexOf('javascript:')===0||prot.indexOf('vbscript:')===0){return'';}}
var out='<a href="'+href+'"';if(title){out+=' title="'+title+'"';}
out+='>'+text+'</a>';return out;};Renderer.prototype.image=function(href,title,text){var out='<img src="'+href+'" alt="'+text+'"';if(title){out+=' title="'+title+'"';}
out+=this.options.xhtml?'/>':'>';return out;};Renderer.prototype.text=function(text){return text;};function Parser(options){this.tokens=[];this.token=null;this.options=options||marked.defaults;this.options.renderer=this.options.renderer||new Renderer;this.renderer=this.options.renderer;this.renderer.options=this.options;}
Parser.parse=function(src,options,renderer){var parser=new Parser(options,renderer);return parser.parse(src);};Parser.prototype.parse=function(src){this.inline=new InlineLexer(src.links,this.options,this.renderer);this.tokens=src.reverse();var out='';while(this.next()){out+=this.tok();}
return out;};Parser.prototype.next=function(){return this.token=this.tokens.pop();};Parser.prototype.peek=function(){return this.tokens[this.tokens.length-1]||0;};Parser.prototype.parseText=function(){var body=this.token.text;while(this.peek().type==='text'){body+='\n'+this.next().text;}
return this.inline.output(body);};Parser.prototype.tok=function(){switch(this.token.type){case'space':{return'';}
case'hr':{return this.renderer.hr();}
case'heading':{return this.renderer.heading(this.inline.output(this.token.text),this.token.depth,this.token.text);}
case'code':{return this.renderer.code(this.token.text,this.token.lang,this.token.escaped);}
case'table':{var header='',body='',i,row,cell,flags,j;cell='';for(i=0;i<this.token.header.length;i++){flags={header:true,align:this.token.align[i]};cell+=this.renderer.tablecell(this.inline.output(this.token.header[i]),{header:true,align:this.token.align[i]});}
header+=this.renderer.tablerow(cell);for(i=0;i<this.token.cells.length;i++){row=this.token.cells[i];cell='';for(j=0;j<row.length;j++){cell+=this.renderer.tablecell(this.inline.output(row[j]),{header:false,align:this.token.align[j]});}
body+=this.renderer.tablerow(cell);}
return this.renderer.table(header,body);}
case'blockquote_start':{var body='';while(this.next().type!=='blockquote_end'){body+=this.tok();}
return this.renderer.blockquote(body);}
case'list_start':{var body='',ordered=this.token.ordered;while(this.next().type!=='list_end'){body+=this.tok();}
return this.renderer.list(body,ordered);}
case'list_item_start':{var body='';while(this.next().type!=='list_item_end'){body+=this.token.type==='text'?this.parseText():this.tok();}
return this.renderer.listitem(body);}
case'loose_item_start':{var body='';while(this.next().type!=='list_item_end'){body+=this.tok();}
return this.renderer.listitem(body);}
case'html':{var html=!this.token.pre&&!this.options.pedantic?this.inline.output(this.token.text):this.token.text;return this.renderer.html(html);}
case'paragraph':{return this.renderer.paragraph(this.inline.output(this.token.text));}
case'text':{return this.renderer.paragraph(this.parseText());}}};function escape(html,encode){return html.replace(!encode?/&(?!#?\w+;)/g:/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#39;');}
function unescape(html){return html.replace(/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/g,function(_,n){n=n.toLowerCase();if(n==='colon')return':';if(n.charAt(0)==='#'){return n.charAt(1)==='x'?String.fromCharCode(parseInt(n.substring(2),16)):String.fromCharCode(+n.substring(1));}
return'';});}
function replace(regex,opt){regex=regex.source;opt=opt||'';return function self(name,val){if(!name)return new RegExp(regex,opt);val=val.source||val;val=val.replace(/(^|[^\[])\^/g,'$1');regex=regex.replace(name,val);return self;};}
function noop(){}
noop.exec=noop;function merge(obj){var i=1,target,key;for(;i<arguments.length;i++){target=arguments[i];for(key in target){if(Object.prototype.hasOwnProperty.call(target,key)){obj[key]=target[key];}}}
return obj;}
function marked(src,opt,callback){if(callback||typeof opt==='function'){if(!callback){callback=opt;opt=null;}
opt=merge({},marked.defaults,opt||{});var highlight=opt.highlight,tokens,pending,i=0;try{tokens=Lexer.lex(src,opt)}catch(e){return callback(e);}
pending=tokens.length;var done=function(err){if(err){opt.highlight=highlight;return callback(err);}
var out;try{out=Parser.parse(tokens,opt);}catch(e){err=e;}
opt.highlight=highlight;return err?callback(err):callback(null,out);};if(!highlight||highlight.length<3){return done();}
delete opt.highlight;if(!pending)return done();for(;i<tokens.length;i++){(function(token){if(token.type!=='code'){return--pending||done();}
return highlight(token.text,token.lang,function(err,code){if(err)return done(err);if(code==null||code===token.text){return--pending||done();}
token.text=code;token.escaped=true;--pending||done();});})(tokens[i]);}
return;}
try{if(opt)opt=merge({},marked.defaults,opt);return Parser.parse(Lexer.lex(src,opt),opt);}catch(e){e.message+='\nPlease report this to https://github.com/chjj/marked.';if((opt||marked.defaults).silent){return'<p>An error occured:</p><pre>'
+escape(e.message+'',true)
+'</pre>';}
throw e;}}
marked.options=marked.setOptions=function(opt){merge(marked.defaults,opt);return marked;};marked.defaults={gfm:true,tables:true,breaks:false,pedantic:false,sanitize:false,sanitizer:null,mangle:true,smartLists:false,silent:false,highlight:null,langPrefix:'lang-',smartypants:false,headerPrefix:'',renderer:new Renderer,xhtml:false};marked.Parser=Parser;marked.parser=Parser.parse;marked.Renderer=Renderer;marked.Lexer=Lexer;marked.lexer=Lexer.lex;marked.InlineLexer=InlineLexer;marked.inlineLexer=InlineLexer.output;marked.parse=marked;if(typeof module!=='undefined'&&typeof exports==='object'){module.exports=marked;}else if(typeof define==='function'&&define.amd){define(function(){return marked;});}else{this.marked=marked;}}).call(function(){return this||(typeof window!=='undefined'?window:global);}());}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],282:[function(require,module,exports){var s=1000;var m=s*60;var h=m*60;var d=h*24;var y=d*365.25;module.exports=function(val,options){options=options||{};if('string'==typeof val)return parse(val);return options.long?long(val):short(val);};function parse(str){str=''+str;if(str.length>10000)return;var match=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str);if(!match)return;var n=parseFloat(match[1]);var type=(match[2]||'ms').toLowerCase();switch(type){case'years':case'year':case'yrs':case'yr':case'y':return n*y;case'days':case'day':case'd':return n*d;case'hours':case'hour':case'hrs':case'hr':case'h':return n*h;case'minutes':case'minute':case'mins':case'min':case'm':return n*m;case'seconds':case'second':case'secs':case'sec':case's':return n*s;case'milliseconds':case'millisecond':case'msecs':case'msec':case'ms':return n;}}
function short(ms){if(ms>=d)return Math.round(ms/d)+'d';if(ms>=h)return Math.round(ms/h)+'h';if(ms>=m)return Math.round(ms/m)+'m';if(ms>=s)return Math.round(ms/s)+'s';return ms+'ms';}
function long(ms){return plural(ms,d,'day')||plural(ms,h,'hour')||plural(ms,m,'minute')||plural(ms,s,'second')||ms+' ms';}
function plural(ms,n,name){if(ms<n)return;if(ms<n*1.5)return Math.floor(ms/n)+' '+name;return Math.ceil(ms/n)+' '+name+'s';}},{}],283:[function(require,module,exports){(function(Buffer){'use strict';const jpeg=require('jpeg-js');function getPixel(x,y,channel,width,buff){return buff[(x+y*width)*4+channel];}
function convertPixelsToHistogram(img){const createHistogramArray=function(){const ret=new Array(256);for(let i=0;i<ret.length;i++){ret[i]=0;}
return ret;};const width=img.width;const height=img.height;const histograms=[createHistogramArray(),createHistogramArray(),createHistogramArray()];for(let channel=0;channel<histograms.length;channel++){for(let i=0;i<width;i++){for(let j=0;j<height;j++){const pixelValue=getPixel(i,j,channel,width,img.data);if(getPixel(i,j,0,width,img.data)<249&&getPixel(i,j,1,width,img.data)<249&&getPixel(i,j,2,width,img.data)<249){histograms[channel][pixelValue]++;}}}}
return histograms;}
function synthesizeWhiteFrame(frames){const firstImageData=jpeg.decode(frames[0].getImage());const width=firstImageData.width;const height=firstImageData.height;const frameData=new Buffer(width*height*4);let i=0;while(i<frameData.length){frameData[i++]=0xFF;frameData[i++]=0xFF;frameData[i++]=0xFF;frameData[i++]=0xFF;}
var jpegImageData=jpeg.encode({data:frameData,width:width,height:height});return jpegImageData.data;}
const screenshotTraceCategory='disabled-by-default-devtools.screenshot';function extractFramesFromTimeline(timeline){let trace;trace=typeof timeline==='string'?fs.readFileSync(timeline,'utf-8'):timeline;try{trace=typeof trace==='string'?JSON.parse(trace):trace;}catch(e){throw new Error('Speedline: Invalid JSON'+e.message);}
let events=trace.traceEvents||trace;events=events.sort((a,b)=>a.ts-b.ts).filter(e=>e.ts!==0);const startTs=events[0].ts/1000;const endTs=events[events.length-1].ts/1000;const rawScreenshots=events.filter(e=>e.cat.includes(screenshotTraceCategory));const frames=rawScreenshots.map(function(evt){const base64img=evt.args&&evt.args.snapshot;const timestamp=evt.ts/1000;const imgBuff=new Buffer(base64img,'base64');return frame(imgBuff,timestamp);});if(frames.length===0){return Promise.reject(new Error('No screenshots found in trace'));}
const fakeWhiteFrame=frame(synthesizeWhiteFrame(frames),startTs);frames.unshift(fakeWhiteFrame);const data={startTs,endTs,frames:frames};return Promise.resolve(data);}
function frame(imgBuff,ts){let _histogram=null;let _progress=null;let _perceptualProgress=null;let _parsedImage=null;return{getHistogram:function(){if(_histogram){return _histogram;}
const pixels=this.getParsedImage();_histogram=convertPixelsToHistogram(pixels);return _histogram;},getTimeStamp:function(){return ts;},setProgress:function(progress){_progress=progress;},setPerceptualProgress:function(progress){_perceptualProgress=progress;},getImage:function(){return imgBuff;},getParsedImage:function(){if(!_parsedImage){_parsedImage=jpeg.decode(imgBuff);}
return _parsedImage;},getProgress:function(){return _progress;},getPerceptualProgress:function(){return _perceptualProgress;}};}
module.exports={extractFramesFromTimeline,create:frame};}).call(this,require("buffer").Buffer)},{"buffer":200,"jpeg-js":278}],284:[function(require,module,exports){'use strict';const frame=require('./frame');const speedIndex=require('./speed-index');function calculateValues(frames,data){const indexes=speedIndex.calculateSpeedIndexes(frames,data);const duration=Math.floor(data.endTs-data.startTs);const first=Math.floor(indexes.firstPaintTs-data.startTs);const complete=Math.floor(indexes.visuallyCompleteTs-data.startTs);return{beginning:data.startTs,end:data.endTs,frames,first,complete,duration,speedIndex:indexes.speedIndex,perceptualSpeedIndex:indexes.perceptualSpeedIndex};}
module.exports=function(timeline){return frame.extractFramesFromTimeline(timeline).then(function(data){const frames=data.frames;speedIndex.calculateVisualProgress(frames);speedIndex.calculatePerceptualProgress(frames);return calculateValues(frames,data);});};},{"./frame":283,"./speed-index":285}],285:[function(require,module,exports){'use strict';const imageSSIM=require('image-ssim');function calculateFrameProgress(current,initial,target){let total=0;let match=0;const currentHist=current.getHistogram();const initialHist=initial.getHistogram();const targetHist=target.getHistogram();for(let channel=0;channel<3;channel++){for(let pixelVal=0;pixelVal<256;pixelVal++){const currentCount=currentHist[channel][pixelVal];const initialCount=initialHist[channel][pixelVal];const targetCount=targetHist[channel][pixelVal];const currentDiff=Math.abs(currentCount-initialCount);const targetDiff=Math.abs(targetCount-initialCount);match+=Math.min(currentDiff,targetDiff);total+=targetDiff;}}
let progress;if(match===0&&total===0){progress=100;}else{progress=Math.floor(match/total*100);}
return progress;}
function calculateVisualProgress(frames){const initial=frames[0];const target=frames[frames.length-1];frames.forEach(function(frame){const progress=calculateFrameProgress(frame,initial,target);frame.setProgress(progress);});return frames;}
function calculateFrameSimilarity(frame,target){const defaultImageConfig={channels:3};const frameData=Object.assign(frame.getParsedImage(),defaultImageConfig);const targetData=Object.assign(target.getParsedImage(),defaultImageConfig);const diff=imageSSIM.compare(frameData,targetData);return diff.ssim;}
function calculatePerceptualProgress(frames){const target=frames[frames.length-1];const framesSimilarity=frames.map(frame=>calculateFrameSimilarity(frame,target));const minPreceptualProgress=framesSimilarity.reduce((min,progress)=>Math.min(min,progress),Infinity);const normalizedSimilarity=framesSimilarity.map(progress=>{if(progress===minPreceptualProgress){return 0;}
const oldRange=1-minPreceptualProgress;return((progress-minPreceptualProgress)*100)/oldRange;});normalizedSimilarity.forEach((progress,index)=>frames[index].setPerceptualProgress(progress));return frames;}
function calculateSpeedIndexes(frames,data){const startTs=data.startTs;let visuallyCompleteTs;let firstPaintTs;for(let i=0;i<frames.length&&!firstPaintTs;i++){if(frames[i].getProgress()>0){firstPaintTs=frames[i].getTimeStamp();}}
for(let i=0;i<frames.length&&!visuallyCompleteTs;i++){if(frames[i].getProgress()>=100){visuallyCompleteTs=frames[i].getTimeStamp();}}
let prevFrameTs=frames[0].getTimeStamp();let prevProgress=frames[0].getProgress();let prevPerceptualProgress=frames[0].getPerceptualProgress();let speedIndex=firstPaintTs-startTs;let perceptualSpeedIndex=firstPaintTs-startTs;frames.forEach(function(frame){if(frame.getTimeStamp()>firstPaintTs){const elapsed=frame.getTimeStamp()-prevFrameTs;speedIndex+=elapsed*(1-prevProgress);perceptualSpeedIndex+=elapsed*(1-prevPerceptualProgress);}
prevFrameTs=frame.getTimeStamp();prevProgress=frame.getProgress()/100;prevPerceptualProgress=frame.getPerceptualProgress()/100;});return{firstPaintTs,visuallyCompleteTs,speedIndex,perceptualSpeedIndex};}
module.exports={calculateVisualProgress,calculatePerceptualProgress,calculateSpeedIndexes};},{"image-ssim":277}],286:[function(require,module,exports){module.exports={"name":"lighthouse","version":"1.4.1","description":"Lighthouse","main":"./lighthouse-core/index.js","bin":{"lighthouse":"./lighthouse-cli/index.js","chrome-debug":"./lighthouse-cli/manual-chrome-launcher.js"},"engines":{"node":">=5"},"scripts":{"lint":"[ \"$CI\" = true ] && eslint --quiet -f codeframe . || eslint .","smoke":"lighthouse-cli/test/smokehouse/offline-local/run-tests.sh && lighthouse-cli/test/smokehouse/dobetterweb/run-tests.sh","coverage":"node $__node_harmony $(npm bin)/istanbul cover -x \"**/third_party/**\" _mocha -- $(find */test -name '*-test.js') --timeout 10000 --reporter progress","coveralls":"npm run coverage && cat ./coverage/lcov.info | coveralls","start":"node ./lighthouse-cli/index.js","test":"npm run lint --silent && npm run unit","cli-unit":"lighthouse-core/scripts/run-mocha.sh --cli","viewer-unit":"lighthouse-core/scripts/run-mocha.sh --viewer","unit":"lighthouse-core/scripts/run-mocha.sh --default","closure":"cd lighthouse-core && closure/closure-type-checking.js","watch":"lighthouse-core/scripts/run-mocha.sh --watch","chrome":"./lighthouse-cli/manual-chrome-launcher.js","fast":"npm run start -- --disable-device-emulation --disable-cpu-throttling --disable-network-throttling","smokehouse":"node $__node_harmony lighthouse-cli/test/smokehouse/smokehouse.js","deploy-viewer":"cd lighthouse-viewer && gulp deploy"},"devDependencies":{"@types/node":"^6.0.45","babel-core":"^6.16.0","babel-plugin-transform-es2015-destructuring":"^6.9.0","coveralls":"^2.11.9","eslint":"^3.12.0","eslint-config-google":"^0.7.1","google-closure-compiler":"^20161201.0.0","gulp":"^3.9.1","gulp-replace":"^0.5.4","gulp-util":"^3.0.7","istanbul":"^0.4.3","jsdom":"^9.0.0","mocha":"^2.3.3","walk":"^2.3.9","zone.js":"^0.7.3"},"dependencies":{"axe-core":"2.1.7","chrome-devtools-frontend":"1.0.422034","debug":"^2.2.0","devtools-timeline-model":"1.1.6","gl-matrix":"2.3.2","handlebars":"^4.0.5","json-stringify-safe":"^5.0.1","marked":"^0.3.6","mkdirp":"^0.5.1","opn":"^4.0.2","rimraf":"^2.2.8","semver":">=4.3.3","speedline":"1.0.3","whatwg-url":"^4.0.0","ws":"^1.1.1","yargs":"3.30.0"},"repository":"googlechrome/lighthouse","keywords":["google","chrome","devtools"],"author":"The Chromium Authors","license":"Apache-2.0","bugs":{"url":"https://github.com/googlechrome/lighthouse/issues"},"homepage":"https://github.com/googlechrome/lighthouse#readme"}},{}]},{},[197]);;class LighthousePort{on(eventName,cb){}
send(message){}
close(){}}
var Audits2Service=class{setNotify(notify){this._notify=notify;}
start(params){const connection=this;const options=undefined;self.listenForStatus(message=>{this.statusUpdate(message[1]);});return self.runLighthouseInWorker(connection,params.url,options,params.aggregationTags).then(result=>({blobUrl:self.createReportPageAsBlob(result,'devtools'),result})).catchException(null);}
stop(){this.close();return Promise.resolve();}
dispatchProtocolMessage(params){this._onMessage(params['message']);return Promise.resolve();}
dispose(){return Promise.resolve();}
statusUpdate(message){this._notify('statusUpdate',{message:message});}
send(message){this._notify('sendProtocolMessage',{message:message});}
close(){}
on(eventName,cb){if(eventName==='message')
this._onMessage=cb;if(eventName==='close')
this._onClose=cb;}};global=self;global.isVinn=true;global.document={};global.document.documentElement={};global.document.documentElement.style={WebkitAppearance:'WebkitAppearance'};;