all files / lighthouse-core/driver/drivers/ cri.js

10.34% Statements 6/58
7.69% Branches 2/26
0% Functions 0/8
10.53% Lines 6/57
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166                                                                                                                                                                                                                                                                                                                               
/**
 * @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 Driver = require('./driver.js');
const chromeRemoteInterface = require('chrome-remote-interface');
const port = process.env.PORT || 9222;
 
const log = require('../../lib/log.js');
 
class CriDriver extends Driver {
 
  /**
   * @return {!Promise<null>}
   */
  connect() {
    return new Promise((resolve, reject) => {
      if (this._chrome) {
        return resolve();
      }
 
      // Make a new tab, stopping Chrome from accidentally giving CRI an "Other" tab.
      // Also disable the lint check because CRI uses "New" for the function name.
      /* eslint-disable new-cap */
      chromeRemoteInterface.New((err, tab) => {
        if (err) {
          return reject(err);
        }
 
        chromeRemoteInterface({port: port, chooseTab: tab}, chrome => {
          this._tab = tab;
          this._chrome = chrome;
          this.beginLogging();
          this.enableRuntimeEvents().then(_ => {
            resolve();
          });
        }).on('error', e => reject(e));
      });
      /* eslint-enable new-cap */
    });
  }
 
  disconnect() {
    return new Promise((resolve, reject) => {
      if (!this._tab) {
        return resolve();
      }
 
      /* eslint-disable new-cap */
      chromeRemoteInterface.Close({
        id: this._tab.id
      }, err => {
        if (err) {
          reject(err);
        } else {
          resolve();
        }
      });
      /* eslint-enable new-cap */
    })
    .then(() => {
      if (this._chrome) {
        this._chrome.close();
      }
      this._tab = null;
      this._chrome = null;
      this.url = null;
    });
  }
 
  beginLogging() {
    // log events received
    this._chrome.on('event', req => _log('verbose', '<=', req));
  }
 
  /**
   * Bind listeners for protocol events
   * @param {!string} eventName
   * @param {function(...)} cb
   */
  on(eventName, cb) {
    if (this._chrome === null) {
      throw new Error('connect() must be called before attempting to listen to events.');
    }
    // log event listeners being bound
    _log('info', 'listen for event =>', {method: eventName});
    this._chrome.on(eventName, cb);
  }
 
  /**
   * Bind a one-time listener for protocol events. Listener is removed once it
   * has been called.
   * @param {!string} eventName
   * @param {function(...)} cb
   */
  once(eventName, cb) {
    if (this._chrome === null) {
      throw new Error('connect() must be called before attempting to listen to events.');
    }
    // log event listeners being bound
    _log('info', 'listen once for event =>', {method: eventName});
    this._chrome.once(eventName, cb);
  }
 
  /**
   * Unbind event listeners
   * @param {!string} eventName
   * @param {function(...)} cb
   */
  off(eventName, cb) {
    if (this._chrome === null) {
      throw new Error('connect() must be called before attempting to remove an event listener.');
    }
 
    this._chrome.removeListener(eventName, cb);
  }
 
  /**
   * Call protocol methods
   * @param {!string} command
   * @param {!Object} params
   * @return {!Promise}
   */
  sendCommand(command, params) {
    if (this._chrome === null) {
      throw new Error('connect() must be called before attempting to send a command.');
    }
 
    return new Promise((resolve, reject) => {
      _log('http', 'method => browser', {method: command, params: params});
 
      this._chrome.send(command, params, (err, result) => {
        if (err) {
          _log('error', 'method <= browser', {method: command, params: result});
          return reject(result);
        }
        _log('http', 'method <= browser OK', {method: command, params: result});
        resolve(result);
      });
    });
  }
}
 
function _log(level, prefix, data) {
  const columns = (typeof process === 'undefined') ? Infinity : process.stdout.columns;
  const maxLength = columns - data.method.length - prefix.length - 7;
  const snippet = data.params ? JSON.stringify(data.params).substr(0, maxLength) : '';
  log.log(level, prefix, data.method, snippet);
}
 
module.exports = CriDriver;