<commit_before>/**
 * 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 puppeteer = require('puppeteer-core');
const findChrome = require('./find_chrome');
const {rpc} = require('../rpc');
const {Color} = require('./color');
const {InterceptedRequest} = require('./intercepted_request');

const fs = require('fs');
const util = require('util');
const {URL} = require('url');
const EventEmitter = require('events');
const fsReadFile = util.promisify(fs.readFile);

class App extends EventEmitter {
  /**
   * @param {!Page} page Puppeteer page
   */
  constructor(page) {
    super();
    this.www_ = new Map();
    this.page_ = page;
    this.page_.on('close', () => this.emit(App.Events.Exit));
  }

  /**
   * @param {!Color} bgcolor
   */
  async init(bgcolor) {
    const bgcolorRGBA = bgcolor.canonicalRGBA();
    this.session_ = await this.page_.target().createCDPSession();
    return Promise.all([
      this.session_.send('Emulation.setDefaultBackgroundColorOverride',
          {color: {r: bgcolorRGBA[0], g: bgcolorRGBA[1],
            b: bgcolorRGBA[2], a: bgcolorRGBA[3] * 255}}),
      this.session_.send('Network.setRequestInterception', {patterns: [{urlPattern: '*'}]}),
      this.session_.on('Network.requestIntercepted', this.requestIntercepted_.bind(this))
    ]);
  }

  async exit() {
    await this.browser_.close();
  }

  /**
   * @param {string} name
   * @param {function} func
   * @return {!Promise}
   */
  exposeFunction(name, func) {
    return this.page_.exposeFunction(name, func);
  }

  /**
   * @param {function()|string} pageFunction
   * @param {!Array<*>} args
   * @return {!Promise<*>}
   */
  evaluate(pageFunction, ...args) {
    return this.page_.evaluate(pageFunction, ...args);
  }

  /**
   * @param {string} www Folder with the web content.
   * @param {string=} path Only serve folder for requests with given prefix.
   */
  serveFolder(folder, prefix) {
    this.www_.set(prefix || '', folder);
  }

  /**
   * Serves pages from given origin, eg `http://localhost:8080`.
   * This can be used for the fast development mode available in web frameworks.
   *
   * @param {string} origin
   */
  serveOrigin(origin) {
    this.wwwOrigin_ = origin;
  }

  /**
   * @param {string} uri
   * @param {*} params
   * @return {!Promise<*>}
   */
  load(uri, params) {
    if (!this.www_.size) {
      this.page_.close();
      throw new Error('Please call app.serveFolder(__dirname) or point to ' +
                      'other folder(s) with your web files');
    }
    this.page_.goto(`https://domain/${uri}`, {timeout: 0});
    return this.initializeRpc_(params);
  }

  /**
   * @param {*} params
   */
  async initializeRpc_(params) {
    const rpcFile = (await fsReadFile(__dirname + '/../rpc/rpc.js')).toString();
    let sendToParent;
    await this.page_.exposeFunction('receivedFromChild', data => sendToParent(data));

    await this.page_.evaluate(rpcFile => {<commit_msg>Update load() uri with default parameter (#58)<commit_after>/**
 * 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 puppeteer = require('puppeteer-core');
const findChrome = require('./find_chrome');
const {rpc} = require('../rpc');
const {Color} = require('./color');
const {InterceptedRequest} = require('./intercepted_request');

const fs = require('fs');
const util = require('util');
const {URL} = require('url');
const EventEmitter = require('events');
const fsReadFile = util.promisify(fs.readFile);

class App extends EventEmitter {
  /**
   * @param {!Page} page Puppeteer page
   */
  constructor(page) {
    super();
    this.www_ = new Map();
    this.page_ = page;
    this.page_.on('close', () => this.emit(App.Events.Exit));
  }

  /**
   * @param {!Color} bgcolor
   */
  async init(bgcolor) {
    const bgcolorRGBA = bgcolor.canonicalRGBA();
    this.session_ = await this.page_.target().createCDPSession();
    return Promise.all([
      this.session_.send('Emulation.setDefaultBackgroundColorOverride',
          {color: {r: bgcolorRGBA[0], g: bgcolorRGBA[1],
            b: bgcolorRGBA[2], a: bgcolorRGBA[3] * 255}}),
      this.session_.send('Network.setRequestInterception', {patterns: [{urlPattern: '*'}]}),
      this.session_.on('Network.requestIntercepted', this.requestIntercepted_.bind(this))
    ]);
  }

  async exit() {
    await this.browser_.close();
  }

  /**
   * @param {string} name
   * @param {function} func
   * @return {!Promise}
   */
  exposeFunction(name, func) {
    return this.page_.exposeFunction(name, func);
  }

  /**
   * @param {function()|string} pageFunction
   * @param {!Array<*>} args
   * @return {!Promise<*>}
   */
  evaluate(pageFunction, ...args) {
    return this.page_.evaluate(pageFunction, ...args);
  }

  /**
   * @param {string} www Folder with the web content.
   * @param {string=} path Only serve folder for requests with given prefix.
   */
  serveFolder(folder, prefix) {
    this.www_.set(prefix || '', folder);
  }

  /**
   * Serves pages from given origin, eg `http://localhost:8080`.
   * This can be used for the fast development mode available in web frameworks.
   *
   * @param {string} origin
   */
  serveOrigin(origin) {
    this.wwwOrigin_ = origin;
  }

  /**
   * @param {string} uri
   * @param {*} params
   * @return {!Promise<*>}
   */
  load(uri, params) {
    if (!this.www_.size) {
      this.page_.close();
      throw new Error('Please call app.serveFolder(__dirname) or point to ' +
                      'other folder(s) with your web files');
    }
    this.page_.goto(`https://domain/${uri||''}`, {timeout: 0});
    return this.initializeRpc_(params);
  }

  /**
   * @param {*} params
   */
  async initializeRpc_(params) {
    const rpcFile = (await fsReadFile(__dirname + '/../rpc/rpc.js')).toString();
    let sendToParent;
    await this.page_.exposeFunction('receivedFromChild', data => sendToParent(data));

    await this.page_.evaluate(rpcFile => {
{'fraction_non_alphanumeric': 0.15270097830710336, 'fraction_numerical': 0.005954912803062527, 'mean_word_length': 3.2933657942787584, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 15, 'https://': 2, 'lorem ipsum': 0, 'www.': 12, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3161127', 'n_tokens_mistral': 2206, 'n_tokens_neox': 2150, 'n_words': 590}