From b8830cb5aaf38f9c55f38b44fbb0c248d6f16f92 Mon Sep 17 00:00:00 2001 From: Paul Irish Date: Fri, 22 Jun 2018 14:36:12 +0100 Subject: [PATCH 01/32] core(perf): add instrumentation to measure LH runtime perf --- lighthouse-core/config/config.js | 3 + lighthouse-core/gather/driver.js | 7 +- lighthouse-core/gather/gather-runner.js | 66 +++++++-- lighthouse-core/index.js | 22 ++- lighthouse-core/runner.js | 30 +++- .../scripts/generate-lh-timing-trace.js | 134 ++++++++++++++++++ lighthouse-core/test/index-test.js | 1 + lighthouse-logger/index.js | 13 ++ lighthouse-logger/package.json | 3 +- lighthouse-logger/yarn.lock | 4 + package.json | 1 + 11 files changed, 259 insertions(+), 25 deletions(-) create mode 100644 lighthouse-core/scripts/generate-lh-timing-trace.js diff --git a/lighthouse-core/config/config.js b/lighthouse-core/config/config.js index 05e476164ae4..bde51127f62b 100644 --- a/lighthouse-core/config/config.js +++ b/lighthouse-core/config/config.js @@ -308,6 +308,8 @@ class Config { * @param {LH.Flags=} flags */ constructor(configJSON, flags) { + const status = {msg: 'Create config', id: 'config-create'}; + log.time(status, 'verbose'); let configPath = flags && flags.configPath; if (!configJSON) { @@ -360,6 +362,7 @@ class Config { // TODO(bckenny): until tsc adds @implements support, assert that Config is a ConfigJson. /** @type {LH.Config.Json} */ const configJson = this; // eslint-disable-line no-unused-vars + log.timeEnd(status); } /** diff --git a/lighthouse-core/gather/driver.js b/lighthouse-core/gather/driver.js index c9d3b98d8918..210666c0bd94 100644 --- a/lighthouse-core/gather/driver.js +++ b/lighthouse-core/gather/driver.js @@ -109,8 +109,11 @@ class Driver { /** * @return {Promise} */ - connect() { - return this._connection.connect(); + async connect() { + const status = {msg: 'Connecting to browser', id: 'lh:init:connect'}; + log.time(status); + await this._connection.connect(); + log.timeEnd(status); } /** diff --git a/lighthouse-core/gather/gather-runner.js b/lighthouse-core/gather/gather-runner.js index d95d09e3fe32..d7872ef727db 100644 --- a/lighthouse-core/gather/gather-runner.js +++ b/lighthouse-core/gather/gather-runner.js @@ -75,8 +75,11 @@ class GatherRunner { url = constants.defaultPassConfig.blankPage, duration = constants.defaultPassConfig.blankDuration ) { + const status = {msg: 'Resetting state with about:blank', id: 'lh:gather:loadBlank'}; + log.time(status); await driver.gotoURL(url); await new Promise(resolve => setTimeout(resolve, duration)); + log.timeEnd(status); } /** @@ -102,7 +105,8 @@ class GatherRunner { * @return {Promise} */ static async setupDriver(driver, options) { - log.log('status', 'Initializing…'); + const status = {msg: 'Initializing…', id: 'lh:gather:setupDriver'}; + log.time(status); const resetStorage = !options.settings.disableStorageReset; // Enable emulation based on settings await driver.assertNoSameOriginServiceWorkerClients(options.requestedUrl); @@ -112,6 +116,7 @@ class GatherRunner { await driver.registerPerformanceObserver(); await driver.dismissJavaScriptDialogs(); if (resetStorage) await driver.clearDataForOrigin(options.requestedUrl); + log.timeEnd(status); } /** @@ -119,13 +124,15 @@ class GatherRunner { * @return {Promise} */ static disposeDriver(driver) { - log.log('status', 'Disconnecting from browser...'); + const status = {msg: 'Disconnecting from browser...', id: 'lh:gather:disconnect'}; + log.time(status); return driver.disconnect().catch(err => { // Ignore disconnecting error if browser was already closed. // See https://github.com/GoogleChrome/lighthouse/issues/1583 if (!(/close\/.*status: 500$/.test(err.message))) { log.error('GatherRunner disconnect', err.message); } + log.timeEnd(status); }); } @@ -179,6 +186,8 @@ class GatherRunner { * @return {Promise} */ static async beforePass(passContext, gathererResults) { + const bpStatus = {msg: `Running beforePass methods`, id: `lh:gather:beforePass`}; + log.time(bpStatus, 'verbose'); const blockedUrls = (passContext.passConfig.blockedUrlPatterns || []) .concat(passContext.settings.blockedUrlPatterns || []); const blankPage = passContext.passConfig.blankPage; @@ -194,10 +203,17 @@ class GatherRunner { const gatherer = gathererDefn.instance; // Abuse the passContext to pass through gatherer options passContext.options = gathererDefn.options || {}; + const status = { + msg: `Retrieving setup: ${gatherer.name}`, + id: `lh:gather:beforePass:${gatherer.name}`, + }; + log.time(status, 'verbose'); const artifactPromise = Promise.resolve().then(_ => gatherer.beforePass(passContext)); gathererResults[gatherer.name] = [artifactPromise]; await GatherRunner.recoverOrThrow(artifactPromise); + log.timeEnd(status); } + log.timeEnd(bpStatus); } /** @@ -216,9 +232,12 @@ class GatherRunner { const recordTrace = config.recordTrace; const isPerfRun = !settings.disableStorageReset && recordTrace && config.useThrottling; - const gatherernames = gatherers.map(g => g.instance.name).join(', '); - const status = 'Loading page & waiting for onload'; - log.log('status', status, gatherernames); + const status = { + msg: 'Loading page & waiting for onload', + id: 'lh:gather:loadPage', + args: [gatherers.map(g => g.instance.name).join(', ')], + }; + log.time(status); // Clear disk & memory cache if it's a perf run if (isPerfRun) await driver.cleanBrowserCaches(); @@ -229,19 +248,28 @@ class GatherRunner { // Navigate. await GatherRunner.loadPage(driver, passContext); - log.log('statusEnd', status); + log.timeEnd(status); + const pStatus = {msg: `Running pass methods`, id: `lh:gather:pass`}; + log.time(pStatus, 'verbose'); for (const gathererDefn of gatherers) { const gatherer = gathererDefn.instance; // Abuse the passContext to pass through gatherer options passContext.options = gathererDefn.options || {}; + const status = { + msg: `Retrieving in-page: ${gatherer.name}`, + id: `lh:gather:pass:${gatherer.name}`, + }; + log.time(status); const artifactPromise = Promise.resolve().then(_ => gatherer.pass(passContext)); const gathererResult = gathererResults[gatherer.name] || []; gathererResult.push(artifactPromise); gathererResults[gatherer.name] = gathererResult; await GatherRunner.recoverOrThrow(artifactPromise); + log.timeEnd(status); } + log.timeEnd(pStatus); } /** @@ -259,16 +287,20 @@ class GatherRunner { let trace; if (config.recordTrace) { - log.log('status', 'Retrieving trace'); + const status = {msg: 'Retrieving trace', id: `lh:gather:getTrace`}; + log.time(status); trace = await driver.endTrace(); - log.verbose('statusEnd', 'Retrieving trace'); + log.timeEnd(status); } - const status = 'Retrieving devtoolsLog and network records'; - log.log('status', status); + const status = { + msg: 'Retrieving devtoolsLog & network records', + id: `lh:gather:getDevtoolsLog`, + }; + log.time(status); const devtoolsLog = driver.endDevtoolsLog(); const networkRecords = NetworkRecorder.recordsFromLogs(devtoolsLog); - log.verbose('statusEnd', status); + log.timeEnd(status); let pageLoadError = GatherRunner.getPageLoadError(passContext.url, networkRecords); // If the driver was offline, a page load error is expected, so do not save it. @@ -288,13 +320,18 @@ class GatherRunner { trace, }; + const apStatus = {msg: `Running afterPass methods`, id: `lh:gather:afterPass`}; // Disable throttling so the afterPass analysis isn't throttled await driver.setThrottling(passContext.settings, {useThrottling: false}); + log.time(apStatus, 'verbose'); for (const gathererDefn of gatherers) { const gatherer = gathererDefn.instance; - const status = `Retrieving: ${gatherer.name}`; - log.log('status', status); + const status = { + msg: `Retrieving: ${gatherer.name}`, + id: `lh:gather:afterPass:${gatherer.name}`, + }; + log.time(status); // Add gatherer options to the passContext. passContext.options = gathererDefn.options || {}; @@ -309,8 +346,9 @@ class GatherRunner { gathererResult.push(artifactPromise); gathererResults[gatherer.name] = gathererResult; await GatherRunner.recoverOrThrow(artifactPromise); - log.verbose('statusEnd', status); + log.timeEnd(status); } + log.timeEnd(apStatus); // Resolve on tracing data using passName from config. return passData; diff --git a/lighthouse-core/index.js b/lighthouse-core/index.js index 7b91a8b0dce7..b918c970230c 100644 --- a/lighthouse-core/index.js +++ b/lighthouse-core/index.js @@ -39,12 +39,19 @@ async function lighthouse(url, flags, configJSON) { flags.logLevel = flags.logLevel || 'error'; log.setLevel(flags.logLevel); + const overallStatus = {msg: 'Overall', id: 'lh:index'}; + log.time(overallStatus, 'verbose'); + // Use ConfigParser to generate a valid config file const config = new Config(configJSON, flags); const connection = new ChromeProtocol(flags.port, flags.hostname); // kick off a lighthouse run - return Runner.run(connection, {url, config}); + const runnerResult = await Runner.run(connection, {url, config}); + + const totalEntry = log.timeEnd(overallStatus); + finalizeEndTime(totalEntry, runnerResult); + return runnerResult; } lighthouse.getAuditList = Runner.getAuditList; @@ -52,4 +59,17 @@ lighthouse.traceCategories = require('./gather/driver').traceCategories; lighthouse.Audit = require('./audits/audit'); lighthouse.Gatherer = require('./gather/gatherers/gatherer'); + +/** + * Add timing entry for the overall LH run + */ +function finalizeEndTime(totalEntry, runnerResult) { + if (!runnerResult) return; + runnerResult.lhr.timing = runnerResult.lhr.timing || {}; + runnerResult.lhr.timing.entries = runnerResult.lhr.timing.entries || []; + // preserve lhr.timing.total for backcompatibility + runnerResult.lhr.timing.total = totalEntry.duration; +} + + module.exports = lighthouse; diff --git a/lighthouse-core/runner.js b/lighthouse-core/runner.js index 8c6addaabcdd..635485cdfb78 100644 --- a/lighthouse-core/runner.js +++ b/lighthouse-core/runner.js @@ -29,8 +29,9 @@ class Runner { */ static async run(connection, opts) { try { - const startTime = Date.now(); const settings = opts.config.settings; + const runnerStatus = {msg: 'Runner setup', id: 'lh:runner:run'}; + log.time(runnerStatus, 'verbose'); /** * List of top-level warnings for this Lighthouse run. @@ -67,6 +68,7 @@ class Runner { if (opts.url && opts.url !== requestedUrl) { throw new Error('Cannot run audit mode on different URL'); } + log.timeEnd(runnerStatus); } else { if (typeof opts.url !== 'string' || opts.url.length === 0) { throw new Error(`You must provide a url to the runner. '${opts.url}' provided.`); @@ -79,6 +81,7 @@ class Runner { throw new Error('The url provided should have a proper protocol and hostname.'); } + log.timeEnd(runnerStatus); artifacts = await Runner._gatherArtifactsFromBrowser(requestedUrl, opts, connection); // -G means save these to ./latest-run, etc. if (settings.gatherMode) { @@ -97,7 +100,8 @@ class Runner { const auditResults = await Runner._runAudits(settings, opts.config.audits, artifacts); // LHR construction phase - log.log('status', 'Generating results...'); + const status = {msg: 'Generating results...', id: 'lh:runner:generate'}; + log.time(status); if (artifacts.LighthouseRunWarnings) { lighthouseRunWarnings.push(...artifacts.LighthouseRunWarnings); @@ -119,6 +123,11 @@ class Runner { categories = ReportScoring.scoreAllCategories(opts.config.categories, resultsById); } + log.timeEnd(status); + // Summarize all the timings and drop onto the LHR + artifacts.Timing = artifacts.Timing || {entries: [], gatherEntries: []}; + artifacts.Timing.entries.push(...log.marky.getEntries()); + /** @type {LH.Result} */ const lhr = { userAgent: artifacts.UserAgent, @@ -131,10 +140,11 @@ class Runner { configSettings: settings, categories, categoryGroups: opts.config.groups || undefined, - timing: {total: Date.now() - startTime}, + timing: artifacts.Timing, }; const report = generateReport(lhr, settings.output); + log.timeEnd(status); return {lhr, artifacts, report}; } catch (err) { // @ts-ignore TODO(bckenny): Sentry type checking @@ -162,6 +172,8 @@ class Runner { settings: runnerOpts.config.settings, }; const artifacts = await GatherRunner.run(runnerOpts.config.passes, gatherOpts); + artifacts.Timing = {entries: [], gatherEntries: log.marky.getEntries()}; + log.marky.clear(); return artifacts; } @@ -173,7 +185,7 @@ class Runner { * @return {Promise>} */ static async _runAudits(settings, audits, artifacts) { - log.log('status', 'Analyzing and running audits...'); + log.time({msg: 'Analyzing and running audits...', id: 'lh:runner:auditing'}); artifacts = Object.assign({}, Runner.instantiateComputedArtifacts(), artifacts); if (artifacts.settings) { @@ -194,6 +206,7 @@ class Runner { auditResults.push(auditResult); } + log.timeEnd({msg: 'Analyzing and running audits...', id: 'lh:runner:auditing'}); return auditResults; } @@ -208,9 +221,12 @@ class Runner { */ static async _runAudit(auditDefn, artifacts, settings) { const audit = auditDefn.implementation; - const status = `Evaluating: ${audit.meta.description}`; + const status = { + msg: `Evaluating: ${audit.meta.description}`, + id: `lh:audit:${audit.meta.name}`, + }; + log.time(status); - log.log('status', status); let auditResult; try { // Return an early error if an artifact required for the audit is missing or an error. @@ -271,7 +287,7 @@ class Runner { auditResult = Audit.generateErrorAuditResult(audit, errorMessage); } - log.verbose('statusEnd', status); + log.timeEnd(status); return auditResult; } diff --git a/lighthouse-core/scripts/generate-lh-timing-trace.js b/lighthouse-core/scripts/generate-lh-timing-trace.js new file mode 100644 index 000000000000..2832763c6818 --- /dev/null +++ b/lighthouse-core/scripts/generate-lh-timing-trace.js @@ -0,0 +1,134 @@ +/** + * @license Copyright 2016 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + */ +'use strict'; + +const fs = require('fs'); +const path = require('path'); + +/** + * Technically, it's fine for usertiming measures to overlap, however non-async events make + * for a much clearer UI in traceviewer. We do this check to make sure we aren't passing off + * async-like measures as non-async. + * @param {!PerformanceEntry} entry user timing entry + * @param {!Array} prevEntries user timing entries + */ +function checkEventOverlap(entry, prevEntries) { + for (const prevEntry of prevEntries) { + const prevEnd = prevEntry.startTime + prevEntry.duration; + const thisEnd = entry.startTime + entry.duration; + const isOverlap = prevEnd > entry.startTime && prevEnd < thisEnd; + if (isOverlap) { + throw new Error(`Two measures overlap! ${prevEntry.name} & ${entry.name}`); + } + } +} + +/** + * Generates a chromium trace file from user timing measures + * Adapted from https://github.com/tdresser/performance-observer-tracing + * @param {!Array} entries user timing entries + */ +function generateTraceEvents(entries) { + const currentTrace = []; + let id = 0; + + entries.sort((a, b) => a.startTime - b.startTime); + entries.forEach((entry, i) => { + checkEventOverlap(entry, entries.slice(0, i)); + + const traceEvent = { + name: entry.name, + cat: entry.entryType, + ts: entry.startTime * 1000, + dur: entry.duration * 1000, + }; + + if (entry.entryType !== 'measure') throw new Error('Unexpected entryType!'); + traceEvent.pid = 'Lighthouse'; + traceEvent.tid = 'measures'; + + if (entry.duration === 0) { + traceEvent.ph = 'n'; + traceEvent.s = 't'; + } else { + traceEvent.ph = 'X'; + } + + traceEvent.id = '0x' + id.toString(16); + id++; + + const args = {}; + for (const key of Object.keys(entry)) { + const value = entry[key]; + if (key === 'entryType' || key === 'name' || key === 'toJSON') { + continue; + } + args[key] = value; + } + traceEvent.args = args; + + currentTrace.push(traceEvent); + }); + + return currentTrace; +} + +/** + * Writes a trace file to disk + * @param {!Array} entries user timing entries + * @param {?string} traceFilePath where to save the trace file + */ +function saveTraceOfTimings(entries, traceFilePath) { + const events = generateTraceEvents(entries); + + const jsonStr = ` + { "traceEvents": [ + ${events.map(evt => JSON.stringify(evt)).join(',\n')} + ]}`; + + if (!traceFilePath) { + traceFilePath = path.resolve(process.cwd(), 'run-timing.trace.json'); + } + fs.writeFileSync(traceFilePath, jsonStr, 'utf8'); + process.stdout.write(` + > Timing trace file saved to: ${traceFilePath} + > Open this file in chrome://tracing + +`); +} + +/** + * Takes filename of LHR object. The primary entrypoint on CLI + */ +function saveTraceFromCLI() { + const printErrorAndQuit = msg => { + process.stderr.write(`ERROR: + > ${msg} + > Example: + > yarn timing results.json + +`); + process.exit(1); + }; + + if (!process.argv[2]) { + printErrorAndQuit('Lighthouse JSON results path not provided'); + } + const filename = path.resolve(process.cwd(), process.argv[2]); + if (!fs.existsSync(filename)) { + printErrorAndQuit('Lighthouse JSON results not found.'); + } + + const lhrObject = JSON.parse(fs.readFileSync(filename, 'utf8')); + const traceFilePath = `${filename}.run-timing.trace.json`; + saveTraceOfTimings(lhrObject.timing.entries, traceFilePath); +} + +if (require.main === module) { + saveTraceFromCLI(); +} else { + module.exports = {generateTraceEvents, saveTraceOfTimings, saveTraceFromCLI}; +} diff --git a/lighthouse-core/test/index-test.js b/lighthouse-core/test/index-test.js index 25cc0e89f596..2d10504787a4 100644 --- a/lighthouse-core/test/index-test.js +++ b/lighthouse-core/test/index-test.js @@ -111,6 +111,7 @@ describe('Module Tests', function() { assert.ok(results.lhr.audits.viewport.explanation); assert.ok(results.lhr.timing); assert.equal(typeof results.lhr.timing.total, 'number'); + assert.ok(results.lhr.timing.entries.length > 3, 'timing entries not populated'); }); }); diff --git a/lighthouse-logger/index.js b/lighthouse-logger/index.js index 39cc6eae1f9f..951281e736c5 100644 --- a/lighthouse-logger/index.js +++ b/lighthouse-logger/index.js @@ -6,6 +6,8 @@ 'use strict'; const debug = require('debug'); +const marky = require('marky'); + const EventEmitter = require('events').EventEmitter; const isWindows = process.platform === 'win32'; @@ -104,6 +106,16 @@ class Log { Log._logToStdErr(`${prefix}:${level || ''}`, [method, snippet]); } + static time({msg, id, args=[]}, level='log') { + marky.mark(id); + Log[level]('status', msg, ...args); + } + + static timeEnd({msg, id, args=[]}, level='verbose') { + Log[level]('statusEnd', msg, ...args); + return marky.stop(id); + } + static log(title, ...args) { Log.events.issueStatus(title, args); return Log._logToStdErr(title, args); @@ -207,5 +219,6 @@ class Log { } Log.events = new Emitter(); +Log.marky = marky; module.exports = Log; diff --git a/lighthouse-logger/package.json b/lighthouse-logger/package.json index 0491cac2910c..80c56a815124 100644 --- a/lighthouse-logger/package.json +++ b/lighthouse-logger/package.json @@ -3,6 +3,7 @@ "version": "1.0.1", "license": "Apache-2.0", "dependencies": { - "debug": "^2.6.8" + "debug": "^2.6.8", + "marky": "^1.2.0" } } diff --git a/lighthouse-logger/yarn.lock b/lighthouse-logger/yarn.lock index 3e130cd61404..5cef70256d6c 100644 --- a/lighthouse-logger/yarn.lock +++ b/lighthouse-logger/yarn.lock @@ -8,6 +8,10 @@ debug@^2.6.8: dependencies: ms "2.0.0" +marky@^1.2.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/marky/-/marky-1.2.0.tgz#9617ed647bbbea8f45d19526da33dec70606df42" + ms@2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/ms/-/ms-2.0.0.tgz#5608aeadfc00be6c2901df5f9861788de0d597c8" diff --git a/package.json b/package.json index bbcc284a5252..73ba2c369cbc 100644 --- a/package.json +++ b/package.json @@ -57,6 +57,7 @@ "deploy-viewer": "cd lighthouse-viewer && gulp deploy", "bundlesize": "bundlesize", "plots-smoke": "bash plots/test/smoke.sh", + "timing": "node lighthouse-core/scripts/generate-lh-timing-trace.js", "changelog": "conventional-changelog --config ./build/changelog-generator/index.js --infile changelog.md --same-file", "type-check": "tsc -p . && cd ./lighthouse-viewer && yarn type-check", "update:sample-artifacts": "node lighthouse-core/scripts/update-report-fixtures.js -G", From df7e1b4e228dd52c8c07f091b740b578227f9c9f Mon Sep 17 00:00:00 2001 From: Paul Irish Date: Fri, 22 Jun 2018 16:28:20 +0100 Subject: [PATCH 02/32] gatherEntries and no more .timing.total --- lighthouse-core/gather/gather-runner.js | 1 + lighthouse-core/index.js | 22 +--------------------- lighthouse-core/lib/asset-saver.js | 3 +++ lighthouse-core/runner.js | 7 +++---- lighthouse-logger/index.js | 3 ++- typings/artifacts.d.ts | 2 ++ typings/lhr.d.ts | 2 +- typings/lighthouse-logger/index.d.ts | 9 +++++++++ 8 files changed, 22 insertions(+), 27 deletions(-) diff --git a/lighthouse-core/gather/gather-runner.js b/lighthouse-core/gather/gather-runner.js index d7872ef727db..a4c51a9c90fd 100644 --- a/lighthouse-core/gather/gather-runner.js +++ b/lighthouse-core/gather/gather-runner.js @@ -417,6 +417,7 @@ class GatherRunner { devtoolsLogs: {}, settings: options.settings, URL: {requestedUrl: options.requestedUrl, finalUrl: ''}, + Timing: {entries: [], gatherEntries: []}, }; } diff --git a/lighthouse-core/index.js b/lighthouse-core/index.js index b918c970230c..cb1c6ec6e4a6 100644 --- a/lighthouse-core/index.js +++ b/lighthouse-core/index.js @@ -39,19 +39,12 @@ async function lighthouse(url, flags, configJSON) { flags.logLevel = flags.logLevel || 'error'; log.setLevel(flags.logLevel); - const overallStatus = {msg: 'Overall', id: 'lh:index'}; - log.time(overallStatus, 'verbose'); - // Use ConfigParser to generate a valid config file const config = new Config(configJSON, flags); const connection = new ChromeProtocol(flags.port, flags.hostname); // kick off a lighthouse run - const runnerResult = await Runner.run(connection, {url, config}); - - const totalEntry = log.timeEnd(overallStatus); - finalizeEndTime(totalEntry, runnerResult); - return runnerResult; + return await Runner.run(connection, {url, config}); } lighthouse.getAuditList = Runner.getAuditList; @@ -59,17 +52,4 @@ lighthouse.traceCategories = require('./gather/driver').traceCategories; lighthouse.Audit = require('./audits/audit'); lighthouse.Gatherer = require('./gather/gatherers/gatherer'); - -/** - * Add timing entry for the overall LH run - */ -function finalizeEndTime(totalEntry, runnerResult) { - if (!runnerResult) return; - runnerResult.lhr.timing = runnerResult.lhr.timing || {}; - runnerResult.lhr.timing.entries = runnerResult.lhr.timing.entries || []; - // preserve lhr.timing.total for backcompatibility - runnerResult.lhr.timing.total = totalEntry.duration; -} - - module.exports = lighthouse; diff --git a/lighthouse-core/lib/asset-saver.js b/lighthouse-core/lib/asset-saver.js index e149d670b705..3836299edd9a 100644 --- a/lighthouse-core/lib/asset-saver.js +++ b/lighthouse-core/lib/asset-saver.js @@ -118,6 +118,9 @@ async function loadArtifacts(basePath) { }); }); await Promise.all(promises); + // Move entries to separate array, so they can be rendered in parallel + artifacts.Timing.gatherEntries = artifacts.Timing.entries; + artifacts.Timing.entries = []; return artifacts; } diff --git a/lighthouse-core/runner.js b/lighthouse-core/runner.js index 635485cdfb78..a30bcaa4104e 100644 --- a/lighthouse-core/runner.js +++ b/lighthouse-core/runner.js @@ -125,8 +125,7 @@ class Runner { log.timeEnd(status); // Summarize all the timings and drop onto the LHR - artifacts.Timing = artifacts.Timing || {entries: [], gatherEntries: []}; - artifacts.Timing.entries.push(...log.marky.getEntries()); + artifacts.Timing.entries.push(...log.getEntries()); /** @type {LH.Result} */ const lhr = { @@ -172,8 +171,8 @@ class Runner { settings: runnerOpts.config.settings, }; const artifacts = await GatherRunner.run(runnerOpts.config.passes, gatherOpts); - artifacts.Timing = {entries: [], gatherEntries: log.marky.getEntries()}; - log.marky.clear(); + artifacts.Timing.entries = log.getEntries(); + log.clearEntries(); return artifacts; } diff --git a/lighthouse-logger/index.js b/lighthouse-logger/index.js index 951281e736c5..f521a599738f 100644 --- a/lighthouse-logger/index.js +++ b/lighthouse-logger/index.js @@ -219,6 +219,7 @@ class Log { } Log.events = new Emitter(); -Log.marky = marky; +Log.clearEntries = _ => marky.clear(); +Log.getEntries = _ => marky.getEntries(); module.exports = Log; diff --git a/typings/artifacts.d.ts b/typings/artifacts.d.ts index b3d0beaf47bb..d824f80f3a2e 100644 --- a/typings/artifacts.d.ts +++ b/typings/artifacts.d.ts @@ -30,6 +30,8 @@ declare global { settings: Config.Settings; /** The URL initially requested and the post-redirects URL that was actually loaded. */ URL: {requestedUrl: string, finalUrl: string}; + + Timing: {entries: PerformanceEntry[], gatherEntries: PerformanceEntry[]}; } /** diff --git a/typings/lhr.d.ts b/typings/lhr.d.ts index 45724ba7cfaf..f920512a728d 100644 --- a/typings/lhr.d.ts +++ b/typings/lhr.d.ts @@ -34,7 +34,7 @@ declare global { /** The User-Agent string of the browser used run Lighthouse for these results. */ userAgent: string; /** Execution timings for the Lighthouse run */ - timing: {total: number, [t: string]: number}; + timing: {entries: PerformanceEntry[], gatherEntries: PerformanceEntry[]}; } // Result namespace diff --git a/typings/lighthouse-logger/index.d.ts b/typings/lighthouse-logger/index.d.ts index 3e862b762c42..17b19aaafc58 100644 --- a/typings/lighthouse-logger/index.d.ts +++ b/typings/lighthouse-logger/index.d.ts @@ -5,12 +5,21 @@ */ declare module 'lighthouse-logger' { + interface Status { + msg: string; + id: string; + args?: any[]; + } export function setLevel(level: string): void; export function formatProtocol(prefix: string, data: Object, level?: string): void; export function log(title: string, ...args: any[]): void; export function warn(title: string, ...args: any[]): void; export function error(title: string, ...args: any[]): void; export function verbose(title: string, ...args: any[]): void; + export function time(status: Status, level?: string): void; + export function timeEnd(status: Status, level?: string): void; export function reset(): string; + export function clearEntries(): void; + export function getEntries(): PerformanceEntry[]; export var events: import('events').EventEmitter; } From f1a2909ac404f84122364827cd5ca7d5f051f356 Mon Sep 17 00:00:00 2001 From: Paul Irish Date: Fri, 22 Jun 2018 16:28:34 +0100 Subject: [PATCH 03/32] fixup typing of traces. --- .../scripts/generate-lh-timing-trace.js | 46 ++++++++----------- typings/externs.d.ts | 4 +- 2 files changed, 21 insertions(+), 29 deletions(-) diff --git a/lighthouse-core/scripts/generate-lh-timing-trace.js b/lighthouse-core/scripts/generate-lh-timing-trace.js index 2832763c6818..216f65dfb415 100644 --- a/lighthouse-core/scripts/generate-lh-timing-trace.js +++ b/lighthouse-core/scripts/generate-lh-timing-trace.js @@ -30,9 +30,10 @@ function checkEventOverlap(entry, prevEntries) { * Generates a chromium trace file from user timing measures * Adapted from https://github.com/tdresser/performance-observer-tracing * @param {!Array} entries user timing entries + * @param {string=} threadName */ -function generateTraceEvents(entries) { - const currentTrace = []; +function generateTraceEvents(entries, threadName = 'measures') { + const currentTrace = /** @type {!LH.TraceEvent[]} */ ([]); let id = 0; entries.sort((a, b) => a.startTime - b.startTime); @@ -44,31 +45,18 @@ function generateTraceEvents(entries) { cat: entry.entryType, ts: entry.startTime * 1000, dur: entry.duration * 1000, + args: {}, + pid: 'Lighthouse', + tid: threadName, + ph: 'X', + id: '0x' + (id++).toString(16), }; if (entry.entryType !== 'measure') throw new Error('Unexpected entryType!'); - traceEvent.pid = 'Lighthouse'; - traceEvent.tid = 'measures'; - if (entry.duration === 0) { traceEvent.ph = 'n'; traceEvent.s = 't'; - } else { - traceEvent.ph = 'X'; - } - - traceEvent.id = '0x' + id.toString(16); - id++; - - const args = {}; - for (const key of Object.keys(entry)) { - const value = entry[key]; - if (key === 'entryType' || key === 'name' || key === 'toJSON') { - continue; - } - args[key] = value; } - traceEvent.args = args; currentTrace.push(traceEvent); }); @@ -78,12 +66,10 @@ function generateTraceEvents(entries) { /** * Writes a trace file to disk - * @param {!Array} entries user timing entries + * @param {LH.TraceEvent[]} events trace events * @param {?string} traceFilePath where to save the trace file */ -function saveTraceOfTimings(entries, traceFilePath) { - const events = generateTraceEvents(entries); - +function saveTraceOfEvents(events, traceFilePath) { const jsonStr = ` { "traceEvents": [ ${events.map(evt => JSON.stringify(evt)).join(',\n')} @@ -104,7 +90,10 @@ function saveTraceOfTimings(entries, traceFilePath) { * Takes filename of LHR object. The primary entrypoint on CLI */ function saveTraceFromCLI() { - const printErrorAndQuit = msg => { + /** + * @param {!string} msg + */ + const printErrorAndQuit = (msg) => { process.stderr.write(`ERROR: > ${msg} > Example: @@ -124,11 +113,14 @@ function saveTraceFromCLI() { const lhrObject = JSON.parse(fs.readFileSync(filename, 'utf8')); const traceFilePath = `${filename}.run-timing.trace.json`; - saveTraceOfTimings(lhrObject.timing.entries, traceFilePath); + + const gatherEvents = generateTraceEvents(lhrObject.timing.gatherEntries, 'gather'); + const events = generateTraceEvents(lhrObject.timing.entries); + saveTraceOfEvents([...gatherEvents, ...events], traceFilePath); } if (require.main === module) { saveTraceFromCLI(); } else { - module.exports = {generateTraceEvents, saveTraceOfTimings, saveTraceFromCLI}; + module.exports = {generateTraceEvents, saveTraceOfEvents, saveTraceFromCLI}; } diff --git a/typings/externs.d.ts b/typings/externs.d.ts index 47237948735e..531240b470ef 100644 --- a/typings/externs.d.ts +++ b/typings/externs.d.ts @@ -160,8 +160,8 @@ declare global { frame?: string; name?: string; }; - pid: number; - tid: number; + pid: number|string; + tid: number|string; ts: number; dur: number; ph: 'B'|'b'|'D'|'E'|'e'|'F'|'I'|'M'|'N'|'n'|'O'|'R'|'S'|'T'|'X'; From c46548d251cbfbb4e6b959a2c20dec8929568136 Mon Sep 17 00:00:00 2001 From: Paul Irish Date: Fri, 22 Jun 2018 18:07:31 +0100 Subject: [PATCH 04/32] feedback. --- lighthouse-core/config/config.js | 2 +- lighthouse-core/runner.js | 1 - .../scripts/generate-lh-timing-trace.js | 26 +++++++++---------- lighthouse-logger/index.js | 7 +++-- 4 files changed, 19 insertions(+), 17 deletions(-) diff --git a/lighthouse-core/config/config.js b/lighthouse-core/config/config.js index bde51127f62b..a247132b42e1 100644 --- a/lighthouse-core/config/config.js +++ b/lighthouse-core/config/config.js @@ -308,7 +308,7 @@ class Config { * @param {LH.Flags=} flags */ constructor(configJSON, flags) { - const status = {msg: 'Create config', id: 'config-create'}; + const status = {msg: 'Create config', id: 'lh:init:config'}; log.time(status, 'verbose'); let configPath = flags && flags.configPath; diff --git a/lighthouse-core/runner.js b/lighthouse-core/runner.js index a30bcaa4104e..987e2471caf1 100644 --- a/lighthouse-core/runner.js +++ b/lighthouse-core/runner.js @@ -172,7 +172,6 @@ class Runner { }; const artifacts = await GatherRunner.run(runnerOpts.config.passes, gatherOpts); artifacts.Timing.entries = log.getEntries(); - log.clearEntries(); return artifacts; } diff --git a/lighthouse-core/scripts/generate-lh-timing-trace.js b/lighthouse-core/scripts/generate-lh-timing-trace.js index 216f65dfb415..137ba212b24b 100644 --- a/lighthouse-core/scripts/generate-lh-timing-trace.js +++ b/lighthouse-core/scripts/generate-lh-timing-trace.js @@ -79,30 +79,30 @@ function saveTraceOfEvents(events, traceFilePath) { traceFilePath = path.resolve(process.cwd(), 'run-timing.trace.json'); } fs.writeFileSync(traceFilePath, jsonStr, 'utf8'); - process.stdout.write(` + // eslint-disable-next-line no-console + console.log(` > Timing trace file saved to: ${traceFilePath} > Open this file in chrome://tracing - `); } /** - * Takes filename of LHR object. The primary entrypoint on CLI + * @param {!string} msg */ -function saveTraceFromCLI() { - /** - * @param {!string} msg - */ - const printErrorAndQuit = (msg) => { - process.stderr.write(`ERROR: +function printErrorAndQuit(msg) { + // eslint-disable-next-line no-console + console.error(`ERROR: > ${msg} > Example: > yarn timing results.json + `) + process.exit(1); +}; -`); - process.exit(1); - }; - +/** + * Takes filename of LHR object. The primary entrypoint on CLI + */ +function saveTraceFromCLI() { if (!process.argv[2]) { printErrorAndQuit('Lighthouse JSON results path not provided'); } diff --git a/lighthouse-logger/index.js b/lighthouse-logger/index.js index f521a599738f..568c2d1204ea 100644 --- a/lighthouse-logger/index.js +++ b/lighthouse-logger/index.js @@ -219,7 +219,10 @@ class Log { } Log.events = new Emitter(); -Log.clearEntries = _ => marky.clear(); -Log.getEntries = _ => marky.getEntries(); +Log.getEntries = _ => { + const entries = marky.getEntries(); + marky.clear(); + return entries; +} module.exports = Log; From ab9386d2a86503c908b375e859dd684177a85bc0 Mon Sep 17 00:00:00 2001 From: Paul Irish Date: Mon, 25 Jun 2018 19:23:24 +0100 Subject: [PATCH 05/32] split lib & cli --- lighthouse-core/lib/asset-saver.js | 8 ++- .../timing-trace-saver.js} | 61 +++---------------- .../scripts/generate-timing-trace.js | 49 +++++++++++++++ .../test/results/artifacts/artifacts.json | 1 + package.json | 2 +- 5 files changed, 66 insertions(+), 55 deletions(-) rename lighthouse-core/{scripts/generate-lh-timing-trace.js => lib/timing-trace-saver.js} (59%) create mode 100644 lighthouse-core/scripts/generate-timing-trace.js diff --git a/lighthouse-core/lib/asset-saver.js b/lighthouse-core/lib/asset-saver.js index 3836299edd9a..eefd42708339 100644 --- a/lighthouse-core/lib/asset-saver.js +++ b/lighthouse-core/lib/asset-saver.js @@ -118,9 +118,11 @@ async function loadArtifacts(basePath) { }); }); await Promise.all(promises); - // Move entries to separate array, so they can be rendered in parallel - artifacts.Timing.gatherEntries = artifacts.Timing.entries; - artifacts.Timing.entries = []; + if (artifacts.Timing) { + // Move entries to separate array, so they can be rendered in parallel + artifacts.Timing.gatherEntries = artifacts.Timing.entries; + artifacts.Timing.entries = []; + } return artifacts; } diff --git a/lighthouse-core/scripts/generate-lh-timing-trace.js b/lighthouse-core/lib/timing-trace-saver.js similarity index 59% rename from lighthouse-core/scripts/generate-lh-timing-trace.js rename to lighthouse-core/lib/timing-trace-saver.js index 137ba212b24b..e5ed2f0b5af2 100644 --- a/lighthouse-core/scripts/generate-lh-timing-trace.js +++ b/lighthouse-core/lib/timing-trace-saver.js @@ -1,13 +1,10 @@ /** - * @license Copyright 2016 Google Inc. All Rights Reserved. + * @license Copyright 2018 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ 'use strict'; -const fs = require('fs'); -const path = require('path'); - /** * Technically, it's fine for usertiming measures to overlap, however non-async events make * for a much clearer UI in traceviewer. We do this check to make sure we aren't passing off @@ -66,61 +63,23 @@ function generateTraceEvents(entries, threadName = 'measures') { /** * Writes a trace file to disk - * @param {LH.TraceEvent[]} events trace events - * @param {?string} traceFilePath where to save the trace file + * @param {LH.Result} lhr + * @return {!string}; */ -function saveTraceOfEvents(events, traceFilePath) { +function createTraceString(lhr) { + const gatherEvents = generateTraceEvents(lhr.timing.gatherEntries, 'gather'); + const auditEvents = generateTraceEvents(lhr.timing.entries); + const events = [...gatherEvents, ...auditEvents]; + const jsonStr = ` { "traceEvents": [ ${events.map(evt => JSON.stringify(evt)).join(',\n')} ]}`; - if (!traceFilePath) { - traceFilePath = path.resolve(process.cwd(), 'run-timing.trace.json'); - } - fs.writeFileSync(traceFilePath, jsonStr, 'utf8'); - // eslint-disable-next-line no-console - console.log(` - > Timing trace file saved to: ${traceFilePath} - > Open this file in chrome://tracing -`); + return jsonStr; } -/** - * @param {!string} msg - */ -function printErrorAndQuit(msg) { - // eslint-disable-next-line no-console - console.error(`ERROR: - > ${msg} - > Example: - > yarn timing results.json - `) - process.exit(1); -}; - -/** - * Takes filename of LHR object. The primary entrypoint on CLI - */ -function saveTraceFromCLI() { - if (!process.argv[2]) { - printErrorAndQuit('Lighthouse JSON results path not provided'); - } - const filename = path.resolve(process.cwd(), process.argv[2]); - if (!fs.existsSync(filename)) { - printErrorAndQuit('Lighthouse JSON results not found.'); - } - const lhrObject = JSON.parse(fs.readFileSync(filename, 'utf8')); - const traceFilePath = `${filename}.run-timing.trace.json`; - const gatherEvents = generateTraceEvents(lhrObject.timing.gatherEntries, 'gather'); - const events = generateTraceEvents(lhrObject.timing.entries); - saveTraceOfEvents([...gatherEvents, ...events], traceFilePath); -} +module.exports = {generateTraceEvents, createTraceString}; -if (require.main === module) { - saveTraceFromCLI(); -} else { - module.exports = {generateTraceEvents, saveTraceOfEvents, saveTraceFromCLI}; -} diff --git a/lighthouse-core/scripts/generate-timing-trace.js b/lighthouse-core/scripts/generate-timing-trace.js new file mode 100644 index 000000000000..d46873490992 --- /dev/null +++ b/lighthouse-core/scripts/generate-timing-trace.js @@ -0,0 +1,49 @@ +/** + * @license Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + */ +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const {createTraceString} = require('../lib/timing-trace-saver'); + +/** + * @param {!string} msg + */ +function printErrorAndQuit(msg) { + // eslint-disable-next-line no-console + console.error(`ERROR: + > ${msg} + > Example: + > yarn timing results.json + `) + process.exit(1); +}; + +/** + * Takes filename of LHR object. The primary entrypoint on CLI + */ +function saveTraceFromCLI() { + if (!process.argv[2]) { + printErrorAndQuit('Lighthouse JSON results path not provided'); + } + const filename = path.resolve(process.cwd(), process.argv[2]); + if (!fs.existsSync(filename)) { + printErrorAndQuit('Lighthouse JSON results not found.'); + } + + const lhrObject = JSON.parse(fs.readFileSync(filename, 'utf8')); + const jsonStr = createTraceString(lhrObject); + + const traceFilePath = `${filename}.run-timing.trace.json`; + fs.writeFileSync(traceFilePath, jsonStr, 'utf8'); + // eslint-disable-next-line no-console + console.log(` + > Timing trace file saved to: ${traceFilePath} + > Open this file in chrome://tracing +`); +} + +saveTraceFromCLI(); diff --git a/lighthouse-core/test/results/artifacts/artifacts.json b/lighthouse-core/test/results/artifacts/artifacts.json index 471ce90596c9..71815e46bd05 100644 --- a/lighthouse-core/test/results/artifacts/artifacts.json +++ b/lighthouse-core/test/results/artifacts/artifacts.json @@ -6,6 +6,7 @@ "requestedUrl": "http://localhost:10200/dobetterweb/dbw_tester.html", "finalUrl": "http://localhost:10200/dobetterweb/dbw_tester.html" }, + "Timing": {}, "Scripts": { "75994.10": "/**\n * @license Copyright 2016 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.\n */\n\n/*eslint-disable*/\n\n(function() {\n\nconst params = new URLSearchParams(location.search);\n\nif (location.search === '' || params.has('dateNow')) {\n // FAIL - Date.now() usage in another file.\n const d = Date.now();\n}\n\nif (location.search === '' || params.has('mutationEvents')) {\n // FAIL - MutationEvent usage in another file.\n document.addEventListener('DOMNodeInserted', function(e) {\n console.log('DOMNodeInserted');\n });\n}\n\nif (location.search === '' || params.has('passiveEvents')) {\n // FAIL - non-passive listener usage in another file.\n document.addEventListener('wheel', e => {\n console.log('wheel: arrow function');\n });\n}\n\nif (location.search === '' || params.has('deprecations')) {\n const div = document.createElement('div');\n div.createShadowRoot();\n // FAIL(errors-in-console) - multiple shadow v0 roots.\n // TODO: disabled until m64 is stable (when moved from deprecation warning to error)\n // div.createShadowRoot();\n}\n\n})();\n", "75994.21": "/**\n* @license\n* Copyright Google Inc. All Rights Reserved.\n*\n* Use of this source code is governed by an MIT-style license that can be\n* found in the LICENSE file at https://angular.io/license\n*/\n(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? factory() :\n typeof define === 'function' && define.amd ? define(factory) :\n (factory());\n}(this, (function () { 'use strict';\n\n/**\n * @license\n * Copyright Google Inc. All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.io/license\n */\n\n\nvar Zone$1 = (function (global) {\n if (global['Zone']) {\n throw new Error('Zone already loaded.');\n }\n var Zone = (function () {\n function Zone(parent, zoneSpec) {\n this._properties = null;\n this._parent = parent;\n this._name = zoneSpec ? zoneSpec.name || 'unnamed' : '';\n this._properties = zoneSpec && zoneSpec.properties || {};\n this._zoneDelegate =\n new ZoneDelegate(this, this._parent && this._parent._zoneDelegate, zoneSpec);\n }\n Zone.assertZonePatched = function () {\n if (global.Promise !== ZoneAwarePromise) {\n throw new Error('Zone.js has detected that ZoneAwarePromise `(window|global).Promise` ' +\n 'has been overwritten.\\n' +\n 'Most likely cause is that a Promise polyfill has been loaded ' +\n 'after Zone.js (Polyfilling Promise api is not necessary when zone.js is loaded. ' +\n 'If you must load one, do so before loading zone.js.)');\n }\n };\n Object.defineProperty(Zone, \"current\", {\n get: function () {\n return _currentZoneFrame.zone;\n },\n enumerable: true,\n configurable: true\n });\n \n Object.defineProperty(Zone, \"currentTask\", {\n get: function () {\n return _currentTask;\n },\n enumerable: true,\n configurable: true\n });\n \n Object.defineProperty(Zone.prototype, \"parent\", {\n get: function () {\n return this._parent;\n },\n enumerable: true,\n configurable: true\n });\n \n Object.defineProperty(Zone.prototype, \"name\", {\n get: function () {\n return this._name;\n },\n enumerable: true,\n configurable: true\n });\n \n Zone.prototype.get = function (key) {\n var zone = this.getZoneWith(key);\n if (zone)\n return zone._properties[key];\n };\n Zone.prototype.getZoneWith = function (key) {\n var current = this;\n while (current) {\n if (current._properties.hasOwnProperty(key)) {\n return current;\n }\n current = current._parent;\n }\n return null;\n };\n Zone.prototype.fork = function (zoneSpec) {\n if (!zoneSpec)\n throw new Error('ZoneSpec required!');\n return this._zoneDelegate.fork(this, zoneSpec);\n };\n Zone.prototype.wrap = function (callback, source) {\n if (typeof callback !== 'function') {\n throw new Error('Expecting function got: ' + callback);\n }\n var _callback = this._zoneDelegate.intercept(this, callback, source);\n var zone = this;\n return function () {\n return zone.runGuarded(_callback, this, arguments, source);\n };\n };\n Zone.prototype.run = function (callback, applyThis, applyArgs, source) {\n if (applyThis === void 0) { applyThis = null; }\n if (applyArgs === void 0) { applyArgs = null; }\n if (source === void 0) { source = null; }\n _currentZoneFrame = new ZoneFrame(_currentZoneFrame, this);\n try {\n return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source);\n }\n finally {\n _currentZoneFrame = _currentZoneFrame.parent;\n }\n };\n Zone.prototype.runGuarded = function (callback, applyThis, applyArgs, source) {\n if (applyThis === void 0) { applyThis = null; }\n if (applyArgs === void 0) { applyArgs = null; }\n if (source === void 0) { source = null; }\n _currentZoneFrame = new ZoneFrame(_currentZoneFrame, this);\n try {\n try {\n return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source);\n }\n catch (error) {\n if (this._zoneDelegate.handleError(this, error)) {\n throw error;\n }\n }\n }\n finally {\n _currentZoneFrame = _currentZoneFrame.parent;\n }\n };\n Zone.prototype.runTask = function (task, applyThis, applyArgs) {\n task.runCount++;\n if (task.zone != this)\n throw new Error('A task can only be run in the zone which created it! (Creation: ' + task.zone.name +\n '; Execution: ' + this.name + ')');\n var previousTask = _currentTask;\n _currentTask = task;\n _currentZoneFrame = new ZoneFrame(_currentZoneFrame, this);\n try {\n if (task.type == 'macroTask' && task.data && !task.data.isPeriodic) {\n task.cancelFn = null;\n }\n try {\n return this._zoneDelegate.invokeTask(this, task, applyThis, applyArgs);\n }\n catch (error) {\n if (this._zoneDelegate.handleError(this, error)) {\n throw error;\n }\n }\n }\n finally {\n _currentZoneFrame = _currentZoneFrame.parent;\n _currentTask = previousTask;\n }\n };\n Zone.prototype.scheduleMicroTask = function (source, callback, data, customSchedule) {\n return this._zoneDelegate.scheduleTask(this, new ZoneTask('microTask', this, source, callback, data, customSchedule, null));\n };\n Zone.prototype.scheduleMacroTask = function (source, callback, data, customSchedule, customCancel) {\n return this._zoneDelegate.scheduleTask(this, new ZoneTask('macroTask', this, source, callback, data, customSchedule, customCancel));\n };\n Zone.prototype.scheduleEventTask = function (source, callback, data, customSchedule, customCancel) {\n return this._zoneDelegate.scheduleTask(this, new ZoneTask('eventTask', this, source, callback, data, customSchedule, customCancel));\n };\n Zone.prototype.cancelTask = function (task) {\n var value = this._zoneDelegate.cancelTask(this, task);\n task.runCount = -1;\n task.cancelFn = null;\n return value;\n };\n Zone.__symbol__ = __symbol__;\n return Zone;\n }());\n \n var ZoneDelegate = (function () {\n function ZoneDelegate(zone, parentDelegate, zoneSpec) {\n this._taskCounts = { microTask: 0, macroTask: 0, eventTask: 0 };\n this.zone = zone;\n this._parentDelegate = parentDelegate;\n this._forkZS = zoneSpec && (zoneSpec && zoneSpec.onFork ? zoneSpec : parentDelegate._forkZS);\n this._forkDlgt = zoneSpec && (zoneSpec.onFork ? parentDelegate : parentDelegate._forkDlgt);\n this._forkCurrZone = zoneSpec && (zoneSpec.onFork ? this.zone : parentDelegate.zone);\n this._interceptZS =\n zoneSpec && (zoneSpec.onIntercept ? zoneSpec : parentDelegate._interceptZS);\n this._interceptDlgt =\n zoneSpec && (zoneSpec.onIntercept ? parentDelegate : parentDelegate._interceptDlgt);\n this._interceptCurrZone =\n zoneSpec && (zoneSpec.onIntercept ? this.zone : parentDelegate.zone);\n this._invokeZS = zoneSpec && (zoneSpec.onInvoke ? zoneSpec : parentDelegate._invokeZS);\n this._invokeDlgt =\n zoneSpec && (zoneSpec.onInvoke ? parentDelegate : parentDelegate._invokeDlgt);\n this._invokeCurrZone = zoneSpec && (zoneSpec.onInvoke ? this.zone : parentDelegate.zone);\n this._handleErrorZS =\n zoneSpec && (zoneSpec.onHandleError ? zoneSpec : parentDelegate._handleErrorZS);\n this._handleErrorDlgt =\n zoneSpec && (zoneSpec.onHandleError ? parentDelegate : parentDelegate._handleErrorDlgt);\n this._handleErrorCurrZone =\n zoneSpec && (zoneSpec.onHandleError ? this.zone : parentDelegate.zone);\n this._scheduleTaskZS =\n zoneSpec && (zoneSpec.onScheduleTask ? zoneSpec : parentDelegate._scheduleTaskZS);\n this._scheduleTaskDlgt =\n zoneSpec && (zoneSpec.onScheduleTask ? parentDelegate : parentDelegate._scheduleTaskDlgt);\n this._scheduleTaskCurrZone =\n zoneSpec && (zoneSpec.onScheduleTask ? this.zone : parentDelegate.zone);\n this._invokeTaskZS =\n zoneSpec && (zoneSpec.onInvokeTask ? zoneSpec : parentDelegate._invokeTaskZS);\n this._invokeTaskDlgt =\n zoneSpec && (zoneSpec.onInvokeTask ? parentDelegate : parentDelegate._invokeTaskDlgt);\n this._invokeTaskCurrZone =\n zoneSpec && (zoneSpec.onInvokeTask ? this.zone : parentDelegate.zone);\n this._cancelTaskZS =\n zoneSpec && (zoneSpec.onCancelTask ? zoneSpec : parentDelegate._cancelTaskZS);\n this._cancelTaskDlgt =\n zoneSpec && (zoneSpec.onCancelTask ? parentDelegate : parentDelegate._cancelTaskDlgt);\n this._cancelTaskCurrZone =\n zoneSpec && (zoneSpec.onCancelTask ? this.zone : parentDelegate.zone);\n this._hasTaskZS = zoneSpec && (zoneSpec.onHasTask ? zoneSpec : parentDelegate._hasTaskZS);\n this._hasTaskDlgt =\n zoneSpec && (zoneSpec.onHasTask ? parentDelegate : parentDelegate._hasTaskDlgt);\n this._hasTaskCurrZone = zoneSpec && (zoneSpec.onHasTask ? this.zone : parentDelegate.zone);\n }\n ZoneDelegate.prototype.fork = function (targetZone, zoneSpec) {\n return this._forkZS ? this._forkZS.onFork(this._forkDlgt, this.zone, targetZone, zoneSpec) :\n new Zone(targetZone, zoneSpec);\n };\n ZoneDelegate.prototype.intercept = function (targetZone, callback, source) {\n return this._interceptZS ?\n this._interceptZS.onIntercept(this._interceptDlgt, this._interceptCurrZone, targetZone, callback, source) :\n callback;\n };\n ZoneDelegate.prototype.invoke = function (targetZone, callback, applyThis, applyArgs, source) {\n return this._invokeZS ?\n this._invokeZS.onInvoke(this._invokeDlgt, this._invokeCurrZone, targetZone, callback, applyThis, applyArgs, source) :\n callback.apply(applyThis, applyArgs);\n };\n ZoneDelegate.prototype.handleError = function (targetZone, error) {\n return this._handleErrorZS ?\n this._handleErrorZS.onHandleError(this._handleErrorDlgt, this._handleErrorCurrZone, targetZone, error) :\n true;\n };\n ZoneDelegate.prototype.scheduleTask = function (targetZone, task) {\n try {\n if (this._scheduleTaskZS) {\n return this._scheduleTaskZS.onScheduleTask(this._scheduleTaskDlgt, this._scheduleTaskCurrZone, targetZone, task);\n }\n else if (task.scheduleFn) {\n task.scheduleFn(task);\n }\n else if (task.type == 'microTask') {\n scheduleMicroTask(task);\n }\n else {\n throw new Error('Task is missing scheduleFn.');\n }\n return task;\n }\n finally {\n if (targetZone == this.zone) {\n this._updateTaskCount(task.type, 1);\n }\n }\n };\n ZoneDelegate.prototype.invokeTask = function (targetZone, task, applyThis, applyArgs) {\n try {\n return this._invokeTaskZS ?\n this._invokeTaskZS.onInvokeTask(this._invokeTaskDlgt, this._invokeTaskCurrZone, targetZone, task, applyThis, applyArgs) :\n task.callback.apply(applyThis, applyArgs);\n }\n finally {\n if (targetZone == this.zone && (task.type != 'eventTask') &&\n !(task.data && task.data.isPeriodic)) {\n this._updateTaskCount(task.type, -1);\n }\n }\n };\n ZoneDelegate.prototype.cancelTask = function (targetZone, task) {\n var value;\n if (this._cancelTaskZS) {\n value = this._cancelTaskZS.onCancelTask(this._cancelTaskDlgt, this._cancelTaskCurrZone, targetZone, task);\n }\n else if (!task.cancelFn) {\n throw new Error('Task does not support cancellation, or is already canceled.');\n }\n else {\n value = task.cancelFn(task);\n }\n if (targetZone == this.zone) {\n // this should not be in the finally block, because exceptions assume not canceled.\n this._updateTaskCount(task.type, -1);\n }\n return value;\n };\n ZoneDelegate.prototype.hasTask = function (targetZone, isEmpty) {\n return this._hasTaskZS &&\n this._hasTaskZS.onHasTask(this._hasTaskDlgt, this._hasTaskCurrZone, targetZone, isEmpty);\n };\n ZoneDelegate.prototype._updateTaskCount = function (type, count) {\n var counts = this._taskCounts;\n var prev = counts[type];\n var next = counts[type] = prev + count;\n if (next < 0) {\n throw new Error('More tasks executed then were scheduled.');\n }\n if (prev == 0 || next == 0) {\n var isEmpty = {\n microTask: counts.microTask > 0,\n macroTask: counts.macroTask > 0,\n eventTask: counts.eventTask > 0,\n change: type\n };\n try {\n this.hasTask(this.zone, isEmpty);\n }\n finally {\n if (this._parentDelegate) {\n this._parentDelegate._updateTaskCount(type, count);\n }\n }\n }\n };\n return ZoneDelegate;\n }());\n var ZoneTask = (function () {\n function ZoneTask(type, zone, source, callback, options, scheduleFn, cancelFn) {\n this.runCount = 0;\n this.type = type;\n this.zone = zone;\n this.source = source;\n this.data = options;\n this.scheduleFn = scheduleFn;\n this.cancelFn = cancelFn;\n this.callback = callback;\n var self = this;\n this.invoke = function () {\n _numberOfNestedTaskFrames++;\n try {\n return zone.runTask(self, this, arguments);\n }\n finally {\n if (_numberOfNestedTaskFrames == 1) {\n drainMicroTaskQueue();\n }\n _numberOfNestedTaskFrames--;\n }\n };\n }\n ZoneTask.prototype.toString = function () {\n if (this.data && typeof this.data.handleId !== 'undefined') {\n return this.data.handleId;\n }\n else {\n return Object.prototype.toString.call(this);\n }\n };\n return ZoneTask;\n }());\n var ZoneFrame = (function () {\n function ZoneFrame(parent, zone) {\n this.parent = parent;\n this.zone = zone;\n }\n return ZoneFrame;\n }());\n function __symbol__(name) {\n return '__zone_symbol__' + name;\n }\n \n var symbolSetTimeout = __symbol__('setTimeout');\n var symbolPromise = __symbol__('Promise');\n var symbolThen = __symbol__('then');\n var _currentZoneFrame = new ZoneFrame(null, new Zone(null, null));\n var _currentTask = null;\n var _microTaskQueue = [];\n var _isDrainingMicrotaskQueue = false;\n var _uncaughtPromiseErrors = [];\n var _numberOfNestedTaskFrames = 0;\n function scheduleQueueDrain() {\n // if we are not running in any task, and there has not been anything scheduled\n // we must bootstrap the initial task creation by manually scheduling the drain\n if (_numberOfNestedTaskFrames === 0 && _microTaskQueue.length === 0) {\n // We are not running in Task, so we need to kickstart the microtask queue.\n if (global[symbolPromise]) {\n global[symbolPromise].resolve(0)[symbolThen](drainMicroTaskQueue);\n }\n else {\n global[symbolSetTimeout](drainMicroTaskQueue, 0);\n }\n }\n }\n function scheduleMicroTask(task) {\n scheduleQueueDrain();\n _microTaskQueue.push(task);\n }\n function consoleError(e) {\n var rejection = e && e.rejection;\n if (rejection) {\n console.error('Unhandled Promise rejection:', rejection instanceof Error ? rejection.message : rejection, '; Zone:', e.zone.name, '; Task:', e.task && e.task.source, '; Value:', rejection, rejection instanceof Error ? rejection.stack : undefined);\n }\n console.error(e);\n }\n function drainMicroTaskQueue() {\n if (!_isDrainingMicrotaskQueue) {\n _isDrainingMicrotaskQueue = true;\n while (_microTaskQueue.length) {\n var queue = _microTaskQueue;\n _microTaskQueue = [];\n for (var i = 0; i < queue.length; i++) {\n var task = queue[i];\n try {\n task.zone.runTask(task, null, null);\n }\n catch (e) {\n consoleError(e);\n }\n }\n }\n while (_uncaughtPromiseErrors.length) {\n var _loop_1 = function() {\n var uncaughtPromiseError = _uncaughtPromiseErrors.shift();\n try {\n uncaughtPromiseError.zone.runGuarded(function () {\n throw uncaughtPromiseError;\n });\n }\n catch (e) {\n consoleError(e);\n }\n };\n while (_uncaughtPromiseErrors.length) {\n _loop_1();\n }\n }\n _isDrainingMicrotaskQueue = false;\n }\n }\n function isThenable(value) {\n return value && value.then;\n }\n function forwardResolution(value) {\n return value;\n }\n function forwardRejection(rejection) {\n return ZoneAwarePromise.reject(rejection);\n }\n var symbolState = __symbol__('state');\n var symbolValue = __symbol__('value');\n var source = 'Promise.then';\n var UNRESOLVED = null;\n var RESOLVED = true;\n var REJECTED = false;\n var REJECTED_NO_CATCH = 0;\n function makeResolver(promise, state) {\n return function (v) {\n resolvePromise(promise, state, v);\n // Do not return value or you will break the Promise spec.\n };\n }\n function resolvePromise(promise, state, value) {\n if (promise[symbolState] === UNRESOLVED) {\n if (value instanceof ZoneAwarePromise && value.hasOwnProperty(symbolState) &&\n value.hasOwnProperty(symbolValue) && value[symbolState] !== UNRESOLVED) {\n clearRejectedNoCatch(value);\n resolvePromise(promise, value[symbolState], value[symbolValue]);\n }\n else if (isThenable(value)) {\n value.then(makeResolver(promise, state), makeResolver(promise, false));\n }\n else {\n promise[symbolState] = state;\n var queue = promise[symbolValue];\n promise[symbolValue] = value;\n for (var i = 0; i < queue.length;) {\n scheduleResolveOrReject(promise, queue[i++], queue[i++], queue[i++], queue[i++]);\n }\n if (queue.length == 0 && state == REJECTED) {\n promise[symbolState] = REJECTED_NO_CATCH;\n try {\n throw new Error('Uncaught (in promise): ' + value +\n (value && value.stack ? '\\n' + value.stack : ''));\n }\n catch (e) {\n var error_1 = e;\n error_1.rejection = value;\n error_1.promise = promise;\n error_1.zone = Zone.current;\n error_1.task = Zone.currentTask;\n _uncaughtPromiseErrors.push(error_1);\n scheduleQueueDrain();\n }\n }\n }\n }\n // Resolving an already resolved promise is a noop.\n return promise;\n }\n function clearRejectedNoCatch(promise) {\n if (promise[symbolState] === REJECTED_NO_CATCH) {\n promise[symbolState] = REJECTED;\n for (var i = 0; i < _uncaughtPromiseErrors.length; i++) {\n if (promise === _uncaughtPromiseErrors[i].promise) {\n _uncaughtPromiseErrors.splice(i, 1);\n break;\n }\n }\n }\n }\n function scheduleResolveOrReject(promise, zone, chainPromise, onFulfilled, onRejected) {\n clearRejectedNoCatch(promise);\n var delegate = promise[symbolState] ? onFulfilled || forwardResolution : onRejected || forwardRejection;\n zone.scheduleMicroTask(source, function () {\n try {\n resolvePromise(chainPromise, true, zone.run(delegate, null, [promise[symbolValue]]));\n }\n catch (error) {\n resolvePromise(chainPromise, false, error);\n }\n });\n }\n var ZoneAwarePromise = (function () {\n function ZoneAwarePromise(executor) {\n var promise = this;\n if (!(promise instanceof ZoneAwarePromise)) {\n throw new Error('Must be an instanceof Promise.');\n }\n promise[symbolState] = UNRESOLVED;\n promise[symbolValue] = []; // queue;\n try {\n executor && executor(makeResolver(promise, RESOLVED), makeResolver(promise, REJECTED));\n }\n catch (e) {\n resolvePromise(promise, false, e);\n }\n }\n ZoneAwarePromise.resolve = function (value) {\n return resolvePromise(new this(null), RESOLVED, value);\n };\n ZoneAwarePromise.reject = function (error) {\n return resolvePromise(new this(null), REJECTED, error);\n };\n ZoneAwarePromise.race = function (values) {\n var resolve;\n var reject;\n var promise = new this(function (res, rej) {\n _a = [res, rej], resolve = _a[0], reject = _a[1];\n var _a;\n });\n function onResolve(value) {\n promise && (promise = null || resolve(value));\n }\n function onReject(error) {\n promise && (promise = null || reject(error));\n }\n for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {\n var value = values_1[_i];\n if (!isThenable(value)) {\n value = this.resolve(value);\n }\n value.then(onResolve, onReject);\n }\n return promise;\n };\n ZoneAwarePromise.all = function (values) {\n var resolve;\n var reject;\n var promise = new this(function (res, rej) {\n resolve = res;\n reject = rej;\n });\n var count = 0;\n var resolvedValues = [];\n for (var _i = 0, values_2 = values; _i < values_2.length; _i++) {\n var value = values_2[_i];\n if (!isThenable(value)) {\n value = this.resolve(value);\n }\n value.then((function (index) { return function (value) {\n resolvedValues[index] = value;\n count--;\n if (!count) {\n resolve(resolvedValues);\n }\n }; })(count), reject);\n count++;\n }\n if (!count)\n resolve(resolvedValues);\n return promise;\n };\n ZoneAwarePromise.prototype.then = function (onFulfilled, onRejected) {\n var chainPromise = new this.constructor(null);\n var zone = Zone.current;\n if (this[symbolState] == UNRESOLVED) {\n this[symbolValue].push(zone, chainPromise, onFulfilled, onRejected);\n }\n else {\n scheduleResolveOrReject(this, zone, chainPromise, onFulfilled, onRejected);\n }\n return chainPromise;\n };\n ZoneAwarePromise.prototype.catch = function (onRejected) {\n return this.then(null, onRejected);\n };\n return ZoneAwarePromise;\n }());\n // Protect against aggressive optimizers dropping seemingly unused properties.\n // E.g. Closure Compiler in advanced mode.\n ZoneAwarePromise['resolve'] = ZoneAwarePromise.resolve;\n ZoneAwarePromise['reject'] = ZoneAwarePromise.reject;\n ZoneAwarePromise['race'] = ZoneAwarePromise.race;\n ZoneAwarePromise['all'] = ZoneAwarePromise.all;\n var NativePromise = global[__symbol__('Promise')] = global['Promise'];\n global['Promise'] = ZoneAwarePromise;\n function patchThen(NativePromise) {\n var NativePromiseProtototype = NativePromise.prototype;\n var NativePromiseThen = NativePromiseProtototype[__symbol__('then')] =\n NativePromiseProtototype.then;\n NativePromiseProtototype.then = function (onResolve, onReject) {\n var nativePromise = this;\n return new ZoneAwarePromise(function (resolve, reject) {\n NativePromiseThen.call(nativePromise, resolve, reject);\n })\n .then(onResolve, onReject);\n };\n }\n if (NativePromise) {\n patchThen(NativePromise);\n if (typeof global['fetch'] !== 'undefined') {\n var fetchPromise = void 0;\n try {\n // In MS Edge this throws\n fetchPromise = global['fetch']();\n }\n catch (e) {\n // In Chrome this throws instead.\n fetchPromise = global['fetch']('about:blank');\n }\n // ignore output to prevent error;\n fetchPromise.then(function () { return null; }, function () { return null; });\n if (fetchPromise.constructor != NativePromise &&\n fetchPromise.constructor != ZoneAwarePromise) {\n patchThen(fetchPromise.constructor);\n }\n }\n }\n // This is not part of public API, but it is usefull for tests, so we expose it.\n Promise[Zone.__symbol__('uncaughtPromiseErrors')] = _uncaughtPromiseErrors;\n /*\n * This code patches Error so that:\n * - It ignores un-needed stack frames.\n * - It Shows the associated Zone for reach frame.\n */\n var FrameType;\n (function (FrameType) {\n /// Skip this frame when printing out stack\n FrameType[FrameType[\"blackList\"] = 0] = \"blackList\";\n /// This frame marks zone transition\n FrameType[FrameType[\"transition\"] = 1] = \"transition\";\n })(FrameType || (FrameType = {}));\n var NativeError = global[__symbol__('Error')] = global.Error;\n // Store the frames which should be removed from the stack frames\n var blackListedStackFrames = {};\n // We must find the frame where Error was created, otherwise we assume we don't understand stack\n var zoneAwareFrame;\n global.Error = ZoneAwareError;\n // How should the stack frames be parsed.\n var frameParserStrategy = null;\n var stackRewrite = 'stackRewrite';\n /**\n * This is ZoneAwareError which processes the stack frame and cleans up extra frames as well as\n * adds zone information to it.\n */\n function ZoneAwareError() {\n // Create an Error.\n var error = NativeError.apply(this, arguments);\n this.message = error.message;\n // Save original stack trace\n this.originalStack = error.stack;\n // Process the stack trace and rewrite the frames.\n if (ZoneAwareError[stackRewrite] && this.originalStack) {\n var frames_1 = this.originalStack.split('\\n');\n var zoneFrame = _currentZoneFrame;\n var i = 0;\n // Find the first frame\n while (frames_1[i] !== zoneAwareFrame && i < frames_1.length) {\n i++;\n }\n for (; i < frames_1.length && zoneFrame; i++) {\n var frame = frames_1[i];\n if (frame.trim()) {\n var frameType = blackListedStackFrames.hasOwnProperty(frame) && blackListedStackFrames[frame];\n if (frameType === FrameType.blackList) {\n frames_1.splice(i, 1);\n i--;\n }\n else if (frameType === FrameType.transition) {\n if (zoneFrame.parent) {\n // This is the special frame where zone changed. Print and process it accordingly\n frames_1[i] += \" [\" + zoneFrame.parent.zone.name + \" => \" + zoneFrame.zone.name + \"]\";\n zoneFrame = zoneFrame.parent;\n }\n else {\n zoneFrame = null;\n }\n }\n else {\n frames_1[i] += \" [\" + zoneFrame.zone.name + \"]\";\n }\n }\n }\n this.stack = this.zoneAwareStack = frames_1.join('\\n');\n }\n }\n \n // Copy the prototype so that instanceof operator works as expected\n ZoneAwareError.prototype = Object.create(NativeError.prototype);\n ZoneAwareError[Zone.__symbol__('blacklistedStackFrames')] = blackListedStackFrames;\n ZoneAwareError[stackRewrite] = false;\n if (NativeError.hasOwnProperty('stackTraceLimit')) {\n // Extend default stack limit as we will be removing few frames.\n NativeError.stackTraceLimit = Math.max(NativeError.stackTraceLimit, 15);\n // make sure that ZoneAwareError has the same property which forwards to NativeError.\n Object.defineProperty(ZoneAwareError, 'stackTraceLimit', {\n get: function () {\n return NativeError.stackTraceLimit;\n },\n set: function (value) {\n return NativeError.stackTraceLimit = value;\n }\n });\n }\n if (NativeError.hasOwnProperty('captureStackTrace')) {\n Object.defineProperty(ZoneAwareError, 'captureStackTrace', {\n value: function (targetObject, constructorOpt) {\n NativeError.captureStackTrace(targetObject, constructorOpt);\n }\n });\n }\n Object.defineProperty(ZoneAwareError, 'prepareStackTrace', {\n get: function () {\n return NativeError.prepareStackTrace;\n },\n set: function (value) {\n return NativeError.prepareStackTrace = value;\n }\n });\n // Now we need to populet the `blacklistedStackFrames` as well as find the\n // Now we need to populet the `blacklistedStackFrames` as well as find the\n // run/runGuraded/runTask frames. This is done by creating a detect zone and then threading\n // the execution through all of the above methods so that we can look at the stack trace and\n // find the frames of interest.\n var detectZone = Zone.current.fork({\n name: 'detect',\n onInvoke: function (parentZoneDelegate, currentZone, targetZone, delegate, applyThis, applyArgs, source) {\n // Here only so that it will show up in the stack frame so that it can be black listed.\n return parentZoneDelegate.invoke(targetZone, delegate, applyThis, applyArgs, source);\n },\n onHandleError: function (parentZD, current, target, error) {\n if (error.originalStack && Error === ZoneAwareError) {\n var frames_2 = error.originalStack.split(/\\n/);\n var runFrame = false, runGuardedFrame = false, runTaskFrame = false;\n while (frames_2.length) {\n var frame = frames_2.shift();\n // On safari it is possible to have stack frame with no line number.\n // This check makes sure that we don't filter frames on name only (must have\n // linenumber)\n if (/:\\d+:\\d+/.test(frame)) {\n // Get rid of the path so that we don't accidintely find function name in path.\n // In chrome the seperator is `(` and `@` in FF and safari\n // Chrome: at Zone.run (zone.js:100)\n // Chrome: at Zone.run (http://localhost:9876/base/build/lib/zone.js:100:24)\n // FireFox: Zone.prototype.run@http://localhost:9876/base/build/lib/zone.js:101:24\n // Safari: run@http://localhost:9876/base/build/lib/zone.js:101:24\n var fnName = frame.split('(')[0].split('@')[0];\n var frameType = FrameType.transition;\n if (fnName.indexOf('ZoneAwareError') !== -1) {\n zoneAwareFrame = frame;\n }\n if (fnName.indexOf('runGuarded') !== -1) {\n runGuardedFrame = true;\n }\n else if (fnName.indexOf('runTask') !== -1) {\n runTaskFrame = true;\n }\n else if (fnName.indexOf('run') !== -1) {\n runFrame = true;\n }\n else {\n frameType = FrameType.blackList;\n }\n blackListedStackFrames[frame] = frameType;\n // Once we find all of the frames we can stop looking.\n if (runFrame && runGuardedFrame && runTaskFrame) {\n ZoneAwareError[stackRewrite] = true;\n break;\n }\n }\n }\n }\n return false;\n }\n });\n // carefully constructor a stack frame which contains all of the frames of interest which\n // need to be detected and blacklisted.\n var detectRunFn = function () {\n detectZone.run(function () {\n detectZone.runGuarded(function () {\n throw new Error('blacklistStackFrames');\n });\n });\n };\n // Cause the error to extract the stack frames.\n detectZone.runTask(detectZone.scheduleMacroTask('detect', detectRunFn, null, function () { return null; }, null));\n return global['Zone'] = Zone;\n})(typeof window === 'object' && window || typeof self === 'object' && self || global);\n\n/**\n * @license\n * Copyright Google Inc. All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.io/license\n */\nvar zoneSymbol = function (n) { return (\"__zone_symbol__\" + n); };\nvar _global$1 = typeof window === 'object' && window || typeof self === 'object' && self || global;\nfunction bindArguments(args, source) {\n for (var i = args.length - 1; i >= 0; i--) {\n if (typeof args[i] === 'function') {\n args[i] = Zone.current.wrap(args[i], source + '_' + i);\n }\n }\n return args;\n}\nfunction patchPrototype(prototype, fnNames) {\n var source = prototype.constructor['name'];\n var _loop_1 = function(i) {\n var name_1 = fnNames[i];\n var delegate = prototype[name_1];\n if (delegate) {\n prototype[name_1] = (function (delegate) {\n return function () {\n return delegate.apply(this, bindArguments(arguments, source + '.' + name_1));\n };\n })(delegate);\n }\n };\n for (var i = 0; i < fnNames.length; i++) {\n _loop_1(i);\n }\n}\nvar isWebWorker = (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope);\nvar isNode = (!('nw' in _global$1) && typeof process !== 'undefined' &&\n {}.toString.call(process) === '[object process]');\nvar isBrowser = !isNode && !isWebWorker && !!(typeof window !== 'undefined' && window['HTMLElement']);\nfunction patchProperty(obj, prop) {\n var desc = Object.getOwnPropertyDescriptor(obj, prop) || { enumerable: true, configurable: true };\n var originalDesc = Object.getOwnPropertyDescriptor(obj, 'original' + prop);\n if (!originalDesc && desc.get) {\n Object.defineProperty(obj, 'original' + prop, { enumerable: false, configurable: true, get: desc.get });\n }\n // A property descriptor cannot have getter/setter and be writable\n // deleting the writable and value properties avoids this error:\n //\n // TypeError: property descriptors must not specify a value or be writable when a\n // getter or setter has been specified\n delete desc.writable;\n delete desc.value;\n // substr(2) cuz 'onclick' -> 'click', etc\n var eventName = prop.substr(2);\n var _prop = '_' + prop;\n desc.set = function (fn) {\n if (this[_prop]) {\n this.removeEventListener(eventName, this[_prop]);\n }\n if (typeof fn === 'function') {\n var wrapFn = function (event) {\n var result;\n result = fn.apply(this, arguments);\n if (result != undefined && !result)\n event.preventDefault();\n };\n this[_prop] = wrapFn;\n this.addEventListener(eventName, wrapFn, false);\n }\n else {\n this[_prop] = null;\n }\n };\n // The getter would return undefined for unassigned properties but the default value of an\n // unassigned property is null\n desc.get = function () {\n var r = this[_prop] || null;\n // result will be null when use inline event attribute,\n // such as \n // because the onclick function is internal raw uncompiled handler\n // the onclick will be evaluated when first time event was triggered or\n // the property is accessed, https://github.com/angular/zone.js/issues/525\n // so we should use original native get to retrive the handler\n if (r === null) {\n var oriDesc = Object.getOwnPropertyDescriptor(obj, 'original' + prop);\n if (oriDesc && oriDesc.get) {\n r = oriDesc.get.apply(this, arguments);\n if (r) {\n desc.set.apply(this, [r]);\n this.removeAttribute(prop);\n }\n }\n }\n return this[_prop] || null;\n };\n Object.defineProperty(obj, prop, desc);\n}\n\nfunction patchOnProperties(obj, properties) {\n var onProperties = [];\n for (var prop in obj) {\n if (prop.substr(0, 2) == 'on') {\n onProperties.push(prop);\n }\n }\n for (var j = 0; j < onProperties.length; j++) {\n patchProperty(obj, onProperties[j]);\n }\n if (properties) {\n for (var i = 0; i < properties.length; i++) {\n patchProperty(obj, 'on' + properties[i]);\n }\n }\n}\n\nvar EVENT_TASKS = zoneSymbol('eventTasks');\n// For EventTarget\nvar ADD_EVENT_LISTENER = 'addEventListener';\nvar REMOVE_EVENT_LISTENER = 'removeEventListener';\nfunction findExistingRegisteredTask(target, handler, name, capture, remove) {\n var eventTasks = target[EVENT_TASKS];\n if (eventTasks) {\n for (var i = 0; i < eventTasks.length; i++) {\n var eventTask = eventTasks[i];\n var data = eventTask.data;\n var listener = data.handler;\n if ((data.handler === handler || listener.listener === handler) &&\n data.useCapturing === capture && data.eventName === name) {\n if (remove) {\n eventTasks.splice(i, 1);\n }\n return eventTask;\n }\n }\n }\n return null;\n}\nfunction findAllExistingRegisteredTasks(target, name, capture, remove) {\n var eventTasks = target[EVENT_TASKS];\n if (eventTasks) {\n var result = [];\n for (var i = eventTasks.length - 1; i >= 0; i--) {\n var eventTask = eventTasks[i];\n var data = eventTask.data;\n if (data.eventName === name && data.useCapturing === capture) {\n result.push(eventTask);\n if (remove) {\n eventTasks.splice(i, 1);\n }\n }\n }\n return result;\n }\n return null;\n}\nfunction attachRegisteredEvent(target, eventTask, isPrepend) {\n var eventTasks = target[EVENT_TASKS];\n if (!eventTasks) {\n eventTasks = target[EVENT_TASKS] = [];\n }\n if (isPrepend) {\n eventTasks.unshift(eventTask);\n }\n else {\n eventTasks.push(eventTask);\n }\n}\nvar defaultListenerMetaCreator = function (self, args) {\n return {\n useCapturing: args[2],\n eventName: args[0],\n handler: args[1],\n target: self || _global$1,\n name: args[0],\n invokeAddFunc: function (addFnSymbol, delegate) {\n if (delegate && delegate.invoke) {\n return this.target[addFnSymbol](this.eventName, delegate.invoke, this.useCapturing);\n }\n else {\n return this.target[addFnSymbol](this.eventName, delegate, this.useCapturing);\n }\n },\n invokeRemoveFunc: function (removeFnSymbol, delegate) {\n if (delegate && delegate.invoke) {\n return this.target[removeFnSymbol](this.eventName, delegate.invoke, this.useCapturing);\n }\n else {\n return this.target[removeFnSymbol](this.eventName, delegate, this.useCapturing);\n }\n }\n };\n};\nfunction makeZoneAwareAddListener(addFnName, removeFnName, useCapturingParam, allowDuplicates, isPrepend, metaCreator) {\n if (useCapturingParam === void 0) { useCapturingParam = true; }\n if (allowDuplicates === void 0) { allowDuplicates = false; }\n if (isPrepend === void 0) { isPrepend = false; }\n if (metaCreator === void 0) { metaCreator = defaultListenerMetaCreator; }\n var addFnSymbol = zoneSymbol(addFnName);\n var removeFnSymbol = zoneSymbol(removeFnName);\n var defaultUseCapturing = useCapturingParam ? false : undefined;\n function scheduleEventListener(eventTask) {\n var meta = eventTask.data;\n attachRegisteredEvent(meta.target, eventTask, isPrepend);\n return meta.invokeAddFunc(addFnSymbol, eventTask);\n }\n function cancelEventListener(eventTask) {\n var meta = eventTask.data;\n findExistingRegisteredTask(meta.target, eventTask.invoke, meta.eventName, meta.useCapturing, true);\n return meta.invokeRemoveFunc(removeFnSymbol, eventTask);\n }\n return function zoneAwareAddListener(self, args) {\n var data = metaCreator(self, args);\n data.useCapturing = data.useCapturing || defaultUseCapturing;\n // - Inside a Web Worker, `this` is undefined, the context is `global`\n // - When `addEventListener` is called on the global context in strict mode, `this` is undefined\n // see https://github.com/angular/zone.js/issues/190\n var delegate = null;\n if (typeof data.handler == 'function') {\n delegate = data.handler;\n }\n else if (data.handler && data.handler.handleEvent) {\n delegate = function (event) { return data.handler.handleEvent(event); };\n }\n var validZoneHandler = false;\n try {\n // In cross site contexts (such as WebDriver frameworks like Selenium),\n // accessing the handler object here will cause an exception to be thrown which\n // will fail tests prematurely.\n validZoneHandler = data.handler && data.handler.toString() === '[object FunctionWrapper]';\n }\n catch (e) {\n // Returning nothing here is fine, because objects in a cross-site context are unusable\n return;\n }\n // Ignore special listeners of IE11 & Edge dev tools, see\n // https://github.com/angular/zone.js/issues/150\n if (!delegate || validZoneHandler) {\n return data.invokeAddFunc(addFnSymbol, data.handler);\n }\n if (!allowDuplicates) {\n var eventTask = findExistingRegisteredTask(data.target, data.handler, data.eventName, data.useCapturing, false);\n if (eventTask) {\n // we already registered, so this will have noop.\n return data.invokeAddFunc(addFnSymbol, eventTask);\n }\n }\n var zone = Zone.current;\n var source = data.target.constructor['name'] + '.' + addFnName + ':' + data.eventName;\n zone.scheduleEventTask(source, delegate, data, scheduleEventListener, cancelEventListener);\n };\n}\nfunction makeZoneAwareRemoveListener(fnName, useCapturingParam, metaCreator) {\n if (useCapturingParam === void 0) { useCapturingParam = true; }\n if (metaCreator === void 0) { metaCreator = defaultListenerMetaCreator; }\n var symbol = zoneSymbol(fnName);\n var defaultUseCapturing = useCapturingParam ? false : undefined;\n return function zoneAwareRemoveListener(self, args) {\n var data = metaCreator(self, args);\n data.useCapturing = data.useCapturing || defaultUseCapturing;\n // - Inside a Web Worker, `this` is undefined, the context is `global`\n // - When `addEventListener` is called on the global context in strict mode, `this` is undefined\n // see https://github.com/angular/zone.js/issues/190\n var eventTask = findExistingRegisteredTask(data.target, data.handler, data.eventName, data.useCapturing, true);\n if (eventTask) {\n eventTask.zone.cancelTask(eventTask);\n }\n else {\n data.invokeRemoveFunc(symbol, data.handler);\n }\n };\n}\n\n\nvar zoneAwareAddEventListener = makeZoneAwareAddListener(ADD_EVENT_LISTENER, REMOVE_EVENT_LISTENER);\nvar zoneAwareRemoveEventListener = makeZoneAwareRemoveListener(REMOVE_EVENT_LISTENER);\nfunction patchEventTargetMethods(obj, addFnName, removeFnName, metaCreator) {\n if (addFnName === void 0) { addFnName = ADD_EVENT_LISTENER; }\n if (removeFnName === void 0) { removeFnName = REMOVE_EVENT_LISTENER; }\n if (metaCreator === void 0) { metaCreator = defaultListenerMetaCreator; }\n if (obj && obj[addFnName]) {\n patchMethod(obj, addFnName, function () { return makeZoneAwareAddListener(addFnName, removeFnName, true, false, false, metaCreator); });\n patchMethod(obj, removeFnName, function () { return makeZoneAwareRemoveListener(removeFnName, true, metaCreator); });\n return true;\n }\n else {\n return false;\n }\n}\nvar originalInstanceKey = zoneSymbol('originalInstance');\n// wrap some native API on `window`\nfunction patchClass(className) {\n var OriginalClass = _global$1[className];\n if (!OriginalClass)\n return;\n _global$1[className] = function () {\n var a = bindArguments(arguments, className);\n switch (a.length) {\n case 0:\n this[originalInstanceKey] = new OriginalClass();\n break;\n case 1:\n this[originalInstanceKey] = new OriginalClass(a[0]);\n break;\n case 2:\n this[originalInstanceKey] = new OriginalClass(a[0], a[1]);\n break;\n case 3:\n this[originalInstanceKey] = new OriginalClass(a[0], a[1], a[2]);\n break;\n case 4:\n this[originalInstanceKey] = new OriginalClass(a[0], a[1], a[2], a[3]);\n break;\n default:\n throw new Error('Arg list too long.');\n }\n };\n var instance = new OriginalClass(function () { });\n var prop;\n for (prop in instance) {\n // https://bugs.webkit.org/show_bug.cgi?id=44721\n if (className === 'XMLHttpRequest' && prop === 'responseBlob')\n continue;\n (function (prop) {\n if (typeof instance[prop] === 'function') {\n _global$1[className].prototype[prop] = function () {\n return this[originalInstanceKey][prop].apply(this[originalInstanceKey], arguments);\n };\n }\n else {\n Object.defineProperty(_global$1[className].prototype, prop, {\n set: function (fn) {\n if (typeof fn === 'function') {\n this[originalInstanceKey][prop] = Zone.current.wrap(fn, className + '.' + prop);\n }\n else {\n this[originalInstanceKey][prop] = fn;\n }\n },\n get: function () {\n return this[originalInstanceKey][prop];\n }\n });\n }\n }(prop));\n }\n for (prop in OriginalClass) {\n if (prop !== 'prototype' && OriginalClass.hasOwnProperty(prop)) {\n _global$1[className][prop] = OriginalClass[prop];\n }\n }\n}\n\nfunction createNamedFn(name, delegate) {\n try {\n return (Function('f', \"return function \" + name + \"(){return f(this, arguments)}\"))(delegate);\n }\n catch (e) {\n // if we fail, we must be CSP, just return delegate.\n return function () {\n return delegate(this, arguments);\n };\n }\n}\nfunction patchMethod(target, name, patchFn) {\n var proto = target;\n while (proto && Object.getOwnPropertyNames(proto).indexOf(name) === -1) {\n proto = Object.getPrototypeOf(proto);\n }\n if (!proto && target[name]) {\n // somehow we did not find it, but we can see it. This happens on IE for Window properties.\n proto = target;\n }\n var delegateName = zoneSymbol(name);\n var delegate;\n if (proto && !(delegate = proto[delegateName])) {\n delegate = proto[delegateName] = proto[name];\n proto[name] = createNamedFn(name, patchFn(delegate, delegateName, name));\n }\n return delegate;\n}\n\n/**\n * @license\n * Copyright Google Inc. All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.io/license\n */\nfunction patchTimer(window, setName, cancelName, nameSuffix) {\n var setNative = null;\n var clearNative = null;\n setName += nameSuffix;\n cancelName += nameSuffix;\n var tasksByHandleId = {};\n function scheduleTask(task) {\n var data = task.data;\n data.args[0] = function () {\n task.invoke.apply(this, arguments);\n delete tasksByHandleId[data.handleId];\n };\n data.handleId = setNative.apply(window, data.args);\n tasksByHandleId[data.handleId] = task;\n return task;\n }\n function clearTask(task) {\n delete tasksByHandleId[task.data.handleId];\n return clearNative(task.data.handleId);\n }\n setNative =\n patchMethod(window, setName, function (delegate) { return function (self, args) {\n if (typeof args[0] === 'function') {\n var zone = Zone.current;\n var options = {\n handleId: null,\n isPeriodic: nameSuffix === 'Interval',\n delay: (nameSuffix === 'Timeout' || nameSuffix === 'Interval') ? args[1] || 0 : null,\n args: args\n };\n var task = zone.scheduleMacroTask(setName, args[0], options, scheduleTask, clearTask);\n if (!task) {\n return task;\n }\n // Node.js must additionally support the ref and unref functions.\n var handle = task.data.handleId;\n if (handle.ref && handle.unref) {\n task.ref = handle.ref.bind(handle);\n task.unref = handle.unref.bind(handle);\n }\n return task;\n }\n else {\n // cause an error by calling it directly.\n return delegate.apply(window, args);\n }\n }; });\n clearNative =\n patchMethod(window, cancelName, function (delegate) { return function (self, args) {\n var task = typeof args[0] === 'number' ? tasksByHandleId[args[0]] : args[0];\n if (task && typeof task.type === 'string') {\n if (task.cancelFn && task.data.isPeriodic || task.runCount === 0) {\n // Do not cancel already canceled functions\n task.zone.cancelTask(task);\n }\n }\n else {\n // cause an error by calling it directly.\n delegate.apply(window, args);\n }\n }; });\n}\n\n/**\n * @license\n * Copyright Google Inc. All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.io/license\n */\n/*\n * This is necessary for Chrome and Chrome mobile, to enable\n * things like redefining `createdCallback` on an element.\n */\nvar _defineProperty = Object[zoneSymbol('defineProperty')] = Object.defineProperty;\nvar _getOwnPropertyDescriptor = Object[zoneSymbol('getOwnPropertyDescriptor')] =\n Object.getOwnPropertyDescriptor;\nvar _create = Object.create;\nvar unconfigurablesKey = zoneSymbol('unconfigurables');\nfunction propertyPatch() {\n Object.defineProperty = function (obj, prop, desc) {\n if (isUnconfigurable(obj, prop)) {\n throw new TypeError('Cannot assign to read only property \\'' + prop + '\\' of ' + obj);\n }\n var originalConfigurableFlag = desc.configurable;\n if (prop !== 'prototype') {\n desc = rewriteDescriptor(obj, prop, desc);\n }\n return _tryDefineProperty(obj, prop, desc, originalConfigurableFlag);\n };\n Object.defineProperties = function (obj, props) {\n Object.keys(props).forEach(function (prop) {\n Object.defineProperty(obj, prop, props[prop]);\n });\n return obj;\n };\n Object.create = function (obj, proto) {\n if (typeof proto === 'object' && !Object.isFrozen(proto)) {\n Object.keys(proto).forEach(function (prop) {\n proto[prop] = rewriteDescriptor(obj, prop, proto[prop]);\n });\n }\n return _create(obj, proto);\n };\n Object.getOwnPropertyDescriptor = function (obj, prop) {\n var desc = _getOwnPropertyDescriptor(obj, prop);\n if (isUnconfigurable(obj, prop)) {\n desc.configurable = false;\n }\n return desc;\n };\n}\n\nfunction _redefineProperty(obj, prop, desc) {\n var originalConfigurableFlag = desc.configurable;\n desc = rewriteDescriptor(obj, prop, desc);\n return _tryDefineProperty(obj, prop, desc, originalConfigurableFlag);\n}\n\nfunction isUnconfigurable(obj, prop) {\n return obj && obj[unconfigurablesKey] && obj[unconfigurablesKey][prop];\n}\nfunction rewriteDescriptor(obj, prop, desc) {\n desc.configurable = true;\n if (!desc.configurable) {\n if (!obj[unconfigurablesKey]) {\n _defineProperty(obj, unconfigurablesKey, { writable: true, value: {} });\n }\n obj[unconfigurablesKey][prop] = true;\n }\n return desc;\n}\nfunction _tryDefineProperty(obj, prop, desc, originalConfigurableFlag) {\n try {\n return _defineProperty(obj, prop, desc);\n }\n catch (e) {\n if (desc.configurable) {\n // In case of errors, when the configurable flag was likely set by rewriteDescriptor(), let's\n // retry with the original flag value\n if (typeof originalConfigurableFlag == 'undefined') {\n delete desc.configurable;\n }\n else {\n desc.configurable = originalConfigurableFlag;\n }\n try {\n return _defineProperty(obj, prop, desc);\n }\n catch (e) {\n var descJson = null;\n try {\n descJson = JSON.stringify(desc);\n }\n catch (e) {\n descJson = descJson.toString();\n }\n console.log(\"Attempting to configure '\" + prop + \"' with descriptor '\" + descJson + \"' on object '\" + obj + \"' and got error, giving up: \" + e);\n }\n }\n else {\n throw e;\n }\n }\n}\n\n/**\n * @license\n * Copyright Google Inc. All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.io/license\n */\nvar WTF_ISSUE_555 = 'Anchor,Area,Audio,BR,Base,BaseFont,Body,Button,Canvas,Content,DList,Directory,Div,Embed,FieldSet,Font,Form,Frame,FrameSet,HR,Head,Heading,Html,IFrame,Image,Input,Keygen,LI,Label,Legend,Link,Map,Marquee,Media,Menu,Meta,Meter,Mod,OList,Object,OptGroup,Option,Output,Paragraph,Pre,Progress,Quote,Script,Select,Source,Span,Style,TableCaption,TableCell,TableCol,Table,TableRow,TableSection,TextArea,Title,Track,UList,Unknown,Video';\nvar NO_EVENT_TARGET = 'ApplicationCache,EventSource,FileReader,InputMethodContext,MediaController,MessagePort,Node,Performance,SVGElementInstance,SharedWorker,TextTrack,TextTrackCue,TextTrackList,WebKitNamedFlow,Window,Worker,WorkerGlobalScope,XMLHttpRequest,XMLHttpRequestEventTarget,XMLHttpRequestUpload,IDBRequest,IDBOpenDBRequest,IDBDatabase,IDBTransaction,IDBCursor,DBIndex,WebSocket'\n .split(',');\nvar EVENT_TARGET = 'EventTarget';\nfunction eventTargetPatch(_global) {\n var apis = [];\n var isWtf = _global['wtf'];\n if (isWtf) {\n // Workaround for: https://github.com/google/tracing-framework/issues/555\n apis = WTF_ISSUE_555.split(',').map(function (v) { return 'HTML' + v + 'Element'; }).concat(NO_EVENT_TARGET);\n }\n else if (_global[EVENT_TARGET]) {\n apis.push(EVENT_TARGET);\n }\n else {\n // Note: EventTarget is not available in all browsers,\n // if it's not available, we instead patch the APIs in the IDL that inherit from EventTarget\n apis = NO_EVENT_TARGET;\n }\n for (var i = 0; i < apis.length; i++) {\n var type = _global[apis[i]];\n patchEventTargetMethods(type && type.prototype);\n }\n}\n\n/**\n * @license\n * Copyright Google Inc. All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.io/license\n */\n// we have to patch the instance since the proto is non-configurable\nfunction apply(_global) {\n var WS = _global.WebSocket;\n // On Safari window.EventTarget doesn't exist so need to patch WS add/removeEventListener\n // On older Chrome, no need since EventTarget was already patched\n if (!_global.EventTarget) {\n patchEventTargetMethods(WS.prototype);\n }\n _global.WebSocket = function (a, b) {\n var socket = arguments.length > 1 ? new WS(a, b) : new WS(a);\n var proxySocket;\n // Safari 7.0 has non-configurable own 'onmessage' and friends properties on the socket instance\n var onmessageDesc = Object.getOwnPropertyDescriptor(socket, 'onmessage');\n if (onmessageDesc && onmessageDesc.configurable === false) {\n proxySocket = Object.create(socket);\n ['addEventListener', 'removeEventListener', 'send', 'close'].forEach(function (propName) {\n proxySocket[propName] = function () {\n return socket[propName].apply(socket, arguments);\n };\n });\n }\n else {\n // we can patch the real socket\n proxySocket = socket;\n }\n patchOnProperties(proxySocket, ['close', 'error', 'message', 'open']);\n return proxySocket;\n };\n for (var prop in WS) {\n _global.WebSocket[prop] = WS[prop];\n }\n}\n\n/**\n * @license\n * Copyright Google Inc. All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.io/license\n */\nvar eventNames = 'copy cut paste abort blur focus canplay canplaythrough change click contextmenu dblclick drag dragend dragenter dragleave dragover dragstart drop durationchange emptied ended input invalid keydown keypress keyup load loadeddata loadedmetadata loadstart message mousedown mouseenter mouseleave mousemove mouseout mouseover mouseup pause play playing progress ratechange reset scroll seeked seeking select show stalled submit suspend timeupdate volumechange waiting mozfullscreenchange mozfullscreenerror mozpointerlockchange mozpointerlockerror error webglcontextrestored webglcontextlost webglcontextcreationerror'\n .split(' ');\nfunction propertyDescriptorPatch(_global) {\n if (isNode) {\n return;\n }\n var supportsWebSocket = typeof WebSocket !== 'undefined';\n if (canPatchViaPropertyDescriptor()) {\n // for browsers that we can patch the descriptor: Chrome & Firefox\n if (isBrowser) {\n patchOnProperties(HTMLElement.prototype, eventNames);\n }\n patchOnProperties(XMLHttpRequest.prototype, null);\n if (typeof IDBIndex !== 'undefined') {\n patchOnProperties(IDBIndex.prototype, null);\n patchOnProperties(IDBRequest.prototype, null);\n patchOnProperties(IDBOpenDBRequest.prototype, null);\n patchOnProperties(IDBDatabase.prototype, null);\n patchOnProperties(IDBTransaction.prototype, null);\n patchOnProperties(IDBCursor.prototype, null);\n }\n if (supportsWebSocket) {\n patchOnProperties(WebSocket.prototype, null);\n }\n }\n else {\n // Safari, Android browsers (Jelly Bean)\n patchViaCapturingAllTheEvents();\n patchClass('XMLHttpRequest');\n if (supportsWebSocket) {\n apply(_global);\n }\n }\n}\nfunction canPatchViaPropertyDescriptor() {\n if (isBrowser && !Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onclick') &&\n typeof Element !== 'undefined') {\n // WebKit https://bugs.webkit.org/show_bug.cgi?id=134364\n // IDL interface attributes are not configurable\n var desc = Object.getOwnPropertyDescriptor(Element.prototype, 'onclick');\n if (desc && !desc.configurable)\n return false;\n }\n Object.defineProperty(XMLHttpRequest.prototype, 'onreadystatechange', {\n get: function () {\n return true;\n }\n });\n var req = new XMLHttpRequest();\n var result = !!req.onreadystatechange;\n Object.defineProperty(XMLHttpRequest.prototype, 'onreadystatechange', {});\n return result;\n}\n\nvar unboundKey = zoneSymbol('unbound');\n// Whenever any eventListener fires, we check the eventListener target and all parents\n// for `onwhatever` properties and replace them with zone-bound functions\n// - Chrome (for now)\nfunction patchViaCapturingAllTheEvents() {\n var _loop_1 = function(i) {\n var property = eventNames[i];\n var onproperty = 'on' + property;\n self.addEventListener(property, function (event) {\n var elt = event.target, bound, source;\n if (elt) {\n source = elt.constructor['name'] + '.' + onproperty;\n }\n else {\n source = 'unknown.' + onproperty;\n }\n while (elt) {\n if (elt[onproperty] && !elt[onproperty][unboundKey]) {\n bound = Zone.current.wrap(elt[onproperty], source);\n bound[unboundKey] = elt[onproperty];\n elt[onproperty] = bound;\n }\n elt = elt.parentElement;\n }\n }, true);\n };\n for (var i = 0; i < eventNames.length; i++) {\n _loop_1(i);\n }\n \n}\n\n/**\n * @license\n * Copyright Google Inc. All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.io/license\n */\nfunction registerElementPatch(_global) {\n if (!isBrowser || !('registerElement' in _global.document)) {\n return;\n }\n var _registerElement = document.registerElement;\n var callbacks = ['createdCallback', 'attachedCallback', 'detachedCallback', 'attributeChangedCallback'];\n document.registerElement = function (name, opts) {\n if (opts && opts.prototype) {\n callbacks.forEach(function (callback) {\n var source = 'Document.registerElement::' + callback;\n if (opts.prototype.hasOwnProperty(callback)) {\n var descriptor = Object.getOwnPropertyDescriptor(opts.prototype, callback);\n if (descriptor && descriptor.value) {\n descriptor.value = Zone.current.wrap(descriptor.value, source);\n _redefineProperty(opts.prototype, callback, descriptor);\n }\n else {\n opts.prototype[callback] = Zone.current.wrap(opts.prototype[callback], source);\n }\n }\n else if (opts.prototype[callback]) {\n opts.prototype[callback] = Zone.current.wrap(opts.prototype[callback], source);\n }\n });\n }\n return _registerElement.apply(document, [name, opts]);\n };\n}\n\n/**\n * @license\n * Copyright Google Inc. All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.io/license\n */\nvar set = 'set';\nvar clear = 'clear';\nvar blockingMethods = ['alert', 'prompt', 'confirm'];\nvar _global = typeof window === 'object' && window || typeof self === 'object' && self || global;\npatchTimer(_global, set, clear, 'Timeout');\npatchTimer(_global, set, clear, 'Interval');\npatchTimer(_global, set, clear, 'Immediate');\npatchTimer(_global, 'request', 'cancel', 'AnimationFrame');\npatchTimer(_global, 'mozRequest', 'mozCancel', 'AnimationFrame');\npatchTimer(_global, 'webkitRequest', 'webkitCancel', 'AnimationFrame');\nfor (var i = 0; i < blockingMethods.length; i++) {\n var name = blockingMethods[i];\n patchMethod(_global, name, function (delegate, symbol, name) {\n return function (s, args) {\n return Zone.current.run(delegate, _global, args, name);\n };\n });\n}\neventTargetPatch(_global);\npropertyDescriptorPatch(_global);\npatchClass('MutationObserver');\npatchClass('WebKitMutationObserver');\npatchClass('FileReader');\npropertyPatch();\nregisterElementPatch(_global);\n// Treat XMLHTTPRequest as a macrotask.\npatchXHR(_global);\nvar XHR_TASK = zoneSymbol('xhrTask');\nvar XHR_SYNC = zoneSymbol('xhrSync');\nvar XHR_LISTENER = zoneSymbol('xhrListener');\nvar XHR_SCHEDULED = zoneSymbol('xhrScheduled');\nfunction patchXHR(window) {\n function findPendingTask(target) {\n var pendingTask = target[XHR_TASK];\n return pendingTask;\n }\n function scheduleTask(task) {\n self[XHR_SCHEDULED] = false;\n var data = task.data;\n // remove existing event listener\n var listener = data.target[XHR_LISTENER];\n if (listener) {\n data.target.removeEventListener('readystatechange', listener);\n }\n var newListener = data.target[XHR_LISTENER] = function () {\n if (data.target.readyState === data.target.DONE) {\n if (!data.aborted && self[XHR_SCHEDULED]) {\n task.invoke();\n }\n }\n };\n data.target.addEventListener('readystatechange', newListener);\n var storedTask = data.target[XHR_TASK];\n if (!storedTask) {\n data.target[XHR_TASK] = task;\n }\n sendNative.apply(data.target, data.args);\n self[XHR_SCHEDULED] = true;\n return task;\n }\n function placeholderCallback() { }\n function clearTask(task) {\n var data = task.data;\n // Note - ideally, we would call data.target.removeEventListener here, but it's too late\n // to prevent it from firing. So instead, we store info for the event listener.\n data.aborted = true;\n return abortNative.apply(data.target, data.args);\n }\n var openNative = patchMethod(window.XMLHttpRequest.prototype, 'open', function () { return function (self, args) {\n self[XHR_SYNC] = args[2] == false;\n return openNative.apply(self, args);\n }; });\n var sendNative = patchMethod(window.XMLHttpRequest.prototype, 'send', function () { return function (self, args) {\n var zone = Zone.current;\n if (self[XHR_SYNC]) {\n // if the XHR is sync there is no task to schedule, just execute the code.\n return sendNative.apply(self, args);\n }\n else {\n var options = { target: self, isPeriodic: false, delay: null, args: args, aborted: false };\n return zone.scheduleMacroTask('XMLHttpRequest.send', placeholderCallback, options, scheduleTask, clearTask);\n }\n }; });\n var abortNative = patchMethod(window.XMLHttpRequest.prototype, 'abort', function (delegate) { return function (self, args) {\n var task = findPendingTask(self);\n if (task && typeof task.type == 'string') {\n // If the XHR has already completed, do nothing.\n if (task.cancelFn == null) {\n return;\n }\n task.zone.cancelTask(task);\n }\n // Otherwise, we are trying to abort an XHR which has not yet been sent, so there is no task\n // to cancel. Do nothing.\n }; });\n}\n/// GEO_LOCATION\nif (_global['navigator'] && _global['navigator'].geolocation) {\n patchPrototype(_global['navigator'].geolocation, ['getCurrentPosition', 'watchPosition']);\n}\n\n/**\n * @license\n * Copyright Google Inc. All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.io/license\n */\n\n})));\n", diff --git a/package.json b/package.json index 73ba2c369cbc..9f188d0fb967 100644 --- a/package.json +++ b/package.json @@ -57,7 +57,7 @@ "deploy-viewer": "cd lighthouse-viewer && gulp deploy", "bundlesize": "bundlesize", "plots-smoke": "bash plots/test/smoke.sh", - "timing": "node lighthouse-core/scripts/generate-lh-timing-trace.js", + "timing": "node lighthouse-core/scripts/generate-timing-trace.js", "changelog": "conventional-changelog --config ./build/changelog-generator/index.js --infile changelog.md --same-file", "type-check": "tsc -p . && cd ./lighthouse-viewer && yarn type-check", "update:sample-artifacts": "node lighthouse-core/scripts/update-report-fixtures.js -G", From 7c155b91264370cea9db64f11407f1f41b7c70e2 Mon Sep 17 00:00:00 2001 From: Paul Irish Date: Mon, 25 Jun 2018 20:12:48 +0100 Subject: [PATCH 06/32] add tests --- lighthouse-core/lib/timing-trace-saver.js | 7 +- lighthouse-core/runner.js | 1 + .../scripts/generate-timing-trace.js | 4 +- lighthouse-core/test/index-test.js | 1 - .../test/lib/timing-trace-saver-test.js | 123 ++++++++++++++++++ lighthouse-logger/index.js | 2 +- 6 files changed, 131 insertions(+), 7 deletions(-) create mode 100644 lighthouse-core/test/lib/timing-trace-saver-test.js diff --git a/lighthouse-core/lib/timing-trace-saver.js b/lighthouse-core/lib/timing-trace-saver.js index e5ed2f0b5af2..82719f1a016c 100644 --- a/lighthouse-core/lib/timing-trace-saver.js +++ b/lighthouse-core/lib/timing-trace-saver.js @@ -26,10 +26,12 @@ function checkEventOverlap(entry, prevEntries) { /** * Generates a chromium trace file from user timing measures * Adapted from https://github.com/tdresser/performance-observer-tracing - * @param {!Array} entries user timing entries + * @param {!Array=} entries user timing entries * @param {string=} threadName */ function generateTraceEvents(entries, threadName = 'measures') { + if (!Array.isArray(entries)) return []; + const currentTrace = /** @type {!LH.TraceEvent[]} */ ([]); let id = 0; @@ -76,10 +78,9 @@ function createTraceString(lhr) { ${events.map(evt => JSON.stringify(evt)).join(',\n')} ]}`; - return jsonStr; + return jsonStr; } - module.exports = {generateTraceEvents, createTraceString}; diff --git a/lighthouse-core/runner.js b/lighthouse-core/runner.js index 987e2471caf1..0eb467e8607e 100644 --- a/lighthouse-core/runner.js +++ b/lighthouse-core/runner.js @@ -125,6 +125,7 @@ class Runner { log.timeEnd(status); // Summarize all the timings and drop onto the LHR + artifacts.Timing = artifacts.Timing || {entries: []}; artifacts.Timing.entries.push(...log.getEntries()); /** @type {LH.Result} */ diff --git a/lighthouse-core/scripts/generate-timing-trace.js b/lighthouse-core/scripts/generate-timing-trace.js index d46873490992..cd4bed671d64 100644 --- a/lighthouse-core/scripts/generate-timing-trace.js +++ b/lighthouse-core/scripts/generate-timing-trace.js @@ -18,9 +18,9 @@ function printErrorAndQuit(msg) { > ${msg} > Example: > yarn timing results.json - `) + `); process.exit(1); -}; +} /** * Takes filename of LHR object. The primary entrypoint on CLI diff --git a/lighthouse-core/test/index-test.js b/lighthouse-core/test/index-test.js index 2d10504787a4..360686b87b1f 100644 --- a/lighthouse-core/test/index-test.js +++ b/lighthouse-core/test/index-test.js @@ -110,7 +110,6 @@ describe('Module Tests', function() { assert.strictEqual(results.lhr.audits.viewport.score, 0); assert.ok(results.lhr.audits.viewport.explanation); assert.ok(results.lhr.timing); - assert.equal(typeof results.lhr.timing.total, 'number'); assert.ok(results.lhr.timing.entries.length > 3, 'timing entries not populated'); }); }); diff --git a/lighthouse-core/test/lib/timing-trace-saver-test.js b/lighthouse-core/test/lib/timing-trace-saver-test.js new file mode 100644 index 000000000000..0e1644259d3e --- /dev/null +++ b/lighthouse-core/test/lib/timing-trace-saver-test.js @@ -0,0 +1,123 @@ +/** + * @license Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + */ +'use strict'; +/* eslint-env mocha */ +const assert = require('assert'); +const { + generateTraceEvents, + createTraceString, +} = require('../../lib/timing-trace-saver'); + + +const mockEntries = [{ + startTime: 650, + name: 'lh:init:config', + duration: 210, + entryType: 'measure', +}, +{ + startTime: 870, + name: 'lh:runner:run', + duration: 120, + entryType: 'measure', +}, +{ + startTime: 990, + name: 'lh:runner:auditing', + duration: 750, + entryType: 'measure', +}, +{ + startTime: 1010, + name: 'lh:audit:is-on-https', + duration: 10, + entryType: 'measure', +}, +]; +const expectedTrace = { + traceEvents: [{ + name: 'lh:init:config', + cat: 'measure', + ts: 650000, + dur: 210000, + args: {}, + pid: 'Lighthouse', + tid: 'measures', + ph: 'X', + id: '0x0', + }, + { + name: 'lh:runner:run', + cat: 'measure', + ts: 870000, + dur: 120000, + args: {}, + pid: 'Lighthouse', + tid: 'measures', + ph: 'X', + id: '0x1', + }, + { + name: 'lh:runner:auditing', + cat: 'measure', + ts: 990000, + dur: 750000, + args: {}, + pid: 'Lighthouse', + tid: 'measures', + ph: 'X', + id: '0x2', + }, + { + name: 'lh:audit:is-on-https', + cat: 'measure', + ts: 1010000, + dur: 10000, + args: {}, + pid: 'Lighthouse', + tid: 'measures', + ph: 'X', + id: '0x3', + }, + ], +}; + + +describe('generateTraceEvents', () => { + it('generates a single trace event', () => { + const event = generateTraceEvents(mockEntries.slice(0, 1)); + assert.deepStrictEqual(event, expectedTrace.traceEvents.slice(0, 1)); + }); + + it('doesn\'t allow overlapping events', () => { + const overlappingEntries = [{ + startTime: 10, + name: 'overlap1', + duration: 100, + entryType: 'measure', + }, + { + startTime: 30, + name: 'overlap2', + duration: 100, + entryType: 'measure', + }, + ]; + assert.throws(_ => generateTraceEvents(overlappingEntries), /measures overlap/); + }); +}); + +describe('createTraceString', () => { + it('creates a real trace', () => { + const jsonStr = createTraceString({ + timing: { + entries: mockEntries, + }, + }); + const traceJson = JSON.parse(jsonStr); + assert.deepStrictEqual(traceJson, expectedTrace); + }); +}); diff --git a/lighthouse-logger/index.js b/lighthouse-logger/index.js index 568c2d1204ea..bbc329049857 100644 --- a/lighthouse-logger/index.js +++ b/lighthouse-logger/index.js @@ -223,6 +223,6 @@ Log.getEntries = _ => { const entries = marky.getEntries(); marky.clear(); return entries; -} +}; module.exports = Log; From 2a45eb5b9e7187d9b031e1a97dec89751a4a7a2c Mon Sep 17 00:00:00 2001 From: Paul Irish Date: Mon, 25 Jun 2018 15:56:43 -0700 Subject: [PATCH 07/32] report the total. --- lighthouse-core/runner.js | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/lighthouse-core/runner.js b/lighthouse-core/runner.js index 0eb467e8607e..bca6589ebbbf 100644 --- a/lighthouse-core/runner.js +++ b/lighthouse-core/runner.js @@ -30,6 +30,8 @@ class Runner { static async run(connection, opts) { try { const settings = opts.config.settings; + const totalStatus = {msg: 'Total', id: 'total'}; + log.time(totalStatus, 'verbose'); const runnerStatus = {msg: 'Runner setup', id: 'lh:runner:run'}; log.time(runnerStatus, 'verbose'); @@ -100,8 +102,8 @@ class Runner { const auditResults = await Runner._runAudits(settings, opts.config.audits, artifacts); // LHR construction phase - const status = {msg: 'Generating results...', id: 'lh:runner:generate'}; - log.time(status); + const resultsStatus = {msg: 'Generating results...', id: 'lh:runner:generate'}; + log.time(resultsStatus); if (artifacts.LighthouseRunWarnings) { lighthouseRunWarnings.push(...artifacts.LighthouseRunWarnings); @@ -123,10 +125,7 @@ class Runner { categories = ReportScoring.scoreAllCategories(opts.config.categories, resultsById); } - log.timeEnd(status); - // Summarize all the timings and drop onto the LHR - artifacts.Timing = artifacts.Timing || {entries: []}; - artifacts.Timing.entries.push(...log.getEntries()); + log.timeEnd(resultsStatus); /** @type {LH.Result} */ const lhr = { @@ -140,11 +139,20 @@ class Runner { configSettings: settings, categories, categoryGroups: opts.config.groups || undefined, - timing: artifacts.Timing, + timing: {entries: artifacts.Timing || [], total: 0}, }; + // Summarize all the timings and drop onto the LHR + log.timeEnd(totalStatus); + lhr.timing.entries.push(...log.getEntries()); + const totalEntry = log.getEntries().find(e => e.name === 'total'); + if (totalEntry) { + lhr.timing.total = totalEntry.duration; + } + + // Create the HTML, JSON, or CSV string const report = generateReport(lhr, settings.output); - log.timeEnd(status); + return {lhr, artifacts, report}; } catch (err) { // @ts-ignore TODO(bckenny): Sentry type checking From 046780bafc3544b2fcf617eddae1147216a8c0aa Mon Sep 17 00:00:00 2001 From: Paul Irish Date: Mon, 25 Jun 2018 15:58:52 -0700 Subject: [PATCH 08/32] gather:true, rather than gatherEntries --- lighthouse-core/gather/gather-runner.js | 2 +- lighthouse-core/index.js | 2 +- lighthouse-core/lib/asset-saver.js | 5 +-- lighthouse-core/lib/timing-trace-saver.js | 39 +++++++++++++------ lighthouse-core/runner.js | 2 +- .../scripts/generate-timing-trace.js | 2 +- .../test/lib/timing-trace-saver-test.js | 29 +++++++------- typings/artifacts.d.ts | 13 ++++++- typings/externs.d.ts | 7 ++-- typings/lhr.d.ts | 2 +- 10 files changed, 62 insertions(+), 41 deletions(-) diff --git a/lighthouse-core/gather/gather-runner.js b/lighthouse-core/gather/gather-runner.js index a4c51a9c90fd..8007020ca653 100644 --- a/lighthouse-core/gather/gather-runner.js +++ b/lighthouse-core/gather/gather-runner.js @@ -417,7 +417,7 @@ class GatherRunner { devtoolsLogs: {}, settings: options.settings, URL: {requestedUrl: options.requestedUrl, finalUrl: ''}, - Timing: {entries: [], gatherEntries: []}, + Timing: [], }; } diff --git a/lighthouse-core/index.js b/lighthouse-core/index.js index cb1c6ec6e4a6..7b91a8b0dce7 100644 --- a/lighthouse-core/index.js +++ b/lighthouse-core/index.js @@ -44,7 +44,7 @@ async function lighthouse(url, flags, configJSON) { const connection = new ChromeProtocol(flags.port, flags.hostname); // kick off a lighthouse run - return await Runner.run(connection, {url, config}); + return Runner.run(connection, {url, config}); } lighthouse.getAuditList = Runner.getAuditList; diff --git a/lighthouse-core/lib/asset-saver.js b/lighthouse-core/lib/asset-saver.js index eefd42708339..6cd41a385e66 100644 --- a/lighthouse-core/lib/asset-saver.js +++ b/lighthouse-core/lib/asset-saver.js @@ -119,9 +119,8 @@ async function loadArtifacts(basePath) { }); await Promise.all(promises); if (artifacts.Timing) { - // Move entries to separate array, so they can be rendered in parallel - artifacts.Timing.gatherEntries = artifacts.Timing.entries; - artifacts.Timing.entries = []; + // Tag existing entries, so they can be rendered in parallel + artifacts.Timing.forEach(entry => (entry.gather = true)); } return artifacts; diff --git a/lighthouse-core/lib/timing-trace-saver.js b/lighthouse-core/lib/timing-trace-saver.js index 82719f1a016c..888f23517060 100644 --- a/lighthouse-core/lib/timing-trace-saver.js +++ b/lighthouse-core/lib/timing-trace-saver.js @@ -9,8 +9,8 @@ * Technically, it's fine for usertiming measures to overlap, however non-async events make * for a much clearer UI in traceviewer. We do this check to make sure we aren't passing off * async-like measures as non-async. - * @param {!PerformanceEntry} entry user timing entry - * @param {!Array} prevEntries user timing entries + * @param {!LH.Artifacts.MeasureEntry} entry user timing entry + * @param {LH.Artifacts.MeasureEntry[]} prevEntries user timing entries */ function checkEventOverlap(entry, prevEntries) { for (const prevEntry of prevEntries) { @@ -26,10 +26,10 @@ function checkEventOverlap(entry, prevEntries) { /** * Generates a chromium trace file from user timing measures * Adapted from https://github.com/tdresser/performance-observer-tracing - * @param {!Array=} entries user timing entries - * @param {string=} threadName + * @param {LH.Artifacts.MeasureEntry[]} entries user timing entries + * @param {string=} trackName */ -function generateTraceEvents(entries, threadName = 'measures') { +function generateTraceEvents(entries, trackName = 'measures') { if (!Array.isArray(entries)) return []; const currentTrace = /** @type {!LH.TraceEvent[]} */ ([]); @@ -45,8 +45,8 @@ function generateTraceEvents(entries, threadName = 'measures') { ts: entry.startTime * 1000, dur: entry.duration * 1000, args: {}, - pid: 'Lighthouse', - tid: threadName, + pid: 0, + tid: trackName === 'measures' ? 50 : 75, ph: 'X', id: '0x' + (id++).toString(16), }; @@ -60,6 +60,20 @@ function generateTraceEvents(entries, threadName = 'measures') { currentTrace.push(traceEvent); }); + // Add labels + const metaEvtBase = { + pid: 0, + tid: trackName === 'measures' ? 50 : 75, + ts: 0, + dur: 0, + ph: 'M', + cat: '__metadata', + name: 'process_labels', + args: {labels: 'Default'}, + }; + currentTrace.push(Object.assign({}, metaEvtBase, {args: {labels: 'Lighthouse Timing'}})); + currentTrace.push(Object.assign({}, metaEvtBase, {name: 'thread_name', args: {name: trackName}})); + return currentTrace; } @@ -69,9 +83,12 @@ function generateTraceEvents(entries, threadName = 'measures') { * @return {!string}; */ function createTraceString(lhr) { - const gatherEvents = generateTraceEvents(lhr.timing.gatherEntries, 'gather'); - const auditEvents = generateTraceEvents(lhr.timing.entries); - const events = [...gatherEvents, ...auditEvents]; + const gatherEntries = lhr.timing.entries.filter(entry => entry.gather); + const entries = lhr.timing.entries.filter(entry => !gatherEntries.includes(entry)); + + const auditEvents = generateTraceEvents(entries); + const gatherEvents = generateTraceEvents(gatherEntries, 'gather'); + const events = [...auditEvents, ...gatherEvents]; const jsonStr = ` { "traceEvents": [ @@ -81,6 +98,4 @@ function createTraceString(lhr) { return jsonStr; } - module.exports = {generateTraceEvents, createTraceString}; - diff --git a/lighthouse-core/runner.js b/lighthouse-core/runner.js index bca6589ebbbf..308c92a15826 100644 --- a/lighthouse-core/runner.js +++ b/lighthouse-core/runner.js @@ -180,7 +180,7 @@ class Runner { settings: runnerOpts.config.settings, }; const artifacts = await GatherRunner.run(runnerOpts.config.passes, gatherOpts); - artifacts.Timing.entries = log.getEntries(); + artifacts.Timing = log.getEntries(); return artifacts; } diff --git a/lighthouse-core/scripts/generate-timing-trace.js b/lighthouse-core/scripts/generate-timing-trace.js index cd4bed671d64..b30795801eaf 100644 --- a/lighthouse-core/scripts/generate-timing-trace.js +++ b/lighthouse-core/scripts/generate-timing-trace.js @@ -37,7 +37,7 @@ function saveTraceFromCLI() { const lhrObject = JSON.parse(fs.readFileSync(filename, 'utf8')); const jsonStr = createTraceString(lhrObject); - const traceFilePath = `${filename}.run-timing.trace.json`; + const traceFilePath = `${filename}.timing.trace.json`; fs.writeFileSync(traceFilePath, jsonStr, 'utf8'); // eslint-disable-next-line no-console console.log(` diff --git a/lighthouse-core/test/lib/timing-trace-saver-test.js b/lighthouse-core/test/lib/timing-trace-saver-test.js index 0e1644259d3e..70a01f8b476e 100644 --- a/lighthouse-core/test/lib/timing-trace-saver-test.js +++ b/lighthouse-core/test/lib/timing-trace-saver-test.js @@ -6,11 +6,7 @@ 'use strict'; /* eslint-env mocha */ const assert = require('assert'); -const { - generateTraceEvents, - createTraceString, -} = require('../../lib/timing-trace-saver'); - +const {generateTraceEvents, createTraceString} = require('../../lib/timing-trace-saver'); const mockEntries = [{ startTime: 650, @@ -44,8 +40,8 @@ const expectedTrace = { ts: 650000, dur: 210000, args: {}, - pid: 'Lighthouse', - tid: 'measures', + pid: 0, + tid: 50, ph: 'X', id: '0x0', }, @@ -55,8 +51,8 @@ const expectedTrace = { ts: 870000, dur: 120000, args: {}, - pid: 'Lighthouse', - tid: 'measures', + pid: 0, + tid: 50, ph: 'X', id: '0x1', }, @@ -66,8 +62,8 @@ const expectedTrace = { ts: 990000, dur: 750000, args: {}, - pid: 'Lighthouse', - tid: 'measures', + pid: 0, + tid: 50, ph: 'X', id: '0x2', }, @@ -77,8 +73,8 @@ const expectedTrace = { ts: 1010000, dur: 10000, args: {}, - pid: 'Lighthouse', - tid: 'measures', + pid: 0, + tid: 50, ph: 'X', id: '0x3', }, @@ -88,8 +84,8 @@ const expectedTrace = { describe('generateTraceEvents', () => { it('generates a single trace event', () => { - const event = generateTraceEvents(mockEntries.slice(0, 1)); - assert.deepStrictEqual(event, expectedTrace.traceEvents.slice(0, 1)); + const event = generateTraceEvents(mockEntries); + assert.deepStrictEqual(event.slice(0, 1), expectedTrace.traceEvents.slice(0, 1)); }); it('doesn\'t allow overlapping events', () => { @@ -118,6 +114,7 @@ describe('createTraceString', () => { }, }); const traceJson = JSON.parse(jsonStr); - assert.deepStrictEqual(traceJson, expectedTrace); + const eventsWithoutMetadata = traceJson.traceEvents.filter(e => e.cat !== '__metadata'); + assert.deepStrictEqual(eventsWithoutMetadata, expectedTrace.traceEvents); }); }); diff --git a/typings/artifacts.d.ts b/typings/artifacts.d.ts index d824f80f3a2e..37f212787b13 100644 --- a/typings/artifacts.d.ts +++ b/typings/artifacts.d.ts @@ -30,8 +30,8 @@ declare global { settings: Config.Settings; /** The URL initially requested and the post-redirects URL that was actually loaded. */ URL: {requestedUrl: string, finalUrl: string}; - - Timing: {entries: PerformanceEntry[], gatherEntries: PerformanceEntry[]}; + /** Holds the timing instrumentation of a gather-only run */ + Timing: Artifacts.MeasureEntry[]; } /** @@ -338,6 +338,15 @@ declare global { }[]; } + export interface MeasureEntry { + name: string; + startTime: number; + duration: number; + entryType: string; + gather?: boolean; + toJSON: any; + } + export interface MetricComputationDataInput { devtoolsLog: DevtoolsLog; trace: Trace; diff --git a/typings/externs.d.ts b/typings/externs.d.ts index 531240b470ef..3985b3f9bf06 100644 --- a/typings/externs.d.ts +++ b/typings/externs.d.ts @@ -159,12 +159,13 @@ declare global { }; frame?: string; name?: string; + labels?: string; }; - pid: number|string; - tid: number|string; + pid: number; + tid: number; ts: number; dur: number; - ph: 'B'|'b'|'D'|'E'|'e'|'F'|'I'|'M'|'N'|'n'|'O'|'R'|'S'|'T'|'X'; + ph: string; // one of 'B'|'b'|'D'|'E'|'e'|'F'|'I'|'M'|'N'|'n'|'O'|'R'|'S'|'T'|'X'; s?: 't'; } diff --git a/typings/lhr.d.ts b/typings/lhr.d.ts index f920512a728d..de1004dfb20d 100644 --- a/typings/lhr.d.ts +++ b/typings/lhr.d.ts @@ -34,7 +34,7 @@ declare global { /** The User-Agent string of the browser used run Lighthouse for these results. */ userAgent: string; /** Execution timings for the Lighthouse run */ - timing: {entries: PerformanceEntry[], gatherEntries: PerformanceEntry[]}; + timing: {entries: Artifacts.MeasureEntry[], total: number}; } // Result namespace From 4e77f8134df106d9c7f9341fe8d3dc72aee4e5bc Mon Sep 17 00:00:00 2001 From: Paul Irish Date: Tue, 26 Jun 2018 10:03:14 -0700 Subject: [PATCH 09/32] Add additional instrumentation --- lighthouse-core/config/config.js | 7 ++++++- lighthouse-core/gather/driver.js | 8 ++++++-- lighthouse-core/lib/asset-saver.js | 3 +++ lighthouse-core/runner.js | 12 ++++-------- 4 files changed, 19 insertions(+), 11 deletions(-) diff --git a/lighthouse-core/config/config.js b/lighthouse-core/config/config.js index a247132b42e1..e8c5059469b6 100644 --- a/lighthouse-core/config/config.js +++ b/lighthouse-core/config/config.js @@ -700,6 +700,8 @@ class Config { * @return {Config['audits']} */ static requireAudits(audits, configPath) { + const status = {msg: 'Requiring audits', id: 'lh:config:requireAudits'}; + log.time(status); const expandedAudits = Config.expandAuditShorthand(audits); if (!expandedAudits) { return null; @@ -731,6 +733,7 @@ class Config { const mergedAuditDefns = mergeOptionsOfItems(auditDefns); mergedAuditDefns.forEach(audit => assertValidAudit(audit.implementation, audit.path)); + log.timeEnd(status); return mergedAuditDefns; } @@ -772,6 +775,8 @@ class Config { if (!passes) { return null; } + const status = {msg: 'Requiring gatherers', id: 'lh:config:requireGatherers'}; + log.time(status); const coreList = Runner.getGathererList(); const fullPasses = passes.map(pass => { @@ -805,7 +810,7 @@ class Config { return Object.assign(pass, {gatherers: mergedDefns}); }); - + log.timeEnd(status); return fullPasses; } } diff --git a/lighthouse-core/gather/driver.js b/lighthouse-core/gather/driver.js index 210666c0bd94..e72f793512b6 100644 --- a/lighthouse-core/gather/driver.js +++ b/lighthouse-core/gather/driver.js @@ -101,9 +101,13 @@ class Driver { /** * @return {Promise} */ - getUserAgent() { + async getUserAgent() { + const status = {msg: 'Getting userAgent', id: 'lh:gather:getUserAgent'}; + log.time(status, 'verbose'); // FIXME: use Browser.getVersion instead - return this.evaluateAsync('navigator.userAgent'); + const userAgent = await this.evaluateAsync('navigator.userAgent'); + log.timeEnd(status); + return userAgent; } /** diff --git a/lighthouse-core/lib/asset-saver.js b/lighthouse-core/lib/asset-saver.js index 6cd41a385e66..7d3462f0ee81 100644 --- a/lighthouse-core/lib/asset-saver.js +++ b/lighthouse-core/lib/asset-saver.js @@ -134,6 +134,8 @@ async function loadArtifacts(basePath) { * @return {Promise} */ async function saveArtifacts(artifacts, basePath) { + const status = {msg: 'Saving artifacts', id: 'lh:assetSaver:saveArtifacts'}; + log.time(status); mkdirp.sync(basePath); rimraf.sync(`${basePath}/*${traceSuffix}`); rimraf.sync(`${basePath}/${artifactsFilename}`); @@ -155,6 +157,7 @@ async function saveArtifacts(artifacts, basePath) { const restArtifactsString = JSON.stringify(restArtifacts, null, 2); fs.writeFileSync(`${basePath}/${artifactsFilename}`, restArtifactsString, 'utf8'); log.log('Artifacts saved to disk in folder:', basePath); + log.timeEnd(status); } /** diff --git a/lighthouse-core/runner.js b/lighthouse-core/runner.js index 308c92a15826..41eca902ccd4 100644 --- a/lighthouse-core/runner.js +++ b/lighthouse-core/runner.js @@ -30,8 +30,6 @@ class Runner { static async run(connection, opts) { try { const settings = opts.config.settings; - const totalStatus = {msg: 'Total', id: 'total'}; - log.time(totalStatus, 'verbose'); const runnerStatus = {msg: 'Runner setup', id: 'lh:runner:run'}; log.time(runnerStatus, 'verbose'); @@ -70,7 +68,6 @@ class Runner { if (opts.url && opts.url !== requestedUrl) { throw new Error('Cannot run audit mode on different URL'); } - log.timeEnd(runnerStatus); } else { if (typeof opts.url !== 'string' || opts.url.length === 0) { throw new Error(`You must provide a url to the runner. '${opts.url}' provided.`); @@ -83,7 +80,6 @@ class Runner { throw new Error('The url provided should have a proper protocol and hostname.'); } - log.timeEnd(runnerStatus); artifacts = await Runner._gatherArtifactsFromBrowser(requestedUrl, opts, connection); // -G means save these to ./latest-run, etc. if (settings.gatherMode) { @@ -143,11 +139,11 @@ class Runner { }; // Summarize all the timings and drop onto the LHR - log.timeEnd(totalStatus); + log.timeEnd(runnerStatus); lhr.timing.entries.push(...log.getEntries()); - const totalEntry = log.getEntries().find(e => e.name === 'total'); - if (totalEntry) { - lhr.timing.total = totalEntry.duration; + const runnerEntry = log.getEntries().find(e => e.name === 'lh:runner:run'); + if (runnerEntry) { + lhr.timing.total = runnerEntry.duration; } // Create the HTML, JSON, or CSV string From 6df70965679fd6555a2d02d0c24e8c4130e7e65d Mon Sep 17 00:00:00 2001 From: Paul Irish Date: Wed, 15 Aug 2018 13:35:14 -0700 Subject: [PATCH 10/32] fix tests --- lighthouse-cli/test/cli/run-test.js | 1 + lighthouse-core/lib/asset-saver.js | 2 +- lighthouse-core/runner.js | 2 +- lighthouse-core/test/results/artifacts/artifacts.json | 2 +- 4 files changed, 4 insertions(+), 3 deletions(-) diff --git a/lighthouse-cli/test/cli/run-test.js b/lighthouse-cli/test/cli/run-test.js index ec911a84e20a..bd19c6a5c9a8 100644 --- a/lighthouse-cli/test/cli/run-test.js +++ b/lighthouse-cli/test/cli/run-test.js @@ -41,6 +41,7 @@ describe('CLI run', function() { Object.keys(results.audits).length, Object.keys(lhr.audits).length); assert.deepStrictEqual(results.timing, lhr.timing); + assert.ok(results.timing.total !== 0); fs.unlinkSync(filename); }); diff --git a/lighthouse-core/lib/asset-saver.js b/lighthouse-core/lib/asset-saver.js index b046cb67b393..a6cb48ba33d7 100644 --- a/lighthouse-core/lib/asset-saver.js +++ b/lighthouse-core/lib/asset-saver.js @@ -118,7 +118,7 @@ async function loadArtifacts(basePath) { }); }); await Promise.all(promises); - if (artifacts.Timing) { + if (Array.isArray(artifacts.Timing)) { // Tag existing entries, so they can be rendered in parallel artifacts.Timing.forEach(entry => (entry.gather = true)); } diff --git a/lighthouse-core/runner.js b/lighthouse-core/runner.js index f5290ff3ca28..7ec3f5108480 100644 --- a/lighthouse-core/runner.js +++ b/lighthouse-core/runner.js @@ -142,7 +142,7 @@ class Runner { // Summarize all the timings and drop onto the LHR log.timeEnd(runnerStatus); lhr.timing.entries.push(...log.getEntries()); - const runnerEntry = log.getEntries().find(e => e.name === 'lh:runner:run'); + const runnerEntry = lhr.timing.entries.find(e => e.name === 'lh:runner:run'); if (runnerEntry) { lhr.timing.total = runnerEntry.duration; } diff --git a/lighthouse-core/test/results/artifacts/artifacts.json b/lighthouse-core/test/results/artifacts/artifacts.json index 42b592008f03..2ddd0f22d4d6 100644 --- a/lighthouse-core/test/results/artifacts/artifacts.json +++ b/lighthouse-core/test/results/artifacts/artifacts.json @@ -6,7 +6,7 @@ "requestedUrl": "http://localhost:10200/dobetterweb/dbw_tester.html", "finalUrl": "http://localhost:10200/dobetterweb/dbw_tester.html" }, - "Timing": {}, + "Timing": [], "Scripts": { "75994.10": "/**\n * @license Copyright 2016 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.\n */\n\n/*eslint-disable*/\n\n(function() {\n\nconst params = new URLSearchParams(location.search);\n\nif (location.search === '' || params.has('dateNow')) {\n // FAIL - Date.now() usage in another file.\n const d = Date.now();\n}\n\nif (location.search === '' || params.has('mutationEvents')) {\n // FAIL - MutationEvent usage in another file.\n document.addEventListener('DOMNodeInserted', function(e) {\n console.log('DOMNodeInserted');\n });\n}\n\nif (location.search === '' || params.has('passiveEvents')) {\n // FAIL - non-passive listener usage in another file.\n document.addEventListener('wheel', e => {\n console.log('wheel: arrow function');\n });\n}\n\nif (location.search === '' || params.has('deprecations')) {\n const div = document.createElement('div');\n div.createShadowRoot();\n // FAIL(errors-in-console) - multiple shadow v0 roots.\n // TODO: disabled until m64 is stable (when moved from deprecation warning to error)\n // div.createShadowRoot();\n}\n\n})();\n", "75994.21": "/**\n* @license\n* Copyright Google Inc. All Rights Reserved.\n*\n* Use of this source code is governed by an MIT-style license that can be\n* found in the LICENSE file at https://angular.io/license\n*/\n(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? factory() :\n typeof define === 'function' && define.amd ? define(factory) :\n (factory());\n}(this, (function () { 'use strict';\n\n/**\n * @license\n * Copyright Google Inc. All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.io/license\n */\n\n\nvar Zone$1 = (function (global) {\n if (global['Zone']) {\n throw new Error('Zone already loaded.');\n }\n var Zone = (function () {\n function Zone(parent, zoneSpec) {\n this._properties = null;\n this._parent = parent;\n this._name = zoneSpec ? zoneSpec.name || 'unnamed' : '';\n this._properties = zoneSpec && zoneSpec.properties || {};\n this._zoneDelegate =\n new ZoneDelegate(this, this._parent && this._parent._zoneDelegate, zoneSpec);\n }\n Zone.assertZonePatched = function () {\n if (global.Promise !== ZoneAwarePromise) {\n throw new Error('Zone.js has detected that ZoneAwarePromise `(window|global).Promise` ' +\n 'has been overwritten.\\n' +\n 'Most likely cause is that a Promise polyfill has been loaded ' +\n 'after Zone.js (Polyfilling Promise api is not necessary when zone.js is loaded. ' +\n 'If you must load one, do so before loading zone.js.)');\n }\n };\n Object.defineProperty(Zone, \"current\", {\n get: function () {\n return _currentZoneFrame.zone;\n },\n enumerable: true,\n configurable: true\n });\n \n Object.defineProperty(Zone, \"currentTask\", {\n get: function () {\n return _currentTask;\n },\n enumerable: true,\n configurable: true\n });\n \n Object.defineProperty(Zone.prototype, \"parent\", {\n get: function () {\n return this._parent;\n },\n enumerable: true,\n configurable: true\n });\n \n Object.defineProperty(Zone.prototype, \"name\", {\n get: function () {\n return this._name;\n },\n enumerable: true,\n configurable: true\n });\n \n Zone.prototype.get = function (key) {\n var zone = this.getZoneWith(key);\n if (zone)\n return zone._properties[key];\n };\n Zone.prototype.getZoneWith = function (key) {\n var current = this;\n while (current) {\n if (current._properties.hasOwnProperty(key)) {\n return current;\n }\n current = current._parent;\n }\n return null;\n };\n Zone.prototype.fork = function (zoneSpec) {\n if (!zoneSpec)\n throw new Error('ZoneSpec required!');\n return this._zoneDelegate.fork(this, zoneSpec);\n };\n Zone.prototype.wrap = function (callback, source) {\n if (typeof callback !== 'function') {\n throw new Error('Expecting function got: ' + callback);\n }\n var _callback = this._zoneDelegate.intercept(this, callback, source);\n var zone = this;\n return function () {\n return zone.runGuarded(_callback, this, arguments, source);\n };\n };\n Zone.prototype.run = function (callback, applyThis, applyArgs, source) {\n if (applyThis === void 0) { applyThis = null; }\n if (applyArgs === void 0) { applyArgs = null; }\n if (source === void 0) { source = null; }\n _currentZoneFrame = new ZoneFrame(_currentZoneFrame, this);\n try {\n return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source);\n }\n finally {\n _currentZoneFrame = _currentZoneFrame.parent;\n }\n };\n Zone.prototype.runGuarded = function (callback, applyThis, applyArgs, source) {\n if (applyThis === void 0) { applyThis = null; }\n if (applyArgs === void 0) { applyArgs = null; }\n if (source === void 0) { source = null; }\n _currentZoneFrame = new ZoneFrame(_currentZoneFrame, this);\n try {\n try {\n return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source);\n }\n catch (error) {\n if (this._zoneDelegate.handleError(this, error)) {\n throw error;\n }\n }\n }\n finally {\n _currentZoneFrame = _currentZoneFrame.parent;\n }\n };\n Zone.prototype.runTask = function (task, applyThis, applyArgs) {\n task.runCount++;\n if (task.zone != this)\n throw new Error('A task can only be run in the zone which created it! (Creation: ' + task.zone.name +\n '; Execution: ' + this.name + ')');\n var previousTask = _currentTask;\n _currentTask = task;\n _currentZoneFrame = new ZoneFrame(_currentZoneFrame, this);\n try {\n if (task.type == 'macroTask' && task.data && !task.data.isPeriodic) {\n task.cancelFn = null;\n }\n try {\n return this._zoneDelegate.invokeTask(this, task, applyThis, applyArgs);\n }\n catch (error) {\n if (this._zoneDelegate.handleError(this, error)) {\n throw error;\n }\n }\n }\n finally {\n _currentZoneFrame = _currentZoneFrame.parent;\n _currentTask = previousTask;\n }\n };\n Zone.prototype.scheduleMicroTask = function (source, callback, data, customSchedule) {\n return this._zoneDelegate.scheduleTask(this, new ZoneTask('microTask', this, source, callback, data, customSchedule, null));\n };\n Zone.prototype.scheduleMacroTask = function (source, callback, data, customSchedule, customCancel) {\n return this._zoneDelegate.scheduleTask(this, new ZoneTask('macroTask', this, source, callback, data, customSchedule, customCancel));\n };\n Zone.prototype.scheduleEventTask = function (source, callback, data, customSchedule, customCancel) {\n return this._zoneDelegate.scheduleTask(this, new ZoneTask('eventTask', this, source, callback, data, customSchedule, customCancel));\n };\n Zone.prototype.cancelTask = function (task) {\n var value = this._zoneDelegate.cancelTask(this, task);\n task.runCount = -1;\n task.cancelFn = null;\n return value;\n };\n Zone.__symbol__ = __symbol__;\n return Zone;\n }());\n \n var ZoneDelegate = (function () {\n function ZoneDelegate(zone, parentDelegate, zoneSpec) {\n this._taskCounts = { microTask: 0, macroTask: 0, eventTask: 0 };\n this.zone = zone;\n this._parentDelegate = parentDelegate;\n this._forkZS = zoneSpec && (zoneSpec && zoneSpec.onFork ? zoneSpec : parentDelegate._forkZS);\n this._forkDlgt = zoneSpec && (zoneSpec.onFork ? parentDelegate : parentDelegate._forkDlgt);\n this._forkCurrZone = zoneSpec && (zoneSpec.onFork ? this.zone : parentDelegate.zone);\n this._interceptZS =\n zoneSpec && (zoneSpec.onIntercept ? zoneSpec : parentDelegate._interceptZS);\n this._interceptDlgt =\n zoneSpec && (zoneSpec.onIntercept ? parentDelegate : parentDelegate._interceptDlgt);\n this._interceptCurrZone =\n zoneSpec && (zoneSpec.onIntercept ? this.zone : parentDelegate.zone);\n this._invokeZS = zoneSpec && (zoneSpec.onInvoke ? zoneSpec : parentDelegate._invokeZS);\n this._invokeDlgt =\n zoneSpec && (zoneSpec.onInvoke ? parentDelegate : parentDelegate._invokeDlgt);\n this._invokeCurrZone = zoneSpec && (zoneSpec.onInvoke ? this.zone : parentDelegate.zone);\n this._handleErrorZS =\n zoneSpec && (zoneSpec.onHandleError ? zoneSpec : parentDelegate._handleErrorZS);\n this._handleErrorDlgt =\n zoneSpec && (zoneSpec.onHandleError ? parentDelegate : parentDelegate._handleErrorDlgt);\n this._handleErrorCurrZone =\n zoneSpec && (zoneSpec.onHandleError ? this.zone : parentDelegate.zone);\n this._scheduleTaskZS =\n zoneSpec && (zoneSpec.onScheduleTask ? zoneSpec : parentDelegate._scheduleTaskZS);\n this._scheduleTaskDlgt =\n zoneSpec && (zoneSpec.onScheduleTask ? parentDelegate : parentDelegate._scheduleTaskDlgt);\n this._scheduleTaskCurrZone =\n zoneSpec && (zoneSpec.onScheduleTask ? this.zone : parentDelegate.zone);\n this._invokeTaskZS =\n zoneSpec && (zoneSpec.onInvokeTask ? zoneSpec : parentDelegate._invokeTaskZS);\n this._invokeTaskDlgt =\n zoneSpec && (zoneSpec.onInvokeTask ? parentDelegate : parentDelegate._invokeTaskDlgt);\n this._invokeTaskCurrZone =\n zoneSpec && (zoneSpec.onInvokeTask ? this.zone : parentDelegate.zone);\n this._cancelTaskZS =\n zoneSpec && (zoneSpec.onCancelTask ? zoneSpec : parentDelegate._cancelTaskZS);\n this._cancelTaskDlgt =\n zoneSpec && (zoneSpec.onCancelTask ? parentDelegate : parentDelegate._cancelTaskDlgt);\n this._cancelTaskCurrZone =\n zoneSpec && (zoneSpec.onCancelTask ? this.zone : parentDelegate.zone);\n this._hasTaskZS = zoneSpec && (zoneSpec.onHasTask ? zoneSpec : parentDelegate._hasTaskZS);\n this._hasTaskDlgt =\n zoneSpec && (zoneSpec.onHasTask ? parentDelegate : parentDelegate._hasTaskDlgt);\n this._hasTaskCurrZone = zoneSpec && (zoneSpec.onHasTask ? this.zone : parentDelegate.zone);\n }\n ZoneDelegate.prototype.fork = function (targetZone, zoneSpec) {\n return this._forkZS ? this._forkZS.onFork(this._forkDlgt, this.zone, targetZone, zoneSpec) :\n new Zone(targetZone, zoneSpec);\n };\n ZoneDelegate.prototype.intercept = function (targetZone, callback, source) {\n return this._interceptZS ?\n this._interceptZS.onIntercept(this._interceptDlgt, this._interceptCurrZone, targetZone, callback, source) :\n callback;\n };\n ZoneDelegate.prototype.invoke = function (targetZone, callback, applyThis, applyArgs, source) {\n return this._invokeZS ?\n this._invokeZS.onInvoke(this._invokeDlgt, this._invokeCurrZone, targetZone, callback, applyThis, applyArgs, source) :\n callback.apply(applyThis, applyArgs);\n };\n ZoneDelegate.prototype.handleError = function (targetZone, error) {\n return this._handleErrorZS ?\n this._handleErrorZS.onHandleError(this._handleErrorDlgt, this._handleErrorCurrZone, targetZone, error) :\n true;\n };\n ZoneDelegate.prototype.scheduleTask = function (targetZone, task) {\n try {\n if (this._scheduleTaskZS) {\n return this._scheduleTaskZS.onScheduleTask(this._scheduleTaskDlgt, this._scheduleTaskCurrZone, targetZone, task);\n }\n else if (task.scheduleFn) {\n task.scheduleFn(task);\n }\n else if (task.type == 'microTask') {\n scheduleMicroTask(task);\n }\n else {\n throw new Error('Task is missing scheduleFn.');\n }\n return task;\n }\n finally {\n if (targetZone == this.zone) {\n this._updateTaskCount(task.type, 1);\n }\n }\n };\n ZoneDelegate.prototype.invokeTask = function (targetZone, task, applyThis, applyArgs) {\n try {\n return this._invokeTaskZS ?\n this._invokeTaskZS.onInvokeTask(this._invokeTaskDlgt, this._invokeTaskCurrZone, targetZone, task, applyThis, applyArgs) :\n task.callback.apply(applyThis, applyArgs);\n }\n finally {\n if (targetZone == this.zone && (task.type != 'eventTask') &&\n !(task.data && task.data.isPeriodic)) {\n this._updateTaskCount(task.type, -1);\n }\n }\n };\n ZoneDelegate.prototype.cancelTask = function (targetZone, task) {\n var value;\n if (this._cancelTaskZS) {\n value = this._cancelTaskZS.onCancelTask(this._cancelTaskDlgt, this._cancelTaskCurrZone, targetZone, task);\n }\n else if (!task.cancelFn) {\n throw new Error('Task does not support cancellation, or is already canceled.');\n }\n else {\n value = task.cancelFn(task);\n }\n if (targetZone == this.zone) {\n // this should not be in the finally block, because exceptions assume not canceled.\n this._updateTaskCount(task.type, -1);\n }\n return value;\n };\n ZoneDelegate.prototype.hasTask = function (targetZone, isEmpty) {\n return this._hasTaskZS &&\n this._hasTaskZS.onHasTask(this._hasTaskDlgt, this._hasTaskCurrZone, targetZone, isEmpty);\n };\n ZoneDelegate.prototype._updateTaskCount = function (type, count) {\n var counts = this._taskCounts;\n var prev = counts[type];\n var next = counts[type] = prev + count;\n if (next < 0) {\n throw new Error('More tasks executed then were scheduled.');\n }\n if (prev == 0 || next == 0) {\n var isEmpty = {\n microTask: counts.microTask > 0,\n macroTask: counts.macroTask > 0,\n eventTask: counts.eventTask > 0,\n change: type\n };\n try {\n this.hasTask(this.zone, isEmpty);\n }\n finally {\n if (this._parentDelegate) {\n this._parentDelegate._updateTaskCount(type, count);\n }\n }\n }\n };\n return ZoneDelegate;\n }());\n var ZoneTask = (function () {\n function ZoneTask(type, zone, source, callback, options, scheduleFn, cancelFn) {\n this.runCount = 0;\n this.type = type;\n this.zone = zone;\n this.source = source;\n this.data = options;\n this.scheduleFn = scheduleFn;\n this.cancelFn = cancelFn;\n this.callback = callback;\n var self = this;\n this.invoke = function () {\n _numberOfNestedTaskFrames++;\n try {\n return zone.runTask(self, this, arguments);\n }\n finally {\n if (_numberOfNestedTaskFrames == 1) {\n drainMicroTaskQueue();\n }\n _numberOfNestedTaskFrames--;\n }\n };\n }\n ZoneTask.prototype.toString = function () {\n if (this.data && typeof this.data.handleId !== 'undefined') {\n return this.data.handleId;\n }\n else {\n return Object.prototype.toString.call(this);\n }\n };\n return ZoneTask;\n }());\n var ZoneFrame = (function () {\n function ZoneFrame(parent, zone) {\n this.parent = parent;\n this.zone = zone;\n }\n return ZoneFrame;\n }());\n function __symbol__(name) {\n return '__zone_symbol__' + name;\n }\n \n var symbolSetTimeout = __symbol__('setTimeout');\n var symbolPromise = __symbol__('Promise');\n var symbolThen = __symbol__('then');\n var _currentZoneFrame = new ZoneFrame(null, new Zone(null, null));\n var _currentTask = null;\n var _microTaskQueue = [];\n var _isDrainingMicrotaskQueue = false;\n var _uncaughtPromiseErrors = [];\n var _numberOfNestedTaskFrames = 0;\n function scheduleQueueDrain() {\n // if we are not running in any task, and there has not been anything scheduled\n // we must bootstrap the initial task creation by manually scheduling the drain\n if (_numberOfNestedTaskFrames === 0 && _microTaskQueue.length === 0) {\n // We are not running in Task, so we need to kickstart the microtask queue.\n if (global[symbolPromise]) {\n global[symbolPromise].resolve(0)[symbolThen](drainMicroTaskQueue);\n }\n else {\n global[symbolSetTimeout](drainMicroTaskQueue, 0);\n }\n }\n }\n function scheduleMicroTask(task) {\n scheduleQueueDrain();\n _microTaskQueue.push(task);\n }\n function consoleError(e) {\n var rejection = e && e.rejection;\n if (rejection) {\n console.error('Unhandled Promise rejection:', rejection instanceof Error ? rejection.message : rejection, '; Zone:', e.zone.name, '; Task:', e.task && e.task.source, '; Value:', rejection, rejection instanceof Error ? rejection.stack : undefined);\n }\n console.error(e);\n }\n function drainMicroTaskQueue() {\n if (!_isDrainingMicrotaskQueue) {\n _isDrainingMicrotaskQueue = true;\n while (_microTaskQueue.length) {\n var queue = _microTaskQueue;\n _microTaskQueue = [];\n for (var i = 0; i < queue.length; i++) {\n var task = queue[i];\n try {\n task.zone.runTask(task, null, null);\n }\n catch (e) {\n consoleError(e);\n }\n }\n }\n while (_uncaughtPromiseErrors.length) {\n var _loop_1 = function() {\n var uncaughtPromiseError = _uncaughtPromiseErrors.shift();\n try {\n uncaughtPromiseError.zone.runGuarded(function () {\n throw uncaughtPromiseError;\n });\n }\n catch (e) {\n consoleError(e);\n }\n };\n while (_uncaughtPromiseErrors.length) {\n _loop_1();\n }\n }\n _isDrainingMicrotaskQueue = false;\n }\n }\n function isThenable(value) {\n return value && value.then;\n }\n function forwardResolution(value) {\n return value;\n }\n function forwardRejection(rejection) {\n return ZoneAwarePromise.reject(rejection);\n }\n var symbolState = __symbol__('state');\n var symbolValue = __symbol__('value');\n var source = 'Promise.then';\n var UNRESOLVED = null;\n var RESOLVED = true;\n var REJECTED = false;\n var REJECTED_NO_CATCH = 0;\n function makeResolver(promise, state) {\n return function (v) {\n resolvePromise(promise, state, v);\n // Do not return value or you will break the Promise spec.\n };\n }\n function resolvePromise(promise, state, value) {\n if (promise[symbolState] === UNRESOLVED) {\n if (value instanceof ZoneAwarePromise && value.hasOwnProperty(symbolState) &&\n value.hasOwnProperty(symbolValue) && value[symbolState] !== UNRESOLVED) {\n clearRejectedNoCatch(value);\n resolvePromise(promise, value[symbolState], value[symbolValue]);\n }\n else if (isThenable(value)) {\n value.then(makeResolver(promise, state), makeResolver(promise, false));\n }\n else {\n promise[symbolState] = state;\n var queue = promise[symbolValue];\n promise[symbolValue] = value;\n for (var i = 0; i < queue.length;) {\n scheduleResolveOrReject(promise, queue[i++], queue[i++], queue[i++], queue[i++]);\n }\n if (queue.length == 0 && state == REJECTED) {\n promise[symbolState] = REJECTED_NO_CATCH;\n try {\n throw new Error('Uncaught (in promise): ' + value +\n (value && value.stack ? '\\n' + value.stack : ''));\n }\n catch (e) {\n var error_1 = e;\n error_1.rejection = value;\n error_1.promise = promise;\n error_1.zone = Zone.current;\n error_1.task = Zone.currentTask;\n _uncaughtPromiseErrors.push(error_1);\n scheduleQueueDrain();\n }\n }\n }\n }\n // Resolving an already resolved promise is a noop.\n return promise;\n }\n function clearRejectedNoCatch(promise) {\n if (promise[symbolState] === REJECTED_NO_CATCH) {\n promise[symbolState] = REJECTED;\n for (var i = 0; i < _uncaughtPromiseErrors.length; i++) {\n if (promise === _uncaughtPromiseErrors[i].promise) {\n _uncaughtPromiseErrors.splice(i, 1);\n break;\n }\n }\n }\n }\n function scheduleResolveOrReject(promise, zone, chainPromise, onFulfilled, onRejected) {\n clearRejectedNoCatch(promise);\n var delegate = promise[symbolState] ? onFulfilled || forwardResolution : onRejected || forwardRejection;\n zone.scheduleMicroTask(source, function () {\n try {\n resolvePromise(chainPromise, true, zone.run(delegate, null, [promise[symbolValue]]));\n }\n catch (error) {\n resolvePromise(chainPromise, false, error);\n }\n });\n }\n var ZoneAwarePromise = (function () {\n function ZoneAwarePromise(executor) {\n var promise = this;\n if (!(promise instanceof ZoneAwarePromise)) {\n throw new Error('Must be an instanceof Promise.');\n }\n promise[symbolState] = UNRESOLVED;\n promise[symbolValue] = []; // queue;\n try {\n executor && executor(makeResolver(promise, RESOLVED), makeResolver(promise, REJECTED));\n }\n catch (e) {\n resolvePromise(promise, false, e);\n }\n }\n ZoneAwarePromise.resolve = function (value) {\n return resolvePromise(new this(null), RESOLVED, value);\n };\n ZoneAwarePromise.reject = function (error) {\n return resolvePromise(new this(null), REJECTED, error);\n };\n ZoneAwarePromise.race = function (values) {\n var resolve;\n var reject;\n var promise = new this(function (res, rej) {\n _a = [res, rej], resolve = _a[0], reject = _a[1];\n var _a;\n });\n function onResolve(value) {\n promise && (promise = null || resolve(value));\n }\n function onReject(error) {\n promise && (promise = null || reject(error));\n }\n for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {\n var value = values_1[_i];\n if (!isThenable(value)) {\n value = this.resolve(value);\n }\n value.then(onResolve, onReject);\n }\n return promise;\n };\n ZoneAwarePromise.all = function (values) {\n var resolve;\n var reject;\n var promise = new this(function (res, rej) {\n resolve = res;\n reject = rej;\n });\n var count = 0;\n var resolvedValues = [];\n for (var _i = 0, values_2 = values; _i < values_2.length; _i++) {\n var value = values_2[_i];\n if (!isThenable(value)) {\n value = this.resolve(value);\n }\n value.then((function (index) { return function (value) {\n resolvedValues[index] = value;\n count--;\n if (!count) {\n resolve(resolvedValues);\n }\n }; })(count), reject);\n count++;\n }\n if (!count)\n resolve(resolvedValues);\n return promise;\n };\n ZoneAwarePromise.prototype.then = function (onFulfilled, onRejected) {\n var chainPromise = new this.constructor(null);\n var zone = Zone.current;\n if (this[symbolState] == UNRESOLVED) {\n this[symbolValue].push(zone, chainPromise, onFulfilled, onRejected);\n }\n else {\n scheduleResolveOrReject(this, zone, chainPromise, onFulfilled, onRejected);\n }\n return chainPromise;\n };\n ZoneAwarePromise.prototype.catch = function (onRejected) {\n return this.then(null, onRejected);\n };\n return ZoneAwarePromise;\n }());\n // Protect against aggressive optimizers dropping seemingly unused properties.\n // E.g. Closure Compiler in advanced mode.\n ZoneAwarePromise['resolve'] = ZoneAwarePromise.resolve;\n ZoneAwarePromise['reject'] = ZoneAwarePromise.reject;\n ZoneAwarePromise['race'] = ZoneAwarePromise.race;\n ZoneAwarePromise['all'] = ZoneAwarePromise.all;\n var NativePromise = global[__symbol__('Promise')] = global['Promise'];\n global['Promise'] = ZoneAwarePromise;\n function patchThen(NativePromise) {\n var NativePromiseProtototype = NativePromise.prototype;\n var NativePromiseThen = NativePromiseProtototype[__symbol__('then')] =\n NativePromiseProtototype.then;\n NativePromiseProtototype.then = function (onResolve, onReject) {\n var nativePromise = this;\n return new ZoneAwarePromise(function (resolve, reject) {\n NativePromiseThen.call(nativePromise, resolve, reject);\n })\n .then(onResolve, onReject);\n };\n }\n if (NativePromise) {\n patchThen(NativePromise);\n if (typeof global['fetch'] !== 'undefined') {\n var fetchPromise = void 0;\n try {\n // In MS Edge this throws\n fetchPromise = global['fetch']();\n }\n catch (e) {\n // In Chrome this throws instead.\n fetchPromise = global['fetch']('about:blank');\n }\n // ignore output to prevent error;\n fetchPromise.then(function () { return null; }, function () { return null; });\n if (fetchPromise.constructor != NativePromise &&\n fetchPromise.constructor != ZoneAwarePromise) {\n patchThen(fetchPromise.constructor);\n }\n }\n }\n // This is not part of public API, but it is usefull for tests, so we expose it.\n Promise[Zone.__symbol__('uncaughtPromiseErrors')] = _uncaughtPromiseErrors;\n /*\n * This code patches Error so that:\n * - It ignores un-needed stack frames.\n * - It Shows the associated Zone for reach frame.\n */\n var FrameType;\n (function (FrameType) {\n /// Skip this frame when printing out stack\n FrameType[FrameType[\"blackList\"] = 0] = \"blackList\";\n /// This frame marks zone transition\n FrameType[FrameType[\"transition\"] = 1] = \"transition\";\n })(FrameType || (FrameType = {}));\n var NativeError = global[__symbol__('Error')] = global.Error;\n // Store the frames which should be removed from the stack frames\n var blackListedStackFrames = {};\n // We must find the frame where Error was created, otherwise we assume we don't understand stack\n var zoneAwareFrame;\n global.Error = ZoneAwareError;\n // How should the stack frames be parsed.\n var frameParserStrategy = null;\n var stackRewrite = 'stackRewrite';\n /**\n * This is ZoneAwareError which processes the stack frame and cleans up extra frames as well as\n * adds zone information to it.\n */\n function ZoneAwareError() {\n // Create an Error.\n var error = NativeError.apply(this, arguments);\n this.message = error.message;\n // Save original stack trace\n this.originalStack = error.stack;\n // Process the stack trace and rewrite the frames.\n if (ZoneAwareError[stackRewrite] && this.originalStack) {\n var frames_1 = this.originalStack.split('\\n');\n var zoneFrame = _currentZoneFrame;\n var i = 0;\n // Find the first frame\n while (frames_1[i] !== zoneAwareFrame && i < frames_1.length) {\n i++;\n }\n for (; i < frames_1.length && zoneFrame; i++) {\n var frame = frames_1[i];\n if (frame.trim()) {\n var frameType = blackListedStackFrames.hasOwnProperty(frame) && blackListedStackFrames[frame];\n if (frameType === FrameType.blackList) {\n frames_1.splice(i, 1);\n i--;\n }\n else if (frameType === FrameType.transition) {\n if (zoneFrame.parent) {\n // This is the special frame where zone changed. Print and process it accordingly\n frames_1[i] += \" [\" + zoneFrame.parent.zone.name + \" => \" + zoneFrame.zone.name + \"]\";\n zoneFrame = zoneFrame.parent;\n }\n else {\n zoneFrame = null;\n }\n }\n else {\n frames_1[i] += \" [\" + zoneFrame.zone.name + \"]\";\n }\n }\n }\n this.stack = this.zoneAwareStack = frames_1.join('\\n');\n }\n }\n \n // Copy the prototype so that instanceof operator works as expected\n ZoneAwareError.prototype = Object.create(NativeError.prototype);\n ZoneAwareError[Zone.__symbol__('blacklistedStackFrames')] = blackListedStackFrames;\n ZoneAwareError[stackRewrite] = false;\n if (NativeError.hasOwnProperty('stackTraceLimit')) {\n // Extend default stack limit as we will be removing few frames.\n NativeError.stackTraceLimit = Math.max(NativeError.stackTraceLimit, 15);\n // make sure that ZoneAwareError has the same property which forwards to NativeError.\n Object.defineProperty(ZoneAwareError, 'stackTraceLimit', {\n get: function () {\n return NativeError.stackTraceLimit;\n },\n set: function (value) {\n return NativeError.stackTraceLimit = value;\n }\n });\n }\n if (NativeError.hasOwnProperty('captureStackTrace')) {\n Object.defineProperty(ZoneAwareError, 'captureStackTrace', {\n value: function (targetObject, constructorOpt) {\n NativeError.captureStackTrace(targetObject, constructorOpt);\n }\n });\n }\n Object.defineProperty(ZoneAwareError, 'prepareStackTrace', {\n get: function () {\n return NativeError.prepareStackTrace;\n },\n set: function (value) {\n return NativeError.prepareStackTrace = value;\n }\n });\n // Now we need to populet the `blacklistedStackFrames` as well as find the\n // Now we need to populet the `blacklistedStackFrames` as well as find the\n // run/runGuraded/runTask frames. This is done by creating a detect zone and then threading\n // the execution through all of the above methods so that we can look at the stack trace and\n // find the frames of interest.\n var detectZone = Zone.current.fork({\n name: 'detect',\n onInvoke: function (parentZoneDelegate, currentZone, targetZone, delegate, applyThis, applyArgs, source) {\n // Here only so that it will show up in the stack frame so that it can be black listed.\n return parentZoneDelegate.invoke(targetZone, delegate, applyThis, applyArgs, source);\n },\n onHandleError: function (parentZD, current, target, error) {\n if (error.originalStack && Error === ZoneAwareError) {\n var frames_2 = error.originalStack.split(/\\n/);\n var runFrame = false, runGuardedFrame = false, runTaskFrame = false;\n while (frames_2.length) {\n var frame = frames_2.shift();\n // On safari it is possible to have stack frame with no line number.\n // This check makes sure that we don't filter frames on name only (must have\n // linenumber)\n if (/:\\d+:\\d+/.test(frame)) {\n // Get rid of the path so that we don't accidintely find function name in path.\n // In chrome the seperator is `(` and `@` in FF and safari\n // Chrome: at Zone.run (zone.js:100)\n // Chrome: at Zone.run (http://localhost:9876/base/build/lib/zone.js:100:24)\n // FireFox: Zone.prototype.run@http://localhost:9876/base/build/lib/zone.js:101:24\n // Safari: run@http://localhost:9876/base/build/lib/zone.js:101:24\n var fnName = frame.split('(')[0].split('@')[0];\n var frameType = FrameType.transition;\n if (fnName.indexOf('ZoneAwareError') !== -1) {\n zoneAwareFrame = frame;\n }\n if (fnName.indexOf('runGuarded') !== -1) {\n runGuardedFrame = true;\n }\n else if (fnName.indexOf('runTask') !== -1) {\n runTaskFrame = true;\n }\n else if (fnName.indexOf('run') !== -1) {\n runFrame = true;\n }\n else {\n frameType = FrameType.blackList;\n }\n blackListedStackFrames[frame] = frameType;\n // Once we find all of the frames we can stop looking.\n if (runFrame && runGuardedFrame && runTaskFrame) {\n ZoneAwareError[stackRewrite] = true;\n break;\n }\n }\n }\n }\n return false;\n }\n });\n // carefully constructor a stack frame which contains all of the frames of interest which\n // need to be detected and blacklisted.\n var detectRunFn = function () {\n detectZone.run(function () {\n detectZone.runGuarded(function () {\n throw new Error('blacklistStackFrames');\n });\n });\n };\n // Cause the error to extract the stack frames.\n detectZone.runTask(detectZone.scheduleMacroTask('detect', detectRunFn, null, function () { return null; }, null));\n return global['Zone'] = Zone;\n})(typeof window === 'object' && window || typeof self === 'object' && self || global);\n\n/**\n * @license\n * Copyright Google Inc. All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.io/license\n */\nvar zoneSymbol = function (n) { return (\"__zone_symbol__\" + n); };\nvar _global$1 = typeof window === 'object' && window || typeof self === 'object' && self || global;\nfunction bindArguments(args, source) {\n for (var i = args.length - 1; i >= 0; i--) {\n if (typeof args[i] === 'function') {\n args[i] = Zone.current.wrap(args[i], source + '_' + i);\n }\n }\n return args;\n}\nfunction patchPrototype(prototype, fnNames) {\n var source = prototype.constructor['name'];\n var _loop_1 = function(i) {\n var name_1 = fnNames[i];\n var delegate = prototype[name_1];\n if (delegate) {\n prototype[name_1] = (function (delegate) {\n return function () {\n return delegate.apply(this, bindArguments(arguments, source + '.' + name_1));\n };\n })(delegate);\n }\n };\n for (var i = 0; i < fnNames.length; i++) {\n _loop_1(i);\n }\n}\nvar isWebWorker = (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope);\nvar isNode = (!('nw' in _global$1) && typeof process !== 'undefined' &&\n {}.toString.call(process) === '[object process]');\nvar isBrowser = !isNode && !isWebWorker && !!(typeof window !== 'undefined' && window['HTMLElement']);\nfunction patchProperty(obj, prop) {\n var desc = Object.getOwnPropertyDescriptor(obj, prop) || { enumerable: true, configurable: true };\n var originalDesc = Object.getOwnPropertyDescriptor(obj, 'original' + prop);\n if (!originalDesc && desc.get) {\n Object.defineProperty(obj, 'original' + prop, { enumerable: false, configurable: true, get: desc.get });\n }\n // A property descriptor cannot have getter/setter and be writable\n // deleting the writable and value properties avoids this error:\n //\n // TypeError: property descriptors must not specify a value or be writable when a\n // getter or setter has been specified\n delete desc.writable;\n delete desc.value;\n // substr(2) cuz 'onclick' -> 'click', etc\n var eventName = prop.substr(2);\n var _prop = '_' + prop;\n desc.set = function (fn) {\n if (this[_prop]) {\n this.removeEventListener(eventName, this[_prop]);\n }\n if (typeof fn === 'function') {\n var wrapFn = function (event) {\n var result;\n result = fn.apply(this, arguments);\n if (result != undefined && !result)\n event.preventDefault();\n };\n this[_prop] = wrapFn;\n this.addEventListener(eventName, wrapFn, false);\n }\n else {\n this[_prop] = null;\n }\n };\n // The getter would return undefined for unassigned properties but the default value of an\n // unassigned property is null\n desc.get = function () {\n var r = this[_prop] || null;\n // result will be null when use inline event attribute,\n // such as \n // because the onclick function is internal raw uncompiled handler\n // the onclick will be evaluated when first time event was triggered or\n // the property is accessed, https://github.com/angular/zone.js/issues/525\n // so we should use original native get to retrive the handler\n if (r === null) {\n var oriDesc = Object.getOwnPropertyDescriptor(obj, 'original' + prop);\n if (oriDesc && oriDesc.get) {\n r = oriDesc.get.apply(this, arguments);\n if (r) {\n desc.set.apply(this, [r]);\n this.removeAttribute(prop);\n }\n }\n }\n return this[_prop] || null;\n };\n Object.defineProperty(obj, prop, desc);\n}\n\nfunction patchOnProperties(obj, properties) {\n var onProperties = [];\n for (var prop in obj) {\n if (prop.substr(0, 2) == 'on') {\n onProperties.push(prop);\n }\n }\n for (var j = 0; j < onProperties.length; j++) {\n patchProperty(obj, onProperties[j]);\n }\n if (properties) {\n for (var i = 0; i < properties.length; i++) {\n patchProperty(obj, 'on' + properties[i]);\n }\n }\n}\n\nvar EVENT_TASKS = zoneSymbol('eventTasks');\n// For EventTarget\nvar ADD_EVENT_LISTENER = 'addEventListener';\nvar REMOVE_EVENT_LISTENER = 'removeEventListener';\nfunction findExistingRegisteredTask(target, handler, name, capture, remove) {\n var eventTasks = target[EVENT_TASKS];\n if (eventTasks) {\n for (var i = 0; i < eventTasks.length; i++) {\n var eventTask = eventTasks[i];\n var data = eventTask.data;\n var listener = data.handler;\n if ((data.handler === handler || listener.listener === handler) &&\n data.useCapturing === capture && data.eventName === name) {\n if (remove) {\n eventTasks.splice(i, 1);\n }\n return eventTask;\n }\n }\n }\n return null;\n}\nfunction findAllExistingRegisteredTasks(target, name, capture, remove) {\n var eventTasks = target[EVENT_TASKS];\n if (eventTasks) {\n var result = [];\n for (var i = eventTasks.length - 1; i >= 0; i--) {\n var eventTask = eventTasks[i];\n var data = eventTask.data;\n if (data.eventName === name && data.useCapturing === capture) {\n result.push(eventTask);\n if (remove) {\n eventTasks.splice(i, 1);\n }\n }\n }\n return result;\n }\n return null;\n}\nfunction attachRegisteredEvent(target, eventTask, isPrepend) {\n var eventTasks = target[EVENT_TASKS];\n if (!eventTasks) {\n eventTasks = target[EVENT_TASKS] = [];\n }\n if (isPrepend) {\n eventTasks.unshift(eventTask);\n }\n else {\n eventTasks.push(eventTask);\n }\n}\nvar defaultListenerMetaCreator = function (self, args) {\n return {\n useCapturing: args[2],\n eventName: args[0],\n handler: args[1],\n target: self || _global$1,\n name: args[0],\n invokeAddFunc: function (addFnSymbol, delegate) {\n if (delegate && delegate.invoke) {\n return this.target[addFnSymbol](this.eventName, delegate.invoke, this.useCapturing);\n }\n else {\n return this.target[addFnSymbol](this.eventName, delegate, this.useCapturing);\n }\n },\n invokeRemoveFunc: function (removeFnSymbol, delegate) {\n if (delegate && delegate.invoke) {\n return this.target[removeFnSymbol](this.eventName, delegate.invoke, this.useCapturing);\n }\n else {\n return this.target[removeFnSymbol](this.eventName, delegate, this.useCapturing);\n }\n }\n };\n};\nfunction makeZoneAwareAddListener(addFnName, removeFnName, useCapturingParam, allowDuplicates, isPrepend, metaCreator) {\n if (useCapturingParam === void 0) { useCapturingParam = true; }\n if (allowDuplicates === void 0) { allowDuplicates = false; }\n if (isPrepend === void 0) { isPrepend = false; }\n if (metaCreator === void 0) { metaCreator = defaultListenerMetaCreator; }\n var addFnSymbol = zoneSymbol(addFnName);\n var removeFnSymbol = zoneSymbol(removeFnName);\n var defaultUseCapturing = useCapturingParam ? false : undefined;\n function scheduleEventListener(eventTask) {\n var meta = eventTask.data;\n attachRegisteredEvent(meta.target, eventTask, isPrepend);\n return meta.invokeAddFunc(addFnSymbol, eventTask);\n }\n function cancelEventListener(eventTask) {\n var meta = eventTask.data;\n findExistingRegisteredTask(meta.target, eventTask.invoke, meta.eventName, meta.useCapturing, true);\n return meta.invokeRemoveFunc(removeFnSymbol, eventTask);\n }\n return function zoneAwareAddListener(self, args) {\n var data = metaCreator(self, args);\n data.useCapturing = data.useCapturing || defaultUseCapturing;\n // - Inside a Web Worker, `this` is undefined, the context is `global`\n // - When `addEventListener` is called on the global context in strict mode, `this` is undefined\n // see https://github.com/angular/zone.js/issues/190\n var delegate = null;\n if (typeof data.handler == 'function') {\n delegate = data.handler;\n }\n else if (data.handler && data.handler.handleEvent) {\n delegate = function (event) { return data.handler.handleEvent(event); };\n }\n var validZoneHandler = false;\n try {\n // In cross site contexts (such as WebDriver frameworks like Selenium),\n // accessing the handler object here will cause an exception to be thrown which\n // will fail tests prematurely.\n validZoneHandler = data.handler && data.handler.toString() === '[object FunctionWrapper]';\n }\n catch (e) {\n // Returning nothing here is fine, because objects in a cross-site context are unusable\n return;\n }\n // Ignore special listeners of IE11 & Edge dev tools, see\n // https://github.com/angular/zone.js/issues/150\n if (!delegate || validZoneHandler) {\n return data.invokeAddFunc(addFnSymbol, data.handler);\n }\n if (!allowDuplicates) {\n var eventTask = findExistingRegisteredTask(data.target, data.handler, data.eventName, data.useCapturing, false);\n if (eventTask) {\n // we already registered, so this will have noop.\n return data.invokeAddFunc(addFnSymbol, eventTask);\n }\n }\n var zone = Zone.current;\n var source = data.target.constructor['name'] + '.' + addFnName + ':' + data.eventName;\n zone.scheduleEventTask(source, delegate, data, scheduleEventListener, cancelEventListener);\n };\n}\nfunction makeZoneAwareRemoveListener(fnName, useCapturingParam, metaCreator) {\n if (useCapturingParam === void 0) { useCapturingParam = true; }\n if (metaCreator === void 0) { metaCreator = defaultListenerMetaCreator; }\n var symbol = zoneSymbol(fnName);\n var defaultUseCapturing = useCapturingParam ? false : undefined;\n return function zoneAwareRemoveListener(self, args) {\n var data = metaCreator(self, args);\n data.useCapturing = data.useCapturing || defaultUseCapturing;\n // - Inside a Web Worker, `this` is undefined, the context is `global`\n // - When `addEventListener` is called on the global context in strict mode, `this` is undefined\n // see https://github.com/angular/zone.js/issues/190\n var eventTask = findExistingRegisteredTask(data.target, data.handler, data.eventName, data.useCapturing, true);\n if (eventTask) {\n eventTask.zone.cancelTask(eventTask);\n }\n else {\n data.invokeRemoveFunc(symbol, data.handler);\n }\n };\n}\n\n\nvar zoneAwareAddEventListener = makeZoneAwareAddListener(ADD_EVENT_LISTENER, REMOVE_EVENT_LISTENER);\nvar zoneAwareRemoveEventListener = makeZoneAwareRemoveListener(REMOVE_EVENT_LISTENER);\nfunction patchEventTargetMethods(obj, addFnName, removeFnName, metaCreator) {\n if (addFnName === void 0) { addFnName = ADD_EVENT_LISTENER; }\n if (removeFnName === void 0) { removeFnName = REMOVE_EVENT_LISTENER; }\n if (metaCreator === void 0) { metaCreator = defaultListenerMetaCreator; }\n if (obj && obj[addFnName]) {\n patchMethod(obj, addFnName, function () { return makeZoneAwareAddListener(addFnName, removeFnName, true, false, false, metaCreator); });\n patchMethod(obj, removeFnName, function () { return makeZoneAwareRemoveListener(removeFnName, true, metaCreator); });\n return true;\n }\n else {\n return false;\n }\n}\nvar originalInstanceKey = zoneSymbol('originalInstance');\n// wrap some native API on `window`\nfunction patchClass(className) {\n var OriginalClass = _global$1[className];\n if (!OriginalClass)\n return;\n _global$1[className] = function () {\n var a = bindArguments(arguments, className);\n switch (a.length) {\n case 0:\n this[originalInstanceKey] = new OriginalClass();\n break;\n case 1:\n this[originalInstanceKey] = new OriginalClass(a[0]);\n break;\n case 2:\n this[originalInstanceKey] = new OriginalClass(a[0], a[1]);\n break;\n case 3:\n this[originalInstanceKey] = new OriginalClass(a[0], a[1], a[2]);\n break;\n case 4:\n this[originalInstanceKey] = new OriginalClass(a[0], a[1], a[2], a[3]);\n break;\n default:\n throw new Error('Arg list too long.');\n }\n };\n var instance = new OriginalClass(function () { });\n var prop;\n for (prop in instance) {\n // https://bugs.webkit.org/show_bug.cgi?id=44721\n if (className === 'XMLHttpRequest' && prop === 'responseBlob')\n continue;\n (function (prop) {\n if (typeof instance[prop] === 'function') {\n _global$1[className].prototype[prop] = function () {\n return this[originalInstanceKey][prop].apply(this[originalInstanceKey], arguments);\n };\n }\n else {\n Object.defineProperty(_global$1[className].prototype, prop, {\n set: function (fn) {\n if (typeof fn === 'function') {\n this[originalInstanceKey][prop] = Zone.current.wrap(fn, className + '.' + prop);\n }\n else {\n this[originalInstanceKey][prop] = fn;\n }\n },\n get: function () {\n return this[originalInstanceKey][prop];\n }\n });\n }\n }(prop));\n }\n for (prop in OriginalClass) {\n if (prop !== 'prototype' && OriginalClass.hasOwnProperty(prop)) {\n _global$1[className][prop] = OriginalClass[prop];\n }\n }\n}\n\nfunction createNamedFn(name, delegate) {\n try {\n return (Function('f', \"return function \" + name + \"(){return f(this, arguments)}\"))(delegate);\n }\n catch (e) {\n // if we fail, we must be CSP, just return delegate.\n return function () {\n return delegate(this, arguments);\n };\n }\n}\nfunction patchMethod(target, name, patchFn) {\n var proto = target;\n while (proto && Object.getOwnPropertyNames(proto).indexOf(name) === -1) {\n proto = Object.getPrototypeOf(proto);\n }\n if (!proto && target[name]) {\n // somehow we did not find it, but we can see it. This happens on IE for Window properties.\n proto = target;\n }\n var delegateName = zoneSymbol(name);\n var delegate;\n if (proto && !(delegate = proto[delegateName])) {\n delegate = proto[delegateName] = proto[name];\n proto[name] = createNamedFn(name, patchFn(delegate, delegateName, name));\n }\n return delegate;\n}\n\n/**\n * @license\n * Copyright Google Inc. All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.io/license\n */\nfunction patchTimer(window, setName, cancelName, nameSuffix) {\n var setNative = null;\n var clearNative = null;\n setName += nameSuffix;\n cancelName += nameSuffix;\n var tasksByHandleId = {};\n function scheduleTask(task) {\n var data = task.data;\n data.args[0] = function () {\n task.invoke.apply(this, arguments);\n delete tasksByHandleId[data.handleId];\n };\n data.handleId = setNative.apply(window, data.args);\n tasksByHandleId[data.handleId] = task;\n return task;\n }\n function clearTask(task) {\n delete tasksByHandleId[task.data.handleId];\n return clearNative(task.data.handleId);\n }\n setNative =\n patchMethod(window, setName, function (delegate) { return function (self, args) {\n if (typeof args[0] === 'function') {\n var zone = Zone.current;\n var options = {\n handleId: null,\n isPeriodic: nameSuffix === 'Interval',\n delay: (nameSuffix === 'Timeout' || nameSuffix === 'Interval') ? args[1] || 0 : null,\n args: args\n };\n var task = zone.scheduleMacroTask(setName, args[0], options, scheduleTask, clearTask);\n if (!task) {\n return task;\n }\n // Node.js must additionally support the ref and unref functions.\n var handle = task.data.handleId;\n if (handle.ref && handle.unref) {\n task.ref = handle.ref.bind(handle);\n task.unref = handle.unref.bind(handle);\n }\n return task;\n }\n else {\n // cause an error by calling it directly.\n return delegate.apply(window, args);\n }\n }; });\n clearNative =\n patchMethod(window, cancelName, function (delegate) { return function (self, args) {\n var task = typeof args[0] === 'number' ? tasksByHandleId[args[0]] : args[0];\n if (task && typeof task.type === 'string') {\n if (task.cancelFn && task.data.isPeriodic || task.runCount === 0) {\n // Do not cancel already canceled functions\n task.zone.cancelTask(task);\n }\n }\n else {\n // cause an error by calling it directly.\n delegate.apply(window, args);\n }\n }; });\n}\n\n/**\n * @license\n * Copyright Google Inc. All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.io/license\n */\n/*\n * This is necessary for Chrome and Chrome mobile, to enable\n * things like redefining `createdCallback` on an element.\n */\nvar _defineProperty = Object[zoneSymbol('defineProperty')] = Object.defineProperty;\nvar _getOwnPropertyDescriptor = Object[zoneSymbol('getOwnPropertyDescriptor')] =\n Object.getOwnPropertyDescriptor;\nvar _create = Object.create;\nvar unconfigurablesKey = zoneSymbol('unconfigurables');\nfunction propertyPatch() {\n Object.defineProperty = function (obj, prop, desc) {\n if (isUnconfigurable(obj, prop)) {\n throw new TypeError('Cannot assign to read only property \\'' + prop + '\\' of ' + obj);\n }\n var originalConfigurableFlag = desc.configurable;\n if (prop !== 'prototype') {\n desc = rewriteDescriptor(obj, prop, desc);\n }\n return _tryDefineProperty(obj, prop, desc, originalConfigurableFlag);\n };\n Object.defineProperties = function (obj, props) {\n Object.keys(props).forEach(function (prop) {\n Object.defineProperty(obj, prop, props[prop]);\n });\n return obj;\n };\n Object.create = function (obj, proto) {\n if (typeof proto === 'object' && !Object.isFrozen(proto)) {\n Object.keys(proto).forEach(function (prop) {\n proto[prop] = rewriteDescriptor(obj, prop, proto[prop]);\n });\n }\n return _create(obj, proto);\n };\n Object.getOwnPropertyDescriptor = function (obj, prop) {\n var desc = _getOwnPropertyDescriptor(obj, prop);\n if (isUnconfigurable(obj, prop)) {\n desc.configurable = false;\n }\n return desc;\n };\n}\n\nfunction _redefineProperty(obj, prop, desc) {\n var originalConfigurableFlag = desc.configurable;\n desc = rewriteDescriptor(obj, prop, desc);\n return _tryDefineProperty(obj, prop, desc, originalConfigurableFlag);\n}\n\nfunction isUnconfigurable(obj, prop) {\n return obj && obj[unconfigurablesKey] && obj[unconfigurablesKey][prop];\n}\nfunction rewriteDescriptor(obj, prop, desc) {\n desc.configurable = true;\n if (!desc.configurable) {\n if (!obj[unconfigurablesKey]) {\n _defineProperty(obj, unconfigurablesKey, { writable: true, value: {} });\n }\n obj[unconfigurablesKey][prop] = true;\n }\n return desc;\n}\nfunction _tryDefineProperty(obj, prop, desc, originalConfigurableFlag) {\n try {\n return _defineProperty(obj, prop, desc);\n }\n catch (e) {\n if (desc.configurable) {\n // In case of errors, when the configurable flag was likely set by rewriteDescriptor(), let's\n // retry with the original flag value\n if (typeof originalConfigurableFlag == 'undefined') {\n delete desc.configurable;\n }\n else {\n desc.configurable = originalConfigurableFlag;\n }\n try {\n return _defineProperty(obj, prop, desc);\n }\n catch (e) {\n var descJson = null;\n try {\n descJson = JSON.stringify(desc);\n }\n catch (e) {\n descJson = descJson.toString();\n }\n console.log(\"Attempting to configure '\" + prop + \"' with descriptor '\" + descJson + \"' on object '\" + obj + \"' and got error, giving up: \" + e);\n }\n }\n else {\n throw e;\n }\n }\n}\n\n/**\n * @license\n * Copyright Google Inc. All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.io/license\n */\nvar WTF_ISSUE_555 = 'Anchor,Area,Audio,BR,Base,BaseFont,Body,Button,Canvas,Content,DList,Directory,Div,Embed,FieldSet,Font,Form,Frame,FrameSet,HR,Head,Heading,Html,IFrame,Image,Input,Keygen,LI,Label,Legend,Link,Map,Marquee,Media,Menu,Meta,Meter,Mod,OList,Object,OptGroup,Option,Output,Paragraph,Pre,Progress,Quote,Script,Select,Source,Span,Style,TableCaption,TableCell,TableCol,Table,TableRow,TableSection,TextArea,Title,Track,UList,Unknown,Video';\nvar NO_EVENT_TARGET = 'ApplicationCache,EventSource,FileReader,InputMethodContext,MediaController,MessagePort,Node,Performance,SVGElementInstance,SharedWorker,TextTrack,TextTrackCue,TextTrackList,WebKitNamedFlow,Window,Worker,WorkerGlobalScope,XMLHttpRequest,XMLHttpRequestEventTarget,XMLHttpRequestUpload,IDBRequest,IDBOpenDBRequest,IDBDatabase,IDBTransaction,IDBCursor,DBIndex,WebSocket'\n .split(',');\nvar EVENT_TARGET = 'EventTarget';\nfunction eventTargetPatch(_global) {\n var apis = [];\n var isWtf = _global['wtf'];\n if (isWtf) {\n // Workaround for: https://github.com/google/tracing-framework/issues/555\n apis = WTF_ISSUE_555.split(',').map(function (v) { return 'HTML' + v + 'Element'; }).concat(NO_EVENT_TARGET);\n }\n else if (_global[EVENT_TARGET]) {\n apis.push(EVENT_TARGET);\n }\n else {\n // Note: EventTarget is not available in all browsers,\n // if it's not available, we instead patch the APIs in the IDL that inherit from EventTarget\n apis = NO_EVENT_TARGET;\n }\n for (var i = 0; i < apis.length; i++) {\n var type = _global[apis[i]];\n patchEventTargetMethods(type && type.prototype);\n }\n}\n\n/**\n * @license\n * Copyright Google Inc. All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.io/license\n */\n// we have to patch the instance since the proto is non-configurable\nfunction apply(_global) {\n var WS = _global.WebSocket;\n // On Safari window.EventTarget doesn't exist so need to patch WS add/removeEventListener\n // On older Chrome, no need since EventTarget was already patched\n if (!_global.EventTarget) {\n patchEventTargetMethods(WS.prototype);\n }\n _global.WebSocket = function (a, b) {\n var socket = arguments.length > 1 ? new WS(a, b) : new WS(a);\n var proxySocket;\n // Safari 7.0 has non-configurable own 'onmessage' and friends properties on the socket instance\n var onmessageDesc = Object.getOwnPropertyDescriptor(socket, 'onmessage');\n if (onmessageDesc && onmessageDesc.configurable === false) {\n proxySocket = Object.create(socket);\n ['addEventListener', 'removeEventListener', 'send', 'close'].forEach(function (propName) {\n proxySocket[propName] = function () {\n return socket[propName].apply(socket, arguments);\n };\n });\n }\n else {\n // we can patch the real socket\n proxySocket = socket;\n }\n patchOnProperties(proxySocket, ['close', 'error', 'message', 'open']);\n return proxySocket;\n };\n for (var prop in WS) {\n _global.WebSocket[prop] = WS[prop];\n }\n}\n\n/**\n * @license\n * Copyright Google Inc. All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.io/license\n */\nvar eventNames = 'copy cut paste abort blur focus canplay canplaythrough change click contextmenu dblclick drag dragend dragenter dragleave dragover dragstart drop durationchange emptied ended input invalid keydown keypress keyup load loadeddata loadedmetadata loadstart message mousedown mouseenter mouseleave mousemove mouseout mouseover mouseup pause play playing progress ratechange reset scroll seeked seeking select show stalled submit suspend timeupdate volumechange waiting mozfullscreenchange mozfullscreenerror mozpointerlockchange mozpointerlockerror error webglcontextrestored webglcontextlost webglcontextcreationerror'\n .split(' ');\nfunction propertyDescriptorPatch(_global) {\n if (isNode) {\n return;\n }\n var supportsWebSocket = typeof WebSocket !== 'undefined';\n if (canPatchViaPropertyDescriptor()) {\n // for browsers that we can patch the descriptor: Chrome & Firefox\n if (isBrowser) {\n patchOnProperties(HTMLElement.prototype, eventNames);\n }\n patchOnProperties(XMLHttpRequest.prototype, null);\n if (typeof IDBIndex !== 'undefined') {\n patchOnProperties(IDBIndex.prototype, null);\n patchOnProperties(IDBRequest.prototype, null);\n patchOnProperties(IDBOpenDBRequest.prototype, null);\n patchOnProperties(IDBDatabase.prototype, null);\n patchOnProperties(IDBTransaction.prototype, null);\n patchOnProperties(IDBCursor.prototype, null);\n }\n if (supportsWebSocket) {\n patchOnProperties(WebSocket.prototype, null);\n }\n }\n else {\n // Safari, Android browsers (Jelly Bean)\n patchViaCapturingAllTheEvents();\n patchClass('XMLHttpRequest');\n if (supportsWebSocket) {\n apply(_global);\n }\n }\n}\nfunction canPatchViaPropertyDescriptor() {\n if (isBrowser && !Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onclick') &&\n typeof Element !== 'undefined') {\n // WebKit https://bugs.webkit.org/show_bug.cgi?id=134364\n // IDL interface attributes are not configurable\n var desc = Object.getOwnPropertyDescriptor(Element.prototype, 'onclick');\n if (desc && !desc.configurable)\n return false;\n }\n Object.defineProperty(XMLHttpRequest.prototype, 'onreadystatechange', {\n get: function () {\n return true;\n }\n });\n var req = new XMLHttpRequest();\n var result = !!req.onreadystatechange;\n Object.defineProperty(XMLHttpRequest.prototype, 'onreadystatechange', {});\n return result;\n}\n\nvar unboundKey = zoneSymbol('unbound');\n// Whenever any eventListener fires, we check the eventListener target and all parents\n// for `onwhatever` properties and replace them with zone-bound functions\n// - Chrome (for now)\nfunction patchViaCapturingAllTheEvents() {\n var _loop_1 = function(i) {\n var property = eventNames[i];\n var onproperty = 'on' + property;\n self.addEventListener(property, function (event) {\n var elt = event.target, bound, source;\n if (elt) {\n source = elt.constructor['name'] + '.' + onproperty;\n }\n else {\n source = 'unknown.' + onproperty;\n }\n while (elt) {\n if (elt[onproperty] && !elt[onproperty][unboundKey]) {\n bound = Zone.current.wrap(elt[onproperty], source);\n bound[unboundKey] = elt[onproperty];\n elt[onproperty] = bound;\n }\n elt = elt.parentElement;\n }\n }, true);\n };\n for (var i = 0; i < eventNames.length; i++) {\n _loop_1(i);\n }\n \n}\n\n/**\n * @license\n * Copyright Google Inc. All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.io/license\n */\nfunction registerElementPatch(_global) {\n if (!isBrowser || !('registerElement' in _global.document)) {\n return;\n }\n var _registerElement = document.registerElement;\n var callbacks = ['createdCallback', 'attachedCallback', 'detachedCallback', 'attributeChangedCallback'];\n document.registerElement = function (name, opts) {\n if (opts && opts.prototype) {\n callbacks.forEach(function (callback) {\n var source = 'Document.registerElement::' + callback;\n if (opts.prototype.hasOwnProperty(callback)) {\n var descriptor = Object.getOwnPropertyDescriptor(opts.prototype, callback);\n if (descriptor && descriptor.value) {\n descriptor.value = Zone.current.wrap(descriptor.value, source);\n _redefineProperty(opts.prototype, callback, descriptor);\n }\n else {\n opts.prototype[callback] = Zone.current.wrap(opts.prototype[callback], source);\n }\n }\n else if (opts.prototype[callback]) {\n opts.prototype[callback] = Zone.current.wrap(opts.prototype[callback], source);\n }\n });\n }\n return _registerElement.apply(document, [name, opts]);\n };\n}\n\n/**\n * @license\n * Copyright Google Inc. All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.io/license\n */\nvar set = 'set';\nvar clear = 'clear';\nvar blockingMethods = ['alert', 'prompt', 'confirm'];\nvar _global = typeof window === 'object' && window || typeof self === 'object' && self || global;\npatchTimer(_global, set, clear, 'Timeout');\npatchTimer(_global, set, clear, 'Interval');\npatchTimer(_global, set, clear, 'Immediate');\npatchTimer(_global, 'request', 'cancel', 'AnimationFrame');\npatchTimer(_global, 'mozRequest', 'mozCancel', 'AnimationFrame');\npatchTimer(_global, 'webkitRequest', 'webkitCancel', 'AnimationFrame');\nfor (var i = 0; i < blockingMethods.length; i++) {\n var name = blockingMethods[i];\n patchMethod(_global, name, function (delegate, symbol, name) {\n return function (s, args) {\n return Zone.current.run(delegate, _global, args, name);\n };\n });\n}\neventTargetPatch(_global);\npropertyDescriptorPatch(_global);\npatchClass('MutationObserver');\npatchClass('WebKitMutationObserver');\npatchClass('FileReader');\npropertyPatch();\nregisterElementPatch(_global);\n// Treat XMLHTTPRequest as a macrotask.\npatchXHR(_global);\nvar XHR_TASK = zoneSymbol('xhrTask');\nvar XHR_SYNC = zoneSymbol('xhrSync');\nvar XHR_LISTENER = zoneSymbol('xhrListener');\nvar XHR_SCHEDULED = zoneSymbol('xhrScheduled');\nfunction patchXHR(window) {\n function findPendingTask(target) {\n var pendingTask = target[XHR_TASK];\n return pendingTask;\n }\n function scheduleTask(task) {\n self[XHR_SCHEDULED] = false;\n var data = task.data;\n // remove existing event listener\n var listener = data.target[XHR_LISTENER];\n if (listener) {\n data.target.removeEventListener('readystatechange', listener);\n }\n var newListener = data.target[XHR_LISTENER] = function () {\n if (data.target.readyState === data.target.DONE) {\n if (!data.aborted && self[XHR_SCHEDULED]) {\n task.invoke();\n }\n }\n };\n data.target.addEventListener('readystatechange', newListener);\n var storedTask = data.target[XHR_TASK];\n if (!storedTask) {\n data.target[XHR_TASK] = task;\n }\n sendNative.apply(data.target, data.args);\n self[XHR_SCHEDULED] = true;\n return task;\n }\n function placeholderCallback() { }\n function clearTask(task) {\n var data = task.data;\n // Note - ideally, we would call data.target.removeEventListener here, but it's too late\n // to prevent it from firing. So instead, we store info for the event listener.\n data.aborted = true;\n return abortNative.apply(data.target, data.args);\n }\n var openNative = patchMethod(window.XMLHttpRequest.prototype, 'open', function () { return function (self, args) {\n self[XHR_SYNC] = args[2] == false;\n return openNative.apply(self, args);\n }; });\n var sendNative = patchMethod(window.XMLHttpRequest.prototype, 'send', function () { return function (self, args) {\n var zone = Zone.current;\n if (self[XHR_SYNC]) {\n // if the XHR is sync there is no task to schedule, just execute the code.\n return sendNative.apply(self, args);\n }\n else {\n var options = { target: self, isPeriodic: false, delay: null, args: args, aborted: false };\n return zone.scheduleMacroTask('XMLHttpRequest.send', placeholderCallback, options, scheduleTask, clearTask);\n }\n }; });\n var abortNative = patchMethod(window.XMLHttpRequest.prototype, 'abort', function (delegate) { return function (self, args) {\n var task = findPendingTask(self);\n if (task && typeof task.type == 'string') {\n // If the XHR has already completed, do nothing.\n if (task.cancelFn == null) {\n return;\n }\n task.zone.cancelTask(task);\n }\n // Otherwise, we are trying to abort an XHR which has not yet been sent, so there is no task\n // to cancel. Do nothing.\n }; });\n}\n/// GEO_LOCATION\nif (_global['navigator'] && _global['navigator'].geolocation) {\n patchPrototype(_global['navigator'].geolocation, ['getCurrentPosition', 'watchPosition']);\n}\n\n/**\n * @license\n * Copyright Google Inc. All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.io/license\n */\n\n})));\n", From 135f960485eeb579b7eb3374d8b92c3e41b34d8a Mon Sep 17 00:00:00 2001 From: Patrick Hulce Date: Fri, 24 Aug 2018 15:46:19 -0700 Subject: [PATCH 11/32] rebase --- lighthouse-core/runner.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lighthouse-core/runner.js b/lighthouse-core/runner.js index 9892b352f463..6726877a5fd7 100644 --- a/lighthouse-core/runner.js +++ b/lighthouse-core/runner.js @@ -146,7 +146,7 @@ class Runner { // Summarize all the timings and drop onto the LHR log.timeEnd(runnerStatus); - lhr.timing.entries.push(...log.getEntries()); + lhr.timing.entries.push(...log.takeTimeEntries()); const runnerEntry = lhr.timing.entries.find(e => e.name === 'lh:runner:run'); if (runnerEntry) { lhr.timing.total = runnerEntry.duration; @@ -156,7 +156,7 @@ class Runner { rendererFormattedStrings: i18n.getRendererFormattedStrings(settings.locale), icuMessagePaths: i18n.replaceIcuMessageInstanceIds(lhr, settings.locale), }; - + // Create the HTML, JSON, or CSV string const report = generateReport(lhr, settings.output); @@ -187,7 +187,7 @@ class Runner { settings: runnerOpts.config.settings, }; const artifacts = await GatherRunner.run(runnerOpts.config.passes, gatherOpts); - artifacts.Timing = log.getEntries(); + artifacts.Timing = log.takeTimeEntries(); return artifacts; } @@ -239,7 +239,7 @@ class Runner { const audit = auditDefn.implementation; const status = { msg: `Evaluating: ${i18n.getFormatted(audit.meta.title, 'en-US')}`, - id: `lh:audit:${audit.meta.name}`, + id: `lh:audit:${audit.meta.id}`, }; log.time(status); From 2715db97cbfc7dd41a45cc98f499e60ff172de79 Mon Sep 17 00:00:00 2001 From: Paul Irish Date: Mon, 27 Aug 2018 12:42:38 -0700 Subject: [PATCH 12/32] use l-logger 1.1.0 --- package.json | 2 +- yarn.lock | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index 6410cb787ed3..32c1c48ea53e 100644 --- a/package.json +++ b/package.json @@ -124,7 +124,7 @@ "intl-messageformat-parser": "^1.4.0", "jpeg-js": "0.1.2", "js-library-detector": "^4.3.1", - "lighthouse-logger": "^1.0.0", + "lighthouse-logger": "^1.1.0", "lodash.isequal": "^4.5.0", "lookup-closest-locale": "6.0.4", "metaviewport-parser": "0.2.0", diff --git a/yarn.lock b/yarn.lock index 56fb7980575f..28c70ee9f7cf 100644 --- a/yarn.lock +++ b/yarn.lock @@ -3945,6 +3945,13 @@ lighthouse-logger@^1.0.0: dependencies: debug "^2.6.8" +lighthouse-logger@^1.1.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/lighthouse-logger/-/lighthouse-logger-1.1.0.tgz#1a355ce5d477f39b184ece1926a5f3627abd833d" + dependencies: + debug "^2.6.8" + marky "^1.2.0" + load-json-file@^1.0.0: version "1.1.0" resolved "https://registry.yarnpkg.com/load-json-file/-/load-json-file-1.1.0.tgz#956905708d58b4bab4c2261b04f59f31c99374c0" @@ -4220,6 +4227,10 @@ map-visit@^1.0.0: dependencies: object-visit "^1.0.0" +marky@^1.2.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/marky/-/marky-1.2.0.tgz#9617ed647bbbea8f45d19526da33dec70606df42" + md5-hex@^1.2.0: version "1.3.0" resolved "https://registry.yarnpkg.com/md5-hex/-/md5-hex-1.3.0.tgz#d2c4afe983c4370662179b8cad145219135046c4" From 4807052d79aa17afd0bc81b9773e8b0478a34ff1 Mon Sep 17 00:00:00 2001 From: Paul Irish Date: Mon, 27 Aug 2018 12:42:46 -0700 Subject: [PATCH 13/32] instrument getBenchmarkIndex --- lighthouse-core/gather/driver.js | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/lighthouse-core/gather/driver.js b/lighthouse-core/gather/driver.js index 5806d353e8e0..db1b73d5ff6b 100644 --- a/lighthouse-core/gather/driver.js +++ b/lighthouse-core/gather/driver.js @@ -115,8 +115,12 @@ class Driver { * Computes the ULTRADUMB™ benchmark index to get a rough estimate of device class. * @return {Promise} */ - getBenchmarkIndex() { - return this.evaluateAsync(`(${pageFunctions.ultradumbBenchmark.toString()})()`); + async getBenchmarkIndex() { + const status = {msg: 'Benchmarking machine', id: 'lh:gather:getBenchmarkIndex'}; + log.time(status); + const indexVal = await this.evaluateAsync(`(${pageFunctions.ultradumbBenchmark.toString()})()`); + log.timeEnd(status); + return indexVal; } /** From fc8817f32ffbe091a6c284ec0e74094d0a0b4dc3 Mon Sep 17 00:00:00 2001 From: Paul Irish Date: Tue, 28 Aug 2018 15:37:53 -0700 Subject: [PATCH 14/32] minor --- lighthouse-core/config/config.js | 4 ++-- lighthouse-core/lib/timing-trace-saver.js | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/lighthouse-core/config/config.js b/lighthouse-core/config/config.js index e4ef379b84af..5d3a26b482fc 100644 --- a/lighthouse-core/config/config.js +++ b/lighthouse-core/config/config.js @@ -710,7 +710,7 @@ class Config { */ static requireAudits(audits, configPath) { const status = {msg: 'Requiring audits', id: 'lh:config:requireAudits'}; - log.time(status); + log.time(status, 'verbose'); const expandedAudits = Config.expandAuditShorthand(audits); if (!expandedAudits) { return null; @@ -785,7 +785,7 @@ class Config { return null; } const status = {msg: 'Requiring gatherers', id: 'lh:config:requireGatherers'}; - log.time(status); + log.time(status, 'verbose'); const coreList = Runner.getGathererList(); const fullPasses = passes.map(pass => { diff --git a/lighthouse-core/lib/timing-trace-saver.js b/lighthouse-core/lib/timing-trace-saver.js index 888f23517060..33529ec06360 100644 --- a/lighthouse-core/lib/timing-trace-saver.js +++ b/lighthouse-core/lib/timing-trace-saver.js @@ -18,7 +18,7 @@ function checkEventOverlap(entry, prevEntries) { const thisEnd = entry.startTime + entry.duration; const isOverlap = prevEnd > entry.startTime && prevEnd < thisEnd; if (isOverlap) { - throw new Error(`Two measures overlap! ${prevEntry.name} & ${entry.name}`); + console.error(`Two measures overlap! ${prevEntry.name} & ${entry.name}`); } } } From 46e66ab53f15dac91422279682c2ebf7395138b1 Mon Sep 17 00:00:00 2001 From: Paul Irish Date: Tue, 28 Aug 2018 15:38:32 -0700 Subject: [PATCH 15/32] instrument computed artifacts --- lighthouse-core/gather/computed/computed-artifact.js | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/lighthouse-core/gather/computed/computed-artifact.js b/lighthouse-core/gather/computed/computed-artifact.js index 53d36d79957d..1670d5dfb4e3 100644 --- a/lighthouse-core/gather/computed/computed-artifact.js +++ b/lighthouse-core/gather/computed/computed-artifact.js @@ -6,6 +6,7 @@ 'use strict'; const ArbitraryEqualityMap = require('../../lib/arbitrary-equality-map'); +const log = require('lighthouse-logger'); class ComputedArtifact { /** @@ -59,12 +60,15 @@ class ComputedArtifact { return computed; } + const status = {msg: `Computing artifact: ${this.name}`, id: `lh:computed:${this.name}`}; + log.time(status, 'verbose'); // Need to cast since `this.compute_(...)` returns the concrete return type // of the base class's compute_, not the called derived class's. const artifactPromise = /** @type {ReturnType} */ ( - this.compute_(requiredArtifacts, this._allComputedArtifacts)); + await this.compute_(requiredArtifacts, this._allComputedArtifacts)); this._cache.set(requiredArtifacts, artifactPromise); + log.timeEnd(status); return artifactPromise; } } From 9125d0530551648b6e41e9d89ec415cd041cca97 Mon Sep 17 00:00:00 2001 From: Paul Irish Date: Tue, 28 Aug 2018 15:39:11 -0700 Subject: [PATCH 16/32] keep artifacts.Timing up to date --- lighthouse-core/runner.js | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/lighthouse-core/runner.js b/lighthouse-core/runner.js index 6726877a5fd7..c4ae3142b86f 100644 --- a/lighthouse-core/runner.js +++ b/lighthouse-core/runner.js @@ -124,6 +124,13 @@ class Runner { log.timeEnd(resultsStatus); + // Summarize all the timings and drop onto the LHR + try { + log.timeEnd(runnerStatus); + } catch (e) {} + artifacts.Timing.push(...log.takeTimeEntries()); + const runnerEntry = artifacts.Timing.find(e => e.name === 'lh:runner:run') + /** @type {LH.Result} */ const lhr = { userAgent: artifacts.HostUserAgent, @@ -141,17 +148,9 @@ class Runner { configSettings: settings, categories, categoryGroups: runOpts.config.groups || undefined, - timing: {entries: artifacts.Timing || [], total: 0}, + timing: {entries: artifacts.Timing, total: runnerEntry && runnerEntry.duration || 0}, }; - // Summarize all the timings and drop onto the LHR - log.timeEnd(runnerStatus); - lhr.timing.entries.push(...log.takeTimeEntries()); - const runnerEntry = lhr.timing.entries.find(e => e.name === 'lh:runner:run'); - if (runnerEntry) { - lhr.timing.total = runnerEntry.duration; - } - lhr.i18n = { rendererFormattedStrings: i18n.getRendererFormattedStrings(settings.locale), icuMessagePaths: i18n.replaceIcuMessageInstanceIds(lhr, settings.locale), From 680a985d8a4987df499fafb7f2cbddcc6878475b Mon Sep 17 00:00:00 2001 From: Paul Irish Date: Tue, 25 Sep 2018 16:21:28 -0700 Subject: [PATCH 17/32] feedback --- lighthouse-core/gather/gather-runner.js | 3 +-- lighthouse-core/lib/asset-saver.js | 4 ++-- lighthouse-core/lib/timing-trace-saver.js | 6 ++++-- lighthouse-core/runner.js | 2 +- lighthouse-core/scripts/generate-timing-trace.js | 2 +- 5 files changed, 9 insertions(+), 8 deletions(-) diff --git a/lighthouse-core/gather/gather-runner.js b/lighthouse-core/gather/gather-runner.js index b74f001274b7..bdac5d5876df 100644 --- a/lighthouse-core/gather/gather-runner.js +++ b/lighthouse-core/gather/gather-runner.js @@ -133,8 +133,7 @@ class GatherRunner { if (!(/close\/.*status: 500$/.test(err.message))) { log.error('GatherRunner disconnect', err.message); } - log.timeEnd(status); - }); + }).then(_ => log.timeEnd(status)) } /** diff --git a/lighthouse-core/lib/asset-saver.js b/lighthouse-core/lib/asset-saver.js index d01eb99bb349..2faa29b37c21 100644 --- a/lighthouse-core/lib/asset-saver.js +++ b/lighthouse-core/lib/asset-saver.js @@ -64,10 +64,10 @@ async function loadArtifacts(basePath) { }); if (Array.isArray(artifacts.Timing)) { - // Tag existing entries, so they can be rendered in parallel + // Any Timing entries in saved artifacts will have a different timeOrigin than the auditing phase + // The `gather` prop is read later in generate-timing-trace and they're added to a separate track of trace events artifacts.Timing.forEach(entry => (entry.gather = true)); } - return artifacts; } diff --git a/lighthouse-core/lib/timing-trace-saver.js b/lighthouse-core/lib/timing-trace-saver.js index 33529ec06360..c55687d2f6f8 100644 --- a/lighthouse-core/lib/timing-trace-saver.js +++ b/lighthouse-core/lib/timing-trace-saver.js @@ -9,7 +9,8 @@ * Technically, it's fine for usertiming measures to overlap, however non-async events make * for a much clearer UI in traceviewer. We do this check to make sure we aren't passing off * async-like measures as non-async. - * @param {!LH.Artifacts.MeasureEntry} entry user timing entry + * prevEntries are expected to be sorted by startTime + * @param {LH.Artifacts.MeasureEntry} entry user timing entry * @param {LH.Artifacts.MeasureEntry[]} prevEntries user timing entries */ function checkEventOverlap(entry, prevEntries) { @@ -32,7 +33,8 @@ function checkEventOverlap(entry, prevEntries) { function generateTraceEvents(entries, trackName = 'measures') { if (!Array.isArray(entries)) return []; - const currentTrace = /** @type {!LH.TraceEvent[]} */ ([]); + /** @type {!LH.TraceEvent[]} */ + const currentTrace = []; let id = 0; entries.sort((a, b) => a.startTime - b.startTime); diff --git a/lighthouse-core/runner.js b/lighthouse-core/runner.js index a4f314c6ba8d..57bd0b944580 100644 --- a/lighthouse-core/runner.js +++ b/lighthouse-core/runner.js @@ -158,7 +158,7 @@ class Runner { // Replace ICU message references with localized strings; save replaced paths in lhr. lhr.i18n.icuMessagePaths = i18n.replaceIcuMessageInstanceIds(lhr, settings.locale); - // Create the HTML, JSON, or CSV string + // Create the HTML, JSON, and/or CSV string const report = generateReport(lhr, settings.output); return {lhr, artifacts, report}; diff --git a/lighthouse-core/scripts/generate-timing-trace.js b/lighthouse-core/scripts/generate-timing-trace.js index b30795801eaf..28d3b58962a9 100644 --- a/lighthouse-core/scripts/generate-timing-trace.js +++ b/lighthouse-core/scripts/generate-timing-trace.js @@ -10,7 +10,7 @@ const path = require('path'); const {createTraceString} = require('../lib/timing-trace-saver'); /** - * @param {!string} msg + * @param {string} msg */ function printErrorAndQuit(msg) { // eslint-disable-next-line no-console From 1a0c8be0f7141ddd13aae97162ba0f5753b4fd26 Mon Sep 17 00:00:00 2001 From: Patrick Hulce Date: Tue, 16 Oct 2018 09:47:03 -0500 Subject: [PATCH 18/32] integrity for new packages --- yarn.lock | 2 ++ 1 file changed, 2 insertions(+) diff --git a/yarn.lock b/yarn.lock index a061687ddc28..00b81b8542bc 100644 --- a/yarn.lock +++ b/yarn.lock @@ -4581,6 +4581,7 @@ lighthouse-logger@^1.0.0: lighthouse-logger@^1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/lighthouse-logger/-/lighthouse-logger-1.1.0.tgz#1a355ce5d477f39b184ece1926a5f3627abd833d" + integrity sha512-l5/HppTtadQ9jyz6CoFPzEr/0zsr6tKL8e4wDBSlKDeaH5PZtI/Z/9YflLrds+uOhC3rk7xWCjIXqqhAjaQ+oA== dependencies: debug "^2.6.8" marky "^1.2.0" @@ -4917,6 +4918,7 @@ map-visit@^1.0.0: marky@^1.2.0: version "1.2.0" resolved "https://registry.yarnpkg.com/marky/-/marky-1.2.0.tgz#9617ed647bbbea8f45d19526da33dec70606df42" + integrity sha1-lhftZHu76o9F0ZUm2jPexwYG30I= md5-hex@^1.2.0: version "1.3.0" From caf144aadcf3a4d313ddfe45d98b33e32308d7d4 Mon Sep 17 00:00:00 2001 From: Patrick Hulce Date: Tue, 16 Oct 2018 09:49:09 -0500 Subject: [PATCH 19/32] lint --- lighthouse-core/gather/gather-runner.js | 10 +++++++--- lighthouse-core/lib/timing-trace-saver.js | 1 + lighthouse-core/runner.js | 2 +- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/lighthouse-core/gather/gather-runner.js b/lighthouse-core/gather/gather-runner.js index 85b5f7530d11..74394d5113e7 100644 --- a/lighthouse-core/gather/gather-runner.js +++ b/lighthouse-core/gather/gather-runner.js @@ -124,16 +124,20 @@ class GatherRunner { * @param {Driver} driver * @return {Promise} */ - static disposeDriver(driver) { + static async disposeDriver(driver) { const status = {msg: 'Disconnecting from browser...', id: 'lh:gather:disconnect'}; + log.time(status); - return driver.disconnect().catch(err => { + try { + await driver.disconnect(); + } catch (err) { // Ignore disconnecting error if browser was already closed. // See https://github.com/GoogleChrome/lighthouse/issues/1583 if (!(/close\/.*status: 500$/.test(err.message))) { log.error('GatherRunner disconnect', err.message); } - }).then(_ => log.timeEnd(status)) + } + log.timeEnd(status); } /** diff --git a/lighthouse-core/lib/timing-trace-saver.js b/lighthouse-core/lib/timing-trace-saver.js index c55687d2f6f8..794326d2d0fa 100644 --- a/lighthouse-core/lib/timing-trace-saver.js +++ b/lighthouse-core/lib/timing-trace-saver.js @@ -19,6 +19,7 @@ function checkEventOverlap(entry, prevEntries) { const thisEnd = entry.startTime + entry.duration; const isOverlap = prevEnd > entry.startTime && prevEnd < thisEnd; if (isOverlap) { + // eslint-disable-next-line no-console console.error(`Two measures overlap! ${prevEntry.name} & ${entry.name}`); } } diff --git a/lighthouse-core/runner.js b/lighthouse-core/runner.js index d44c0459f7eb..671dd6e24936 100644 --- a/lighthouse-core/runner.js +++ b/lighthouse-core/runner.js @@ -128,7 +128,7 @@ class Runner { log.timeEnd(runnerStatus); } catch (e) {} artifacts.Timing.push(...log.takeTimeEntries()); - const runnerEntry = artifacts.Timing.find(e => e.name === 'lh:runner:run') + const runnerEntry = artifacts.Timing.find(e => e.name === 'lh:runner:run'); /** @type {LH.Result} */ const lhr = { From 6046bb4120bbe9ee309320cc276fe8b06f6b3c9f Mon Sep 17 00:00:00 2001 From: Patrick Hulce Date: Tue, 16 Oct 2018 10:02:11 -0500 Subject: [PATCH 20/32] feedback and tests --- .../gather/computed/computed-artifact.js | 5 ++-- lighthouse-core/runner.js | 3 +++ .../scripts/generate-timing-trace.js | 8 +++++++ .../gather/computed/computed-artifact-test.js | 24 ++++++++++--------- .../test/lib/timing-trace-saver-test.js | 18 +++++++++++++- 5 files changed, 44 insertions(+), 14 deletions(-) diff --git a/lighthouse-core/gather/computed/computed-artifact.js b/lighthouse-core/gather/computed/computed-artifact.js index 0bb793f008e3..435a06d71189 100644 --- a/lighthouse-core/gather/computed/computed-artifact.js +++ b/lighthouse-core/gather/computed/computed-artifact.js @@ -65,11 +65,12 @@ class ComputedArtifact { // Need to cast since `this.compute_(...)` returns the concrete return type // of the base class's compute_, not the called derived class's. const artifactPromise = /** @type {ReturnType} */ ( - await this.compute_(requiredArtifacts, this._allComputedArtifacts)); + this.compute_(requiredArtifacts, this._allComputedArtifacts)); this._cache.set(requiredArtifacts, artifactPromise); + const artifactValue = await artifactPromise; log.timeEnd(status); - return artifactPromise; + return artifactValue; } } diff --git a/lighthouse-core/runner.js b/lighthouse-core/runner.js index 671dd6e24936..5b30862a6610 100644 --- a/lighthouse-core/runner.js +++ b/lighthouse-core/runner.js @@ -88,6 +88,9 @@ class Runner { } } + // Make sure artifacts.Timing exists if we're running off of old artifacts + if (!artifacts.Timing) artifacts.Timing = []; + // Potentially quit early if (settings.gatherMode && !settings.auditMode) return; diff --git a/lighthouse-core/scripts/generate-timing-trace.js b/lighthouse-core/scripts/generate-timing-trace.js index 28d3b58962a9..00c55bd55ce5 100644 --- a/lighthouse-core/scripts/generate-timing-trace.js +++ b/lighthouse-core/scripts/generate-timing-trace.js @@ -9,6 +9,14 @@ const fs = require('fs'); const path = require('path'); const {createTraceString} = require('../lib/timing-trace-saver'); +/** + * @fileoverview This script takes the timing entries saved during a Lighthouse run and generates + * a trace file that's readable in chrome://tracing. + * + * input = LHR.json + * output = LHR.timing.trace.json + */ + /** * @param {string} msg */ diff --git a/lighthouse-core/test/gather/computed/computed-artifact-test.js b/lighthouse-core/test/gather/computed/computed-artifact-test.js index 70a70293a28b..a6b535adf778 100644 --- a/lighthouse-core/test/gather/computed/computed-artifact-test.js +++ b/lighthouse-core/test/gather/computed/computed-artifact-test.js @@ -30,18 +30,20 @@ class TestComputedArtifact extends ComputedArtifact { } describe('ComputedArtifact base class', () => { - it('caches computed artifacts by strict equality', () => { + it('caches computed artifacts by strict equality', async () => { const computedArtifact = new TestComputedArtifact(); - return computedArtifact.request({x: 1}).then(result => { - assert.equal(result, 0); - }).then(_ => computedArtifact.request({x: 2})).then(result => { - assert.equal(result, 1); - }).then(_ => computedArtifact.request({x: 1})).then(result => { - assert.equal(result, 0); - }).then(_ => computedArtifact.request({x: 2})).then(result => { - assert.equal(result, 1); - assert.equal(computedArtifact.computeCounter, 2); - }); + let result = await computedArtifact.request({x: 1}); + assert.equal(result, 0); + + result = await computedArtifact.request({x: 2}); + assert.equal(result, 1); + + result = await computedArtifact.request({x: 1}); + assert.equal(result, 0); + + result = await computedArtifact.request({x: 2}); + assert.equal(result, 1); + assert.equal(computedArtifact.computeCounter, 2); }); }); diff --git a/lighthouse-core/test/lib/timing-trace-saver-test.js b/lighthouse-core/test/lib/timing-trace-saver-test.js index 70a01f8b476e..ae75a2680b5d 100644 --- a/lighthouse-core/test/lib/timing-trace-saver-test.js +++ b/lighthouse-core/test/lib/timing-trace-saver-test.js @@ -83,6 +83,19 @@ const expectedTrace = { describe('generateTraceEvents', () => { + let consoleError; + let origConsoleError; + + beforeEach(() => { + origConsoleError = console.error; + consoleError = jest.fn(); + console.error = consoleError; + }); + + afterEach(() => { + console.error = origConsoleError; + }); + it('generates a single trace event', () => { const event = generateTraceEvents(mockEntries); assert.deepStrictEqual(event.slice(0, 1), expectedTrace.traceEvents.slice(0, 1)); @@ -102,7 +115,10 @@ describe('generateTraceEvents', () => { entryType: 'measure', }, ]; - assert.throws(_ => generateTraceEvents(overlappingEntries), /measures overlap/); + + generateTraceEvents(overlappingEntries); + expect(consoleError).toHaveBeenCalled(); + expect(consoleError.mock.calls[0][0]).toContain('measures overlap'); }); }); From 01aeac7f187e2b122fa4a0eb9c77485ff733dc80 Mon Sep 17 00:00:00 2001 From: Patrick Hulce Date: Tue, 16 Oct 2018 10:07:42 -0500 Subject: [PATCH 21/32] last things? --- lighthouse-core/lib/timing-trace-saver.js | 1 + lighthouse-core/test/lib/timing-trace-saver-test.js | 6 +++++- typings/externs.d.ts | 1 + 3 files changed, 7 insertions(+), 1 deletion(-) diff --git a/lighthouse-core/lib/timing-trace-saver.js b/lighthouse-core/lib/timing-trace-saver.js index 794326d2d0fa..d093fa15a30a 100644 --- a/lighthouse-core/lib/timing-trace-saver.js +++ b/lighthouse-core/lib/timing-trace-saver.js @@ -42,6 +42,7 @@ function generateTraceEvents(entries, trackName = 'measures') { entries.forEach((entry, i) => { checkEventOverlap(entry, entries.slice(0, i)); + /** @type {LH.TraceEvent} */ const traceEvent = { name: entry.name, cat: entry.entryType, diff --git a/lighthouse-core/test/lib/timing-trace-saver-test.js b/lighthouse-core/test/lib/timing-trace-saver-test.js index ae75a2680b5d..be3749e9df4b 100644 --- a/lighthouse-core/test/lib/timing-trace-saver-test.js +++ b/lighthouse-core/test/lib/timing-trace-saver-test.js @@ -4,7 +4,11 @@ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ 'use strict'; -/* eslint-env mocha */ + +/* eslint-env jest */ + +/* eslint-disable no-console */ + const assert = require('assert'); const {generateTraceEvents, createTraceString} = require('../../lib/timing-trace-saver'); diff --git a/typings/externs.d.ts b/typings/externs.d.ts index 3e3d0784ed9f..344ba0df98ca 100644 --- a/typings/externs.d.ts +++ b/typings/externs.d.ts @@ -201,6 +201,7 @@ declare global { dur: number; ph: string; // one of 'B'|'b'|'D'|'E'|'e'|'F'|'I'|'M'|'N'|'n'|'O'|'R'|'S'|'T'|'X'; s?: 't'; + id?: string; } export interface DevToolsJsonTarget { From 852561bc96824fce24332392c5e19703bd95de7a Mon Sep 17 00:00:00 2001 From: Patrick Hulce Date: Tue, 16 Oct 2018 10:13:07 -0500 Subject: [PATCH 22/32] move artifacts.Timing --- lighthouse-core/gather/gather-runner.js | 3 +++ lighthouse-core/runner.js | 1 - 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/lighthouse-core/gather/gather-runner.js b/lighthouse-core/gather/gather-runner.js index 74394d5113e7..3fb2a4305162 100644 --- a/lighthouse-core/gather/gather-runner.js +++ b/lighthouse-core/gather/gather-runner.js @@ -395,6 +395,9 @@ class GatherRunner { // Take only unique LighthouseRunWarnings. baseArtifacts.LighthouseRunWarnings = Array.from(new Set(baseArtifacts.LighthouseRunWarnings)); + // Take the timing entries we've gathered so far. + baseArtifacts.Timing = log.takeTimeEntries(); + // TODO(bckenny): correct Partial at this point to drop cast. return /** @type {LH.Artifacts} */ ({...baseArtifacts, ...gathererArtifacts}); } diff --git a/lighthouse-core/runner.js b/lighthouse-core/runner.js index 5b30862a6610..e6a04a6c2ee1 100644 --- a/lighthouse-core/runner.js +++ b/lighthouse-core/runner.js @@ -190,7 +190,6 @@ class Runner { settings: runnerOpts.config.settings, }; const artifacts = await GatherRunner.run(runnerOpts.config.passes, gatherOpts); - artifacts.Timing = log.takeTimeEntries(); return artifacts; } From 3971b1f8daf7b19d3c34b0204f5e1208c3fdfb7c Mon Sep 17 00:00:00 2001 From: Patrick Hulce Date: Tue, 16 Oct 2018 10:29:32 -0500 Subject: [PATCH 23/32] type check --- lighthouse-core/lib/timing-trace-saver.js | 1 + typings/externs.d.ts | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/lighthouse-core/lib/timing-trace-saver.js b/lighthouse-core/lib/timing-trace-saver.js index d093fa15a30a..38872e4f05ba 100644 --- a/lighthouse-core/lib/timing-trace-saver.js +++ b/lighthouse-core/lib/timing-trace-saver.js @@ -65,6 +65,7 @@ function generateTraceEvents(entries, trackName = 'measures') { }); // Add labels + /** @type {LH.TraceEvent} */ const metaEvtBase = { pid: 0, tid: trackName === 'measures' ? 50 : 75, diff --git a/typings/externs.d.ts b/typings/externs.d.ts index 344ba0df98ca..7699e9e83741 100644 --- a/typings/externs.d.ts +++ b/typings/externs.d.ts @@ -199,7 +199,7 @@ declare global { tid: number; ts: number; dur: number; - ph: string; // one of 'B'|'b'|'D'|'E'|'e'|'F'|'I'|'M'|'N'|'n'|'O'|'R'|'S'|'T'|'X'; + ph: 'B'|'b'|'D'|'E'|'e'|'F'|'I'|'M'|'N'|'n'|'O'|'R'|'S'|'T'|'X'; s?: 't'; id?: string; } From 8bf6cc1bb7e107f52936934c8717d6d26ac5b309 Mon Sep 17 00:00:00 2001 From: Patrick Hulce Date: Tue, 16 Oct 2018 10:31:37 -0500 Subject: [PATCH 24/32] more nits --- lighthouse-core/lib/timing-trace-saver.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lighthouse-core/lib/timing-trace-saver.js b/lighthouse-core/lib/timing-trace-saver.js index 38872e4f05ba..078d4e2e3906 100644 --- a/lighthouse-core/lib/timing-trace-saver.js +++ b/lighthouse-core/lib/timing-trace-saver.js @@ -34,7 +34,7 @@ function checkEventOverlap(entry, prevEntries) { function generateTraceEvents(entries, trackName = 'measures') { if (!Array.isArray(entries)) return []; - /** @type {!LH.TraceEvent[]} */ + /** @type {LH.TraceEvent[]} */ const currentTrace = []; let id = 0; @@ -85,7 +85,7 @@ function generateTraceEvents(entries, trackName = 'measures') { /** * Writes a trace file to disk * @param {LH.Result} lhr - * @return {!string}; + * @return {string} */ function createTraceString(lhr) { const gatherEntries = lhr.timing.entries.filter(entry => entry.gather); From bcfaf7cca69f705aa2f7fa845039076a3e4945a7 Mon Sep 17 00:00:00 2001 From: Patrick Hulce Date: Wed, 17 Oct 2018 20:56:14 -0500 Subject: [PATCH 25/32] more feedback --- lighthouse-core/gather/computed/computed-artifact.js | 5 ++--- lighthouse-core/runner.js | 11 +++++------ 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/lighthouse-core/gather/computed/computed-artifact.js b/lighthouse-core/gather/computed/computed-artifact.js index 435a06d71189..7556bd9fb889 100644 --- a/lighthouse-core/gather/computed/computed-artifact.js +++ b/lighthouse-core/gather/computed/computed-artifact.js @@ -68,9 +68,8 @@ class ComputedArtifact { this.compute_(requiredArtifacts, this._allComputedArtifacts)); this._cache.set(requiredArtifacts, artifactPromise); - const artifactValue = await artifactPromise; - log.timeEnd(status); - return artifactValue; + artifactPromise.then(() => log.timeEnd(status)); + return artifactPromise; } } diff --git a/lighthouse-core/runner.js b/lighthouse-core/runner.js index e6a04a6c2ee1..fb2d072bd41e 100644 --- a/lighthouse-core/runner.js +++ b/lighthouse-core/runner.js @@ -88,9 +88,6 @@ class Runner { } } - // Make sure artifacts.Timing exists if we're running off of old artifacts - if (!artifacts.Timing) artifacts.Timing = []; - // Potentially quit early if (settings.gatherMode && !settings.auditMode) return; @@ -130,8 +127,10 @@ class Runner { try { log.timeEnd(runnerStatus); } catch (e) {} - artifacts.Timing.push(...log.takeTimeEntries()); - const runnerEntry = artifacts.Timing.find(e => e.name === 'lh:runner:run'); + + const timingEntries = artifacts.Timing || []; + timingEntries.push(...log.takeTimeEntries()); + const runnerEntry = timingEntries.find(e => e.name === 'lh:runner:run'); /** @type {LH.Result} */ const lhr = { @@ -151,7 +150,7 @@ class Runner { configSettings: settings, categories, categoryGroups: runOpts.config.groups || undefined, - timing: {entries: artifacts.Timing, total: runnerEntry && runnerEntry.duration || 0}, + timing: {entries: timingEntries, total: runnerEntry && runnerEntry.duration || 0}, i18n: { rendererFormattedStrings: i18n.getRendererFormattedStrings(settings.locale), icuMessagePaths: {}, From c72ac0cbda8a8e2b252332e98b69a2b119ba0307 Mon Sep 17 00:00:00 2001 From: Brendan Kenny Date: Thu, 18 Oct 2018 18:17:24 -0700 Subject: [PATCH 26/32] Update typings/artifacts.d.ts Co-Authored-By: paulirish --- typings/artifacts.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/typings/artifacts.d.ts b/typings/artifacts.d.ts index 2156f2e0ac0f..831c1afbf350 100644 --- a/typings/artifacts.d.ts +++ b/typings/artifacts.d.ts @@ -37,7 +37,7 @@ declare global { settings: Config.Settings; /** The URL initially requested and the post-redirects URL that was actually loaded. */ URL: {requestedUrl: string, finalUrl: string}; - /** Holds the timing instrumentation of a gather-only run */ + /** The timing instrumentation of the gather portion of a run. */ Timing: Artifacts.MeasureEntry[]; } From 274693a5ccd7b3fae79e874ef264d384fde0782d Mon Sep 17 00:00:00 2001 From: Paul Irish Date: Thu, 18 Oct 2018 18:18:52 -0700 Subject: [PATCH 27/32] Update artifacts.d.ts --- typings/artifacts.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/typings/artifacts.d.ts b/typings/artifacts.d.ts index 831c1afbf350..fdb11a261752 100644 --- a/typings/artifacts.d.ts +++ b/typings/artifacts.d.ts @@ -307,6 +307,7 @@ declare global { startTime: number; duration: number; entryType: string; + /** Whether timing entry was collected during artifact gathering. */ gather?: boolean; toJSON: any; } From bd0385981106197c7d6e909e6c4ea956c1148faf Mon Sep 17 00:00:00 2001 From: Paul Irish Date: Thu, 18 Oct 2018 18:48:24 -0700 Subject: [PATCH 28/32] drop try/catch --- lighthouse-core/runner.js | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/lighthouse-core/runner.js b/lighthouse-core/runner.js index fb2d072bd41e..ebcbf188477a 100644 --- a/lighthouse-core/runner.js +++ b/lighthouse-core/runner.js @@ -124,9 +124,7 @@ class Runner { log.timeEnd(resultsStatus); // Summarize all the timings and drop onto the LHR - try { - log.timeEnd(runnerStatus); - } catch (e) {} + log.timeEnd(runnerStatus); const timingEntries = artifacts.Timing || []; timingEntries.push(...log.takeTimeEntries()); From 434f7887ce43bab5f7b2200076c613291a9a9740 Mon Sep 17 00:00:00 2001 From: Connor Clark Date: Wed, 24 Oct 2018 13:52:14 -0700 Subject: [PATCH 29/32] use status object --- lighthouse-core/runner.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lighthouse-core/runner.js b/lighthouse-core/runner.js index 9e485e4855fc..83ea7b720894 100644 --- a/lighthouse-core/runner.js +++ b/lighthouse-core/runner.js @@ -199,7 +199,8 @@ class Runner { * @return {Promise>} */ static async _runAudits(settings, audits, artifacts, runWarnings) { - log.time({msg: 'Analyzing and running audits...', id: 'lh:runner:auditing'}); + const status = {msg: 'Analyzing and running audits...', id: 'lh:runner:auditing'}; + log.time(status); if (artifacts.settings) { const overrides = { @@ -231,7 +232,7 @@ class Runner { auditResults.push(auditResult); } - log.timeEnd({msg: 'Analyzing and running audits...', id: 'lh:runner:auditing'}); + log.timeEnd(status); return auditResults; } From 8c7b0a22683a503dc9bd7af40e355a7f8cf80cc7 Mon Sep 17 00:00:00 2001 From: Connor Clark Date: Wed, 24 Oct 2018 17:50:09 -0700 Subject: [PATCH 30/32] update lh logger. dedupe time measures --- lighthouse-core/gather/gather-runner.js | 2 +- lighthouse-core/runner.js | 13 +++++++++++-- package.json | 2 +- typings/lighthouse-logger/index.d.ts | 1 + yarn.lock | 8 ++++---- 5 files changed, 18 insertions(+), 8 deletions(-) diff --git a/lighthouse-core/gather/gather-runner.js b/lighthouse-core/gather/gather-runner.js index add130dbd1f7..d8d5463eb65f 100644 --- a/lighthouse-core/gather/gather-runner.js +++ b/lighthouse-core/gather/gather-runner.js @@ -400,7 +400,7 @@ class GatherRunner { baseArtifacts.LighthouseRunWarnings = Array.from(new Set(baseArtifacts.LighthouseRunWarnings)); // Take the timing entries we've gathered so far. - baseArtifacts.Timing = log.takeTimeEntries(); + baseArtifacts.Timing = log.getTimeEntries(); // TODO(bckenny): correct Partial at this point to drop cast. return /** @type {LH.Artifacts} */ ({...baseArtifacts, ...gathererArtifacts}); diff --git a/lighthouse-core/runner.js b/lighthouse-core/runner.js index 83ea7b720894..35dca54d7557 100644 --- a/lighthouse-core/runner.js +++ b/lighthouse-core/runner.js @@ -126,8 +126,17 @@ class Runner { // Summarize all the timings and drop onto the LHR log.timeEnd(runnerStatus); - const timingEntries = artifacts.Timing || []; - timingEntries.push(...log.takeTimeEntries()); + const timingEntriesFromArtifacts = /** @type {PerformanceEntry[]} */ artifacts.Timing || []; + const timingEntriesFromRunner = log.takeTimeEntries(); + const timingEntriesKeyValues = [ + ...timingEntriesFromArtifacts, + ...timingEntriesFromRunner, + ].map(entry => { + /** @type {[string, PerformanceEntry]} */ + const kv = [entry.name, entry]; + return kv; + }); + const timingEntries = Array.from(new Map(timingEntriesKeyValues).values()); const runnerEntry = timingEntries.find(e => e.name === 'lh:runner:run'); /** @type {LH.Result} */ diff --git a/package.json b/package.json index 1151d15e6f6c..192c4c4ffce3 100644 --- a/package.json +++ b/package.json @@ -141,7 +141,7 @@ "intl-messageformat-parser": "^1.4.0", "jpeg-js": "0.1.2", "js-library-detector": "^5.1.0", - "lighthouse-logger": "^1.1.0", + "lighthouse-logger": "^1.2.0", "lodash.isequal": "^4.5.0", "lookup-closest-locale": "6.0.4", "metaviewport-parser": "0.2.0", diff --git a/typings/lighthouse-logger/index.d.ts b/typings/lighthouse-logger/index.d.ts index 2863cda5ba40..f3f290a6c215 100644 --- a/typings/lighthouse-logger/index.d.ts +++ b/typings/lighthouse-logger/index.d.ts @@ -21,5 +21,6 @@ declare module 'lighthouse-logger' { export function reset(): string; /** Retrieves and clears all stored time entries */ export function takeTimeEntries(): PerformanceEntry[]; + export function getTimeEntries(): PerformanceEntry[]; export var events: import('events').EventEmitter; } diff --git a/yarn.lock b/yarn.lock index 621057ceb321..bf7a8b2a1947 100644 --- a/yarn.lock +++ b/yarn.lock @@ -5471,10 +5471,10 @@ lighthouse-logger@^1.0.0: dependencies: debug "^2.6.8" -lighthouse-logger@^1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/lighthouse-logger/-/lighthouse-logger-1.1.0.tgz#1a355ce5d477f39b184ece1926a5f3627abd833d" - integrity sha512-l5/HppTtadQ9jyz6CoFPzEr/0zsr6tKL8e4wDBSlKDeaH5PZtI/Z/9YflLrds+uOhC3rk7xWCjIXqqhAjaQ+oA== +lighthouse-logger@^1.2.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/lighthouse-logger/-/lighthouse-logger-1.2.0.tgz#b76d56935e9c137e86a04741f6bb9b2776e886ca" + integrity sha512-wzUvdIeJZhRsG6gpZfmSCfysaxNEr43i+QT+Hie94wvHDKFLi4n7C2GqZ4sTC+PH5b5iktmXJvU87rWvhP3lHw== dependencies: debug "^2.6.8" marky "^1.2.0" From 508506ad2f56d602fe27a2afe9398ffcebed9c45 Mon Sep 17 00:00:00 2001 From: Connor Clark Date: Wed, 24 Oct 2018 18:13:58 -0700 Subject: [PATCH 31/32] better code --- lighthouse-core/runner.js | 31 +++++++++++++++++-------------- typings/lhr.d.ts | 7 ++++++- 2 files changed, 23 insertions(+), 15 deletions(-) diff --git a/lighthouse-core/runner.js b/lighthouse-core/runner.js index 35dca54d7557..009f9b3ce2c8 100644 --- a/lighthouse-core/runner.js +++ b/lighthouse-core/runner.js @@ -126,19 +126,6 @@ class Runner { // Summarize all the timings and drop onto the LHR log.timeEnd(runnerStatus); - const timingEntriesFromArtifacts = /** @type {PerformanceEntry[]} */ artifacts.Timing || []; - const timingEntriesFromRunner = log.takeTimeEntries(); - const timingEntriesKeyValues = [ - ...timingEntriesFromArtifacts, - ...timingEntriesFromRunner, - ].map(entry => { - /** @type {[string, PerformanceEntry]} */ - const kv = [entry.name, entry]; - return kv; - }); - const timingEntries = Array.from(new Map(timingEntriesKeyValues).values()); - const runnerEntry = timingEntries.find(e => e.name === 'lh:runner:run'); - /** @type {LH.Result} */ const lhr = { userAgent: artifacts.HostUserAgent, @@ -157,7 +144,7 @@ class Runner { configSettings: settings, categories, categoryGroups: runOpts.config.groups || undefined, - timing: {entries: timingEntries, total: runnerEntry && runnerEntry.duration || 0}, + timing: this._getTiming(artifacts), i18n: { rendererFormattedStrings: i18n.getRendererFormattedStrings(settings.locale), icuMessagePaths: {}, @@ -177,6 +164,22 @@ class Runner { } } + /** + * @param {LH.Artifacts} artifacts + * @return {LH.Result.Timing} + */ + static _getTiming(artifacts) { + const timingEntriesFromArtifacts = artifacts.Timing || []; + const timingEntriesFromRunner = log.takeTimeEntries(); + const timingEntriesKeyValues = [ + ...timingEntriesFromArtifacts, + ...timingEntriesFromRunner, + ].map(entry => /** @type {[string, PerformanceEntry]} */ ([entry.name, entry])); + const timingEntries = Array.from(new Map(timingEntriesKeyValues).values()); + const runnerEntry = timingEntries.find(e => e.name === 'lh:runner:run'); + return {entries: timingEntries, total: runnerEntry && runnerEntry.duration || 0}; + } + /** * Establish connection, load page and collect all required artifacts * @param {string} requestedUrl diff --git a/typings/lhr.d.ts b/typings/lhr.d.ts index 6dfa033d695b..8c1403f40cc0 100644 --- a/typings/lhr.d.ts +++ b/typings/lhr.d.ts @@ -59,13 +59,18 @@ declare global { /** Information about the environment in which Lighthouse was run. */ environment: Environment; /** Execution timings for the Lighthouse run */ - timing: {entries: Artifacts.MeasureEntry[], total: number}; + timing: Result.Timing; /** The record of all formatted string locations in the LHR and their corresponding source values. */ i18n: {rendererFormattedStrings: I18NRendererStrings, icuMessagePaths: I18NMessages}; } // Result namespace export module Result { + export interface Timing { + entries: Artifacts.MeasureEntry[]; + total: number; + } + export interface Category { /** The string identifier of the category. */ id: string; From 4a2e662ab753bb0c77ea02cdef663aeef2cf6ed3 Mon Sep 17 00:00:00 2001 From: Connor Clark Date: Thu, 25 Oct 2018 10:30:32 -0700 Subject: [PATCH 32/32] pr changes --- lighthouse-core/runner.js | 5 +++-- lighthouse-core/scripts/generate-timing-trace.js | 2 +- package.json | 2 +- typings/artifacts.d.ts | 7 +------ 4 files changed, 6 insertions(+), 10 deletions(-) diff --git a/lighthouse-core/runner.js b/lighthouse-core/runner.js index 009f9b3ce2c8..a363974fd966 100644 --- a/lighthouse-core/runner.js +++ b/lighthouse-core/runner.js @@ -122,8 +122,6 @@ class Runner { } log.timeEnd(resultsStatus); - - // Summarize all the timings and drop onto the LHR log.timeEnd(runnerStatus); /** @type {LH.Result} */ @@ -165,6 +163,9 @@ class Runner { } /** + * This handles both the auditMode case where gatherer entries need to be merged in and + * the gather/audit case where timingEntriesFromRunner contains all entries from this run, + * including those also in timingEntriesFromArtifacts. * @param {LH.Artifacts} artifacts * @return {LH.Result.Timing} */ diff --git a/lighthouse-core/scripts/generate-timing-trace.js b/lighthouse-core/scripts/generate-timing-trace.js index 00c55bd55ce5..055311404d4c 100644 --- a/lighthouse-core/scripts/generate-timing-trace.js +++ b/lighthouse-core/scripts/generate-timing-trace.js @@ -25,7 +25,7 @@ function printErrorAndQuit(msg) { console.error(`ERROR: > ${msg} > Example: - > yarn timing results.json + > yarn timing-trace results.json `); process.exit(1); } diff --git a/package.json b/package.json index 192c4c4ffce3..6a163f76bc72 100644 --- a/package.json +++ b/package.json @@ -54,7 +54,7 @@ "deploy-viewer": "cd lighthouse-viewer && gulp deploy", "bundlesize": "bundlesize", "plots-smoke": "bash plots/test/smoke.sh", - "timing": "node lighthouse-core/scripts/generate-timing-trace.js", + "timing-trace": "node lighthouse-core/scripts/generate-timing-trace.js", "changelog": "conventional-changelog --config ./build/changelog-generator/index.js --infile changelog.md --same-file", "type-check": "tsc -p . && cd ./lighthouse-viewer && yarn type-check", "i18n:checks": "./lighthouse-core/scripts/i18n/assert-strings-collected.sh", diff --git a/typings/artifacts.d.ts b/typings/artifacts.d.ts index f45119fa6eb3..56e8e8337daa 100644 --- a/typings/artifacts.d.ts +++ b/typings/artifacts.d.ts @@ -306,14 +306,9 @@ declare global { }[]; } - export interface MeasureEntry { - name: string; - startTime: number; - duration: number; - entryType: string; + export interface MeasureEntry extends PerformanceEntry { /** Whether timing entry was collected during artifact gathering. */ gather?: boolean; - toJSON: any; } export interface MetricComputationDataInput {