mirror of
https://github.com/puppeteer/puppeteer
synced 2024-06-14 14:02:48 +00:00
Convert var's to let's
This patch: - converts all var's to let's throughout the codebase - enforces the let's over var's via the eslint rule
This commit is contained in:
parent
78e879925f
commit
819fa355f4
@ -49,6 +49,7 @@ module.exports = {
|
||||
"arrow-parens": [2, "as-needed"],
|
||||
|
||||
// anti-patterns
|
||||
"no-var": 2,
|
||||
"no-with": 2,
|
||||
"no-multi-str": 2,
|
||||
"no-caller": 2,
|
||||
@ -99,13 +100,11 @@ module.exports = {
|
||||
"no-mixed-spaces-and-tabs": 2,
|
||||
"no-trailing-spaces": 2,
|
||||
"linebreak-style": [ 2, "unix" ],
|
||||
"indent": [2, 2, { "SwitchCase": 1, "CallExpression": {"arguments": 2}, "MemberExpression": 2 }],
|
||||
|
||||
/**
|
||||
* Disabled, aspirational rules
|
||||
*/
|
||||
|
||||
"indent": [2, 2, { "SwitchCase": 1, "CallExpression": {"arguments": 2}, "MemberExpression": 2 }],
|
||||
|
||||
// brace-style is disabled, as eslint cannot enforce 1tbs as default, but allman for functions
|
||||
"brace-style": [0, "allman", { "allowSingleLine": true }],
|
||||
|
||||
|
10
install.js
10
install.js
@ -14,9 +14,9 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
var Downloader = require('./utils/ChromiumDownloader');
|
||||
var revision = require('./package').puppeteer.chromium_revision;
|
||||
var ProgressBar = require('progress');
|
||||
let Downloader = require('./utils/ChromiumDownloader');
|
||||
let revision = require('./package').puppeteer.chromium_revision;
|
||||
let ProgressBar = require('progress');
|
||||
|
||||
// Do nothing if the revision is already downloaded.
|
||||
if (Downloader.revisionInfo(Downloader.currentPlatform(), revision))
|
||||
@ -27,7 +27,7 @@ Downloader.downloadRevision(Downloader.currentPlatform(), revision, onProgress)
|
||||
console.error('Download failed: ' + error.message);
|
||||
});
|
||||
|
||||
var progressBar = null;
|
||||
let progressBar = null;
|
||||
function onProgress(bytesTotal, delta) {
|
||||
if (!progressBar) {
|
||||
progressBar = new ProgressBar(`Downloading Chromium - ${toMegabytes(bytesTotal)} [:bar] :percent :etas `, {
|
||||
@ -41,7 +41,7 @@ function onProgress(bytesTotal, delta) {
|
||||
}
|
||||
|
||||
function toMegabytes(bytes) {
|
||||
var mb = bytes / 1024 / 1024;
|
||||
let mb = bytes / 1024 / 1024;
|
||||
return (Math.round(mb * 10) / 10) + ' Mb';
|
||||
}
|
||||
|
||||
|
@ -14,18 +14,18 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
var http = require('http');
|
||||
var path = require('path');
|
||||
var removeRecursive = require('rimraf').sync;
|
||||
var Page = require('./Page');
|
||||
var childProcess = require('child_process');
|
||||
var Downloader = require('../utils/ChromiumDownloader');
|
||||
var Connection = require('./Connection');
|
||||
let http = require('http');
|
||||
let path = require('path');
|
||||
let removeRecursive = require('rimraf').sync;
|
||||
let Page = require('./Page');
|
||||
let childProcess = require('child_process');
|
||||
let Downloader = require('../utils/ChromiumDownloader');
|
||||
let Connection = require('./Connection');
|
||||
|
||||
var CHROME_PROFILE_PATH = path.resolve(__dirname, '..', '.dev_profile');
|
||||
var browserId = 0;
|
||||
let CHROME_PROFILE_PATH = path.resolve(__dirname, '..', '.dev_profile');
|
||||
let browserId = 0;
|
||||
|
||||
var DEFAULT_ARGS = [
|
||||
let DEFAULT_ARGS = [
|
||||
'--disable-background-timer-throttling',
|
||||
'--no-first-run',
|
||||
];
|
||||
@ -54,8 +54,8 @@ class Browser {
|
||||
if (typeof options.executablePath === 'string') {
|
||||
this._chromeExecutable = options.executablePath;
|
||||
} else {
|
||||
var chromiumRevision = require('../package.json').puppeteer.chromium_revision;
|
||||
var revisionInfo = Downloader.revisionInfo(Downloader.currentPlatform(), chromiumRevision);
|
||||
let chromiumRevision = require('../package.json').puppeteer.chromium_revision;
|
||||
let revisionInfo = Downloader.revisionInfo(Downloader.currentPlatform(), chromiumRevision);
|
||||
console.assert(revisionInfo, 'Chromium revision is not downloaded. Run npm install');
|
||||
this._chromeExecutable = revisionInfo.executablePath;
|
||||
}
|
||||
@ -72,8 +72,8 @@ class Browser {
|
||||
await this._ensureChromeIsRunning();
|
||||
if (!this._chromeProcess || this._terminated)
|
||||
throw new Error('ERROR: this chrome instance is not alive any more!');
|
||||
var client = await Connection.create(this._remoteDebuggingPort);
|
||||
var page = await Page.create(client);
|
||||
let client = await Connection.create(this._remoteDebuggingPort);
|
||||
let page = await Page.create(client);
|
||||
return page;
|
||||
}
|
||||
|
||||
@ -91,7 +91,7 @@ class Browser {
|
||||
*/
|
||||
async version() {
|
||||
await this._ensureChromeIsRunning();
|
||||
var version = await Connection.version(this._remoteDebuggingPort);
|
||||
let version = await Connection.version(this._remoteDebuggingPort);
|
||||
return version.Browser;
|
||||
}
|
||||
|
||||
@ -99,7 +99,7 @@ class Browser {
|
||||
if (this._chromeProcess)
|
||||
return;
|
||||
this._chromeProcess = childProcess.spawn(this._chromeExecutable, this._chromeArguments, {});
|
||||
var stderr = '';
|
||||
let stderr = '';
|
||||
this._chromeProcess.stderr.on('data', data => stderr += data.toString('utf8'));
|
||||
// Cleanup as processes exit.
|
||||
process.on('exit', () => this._chromeProcess.kill());
|
||||
@ -123,20 +123,20 @@ class Browser {
|
||||
module.exports = Browser;
|
||||
|
||||
function waitForChromeResponsive(remoteDebuggingPort, shouldWaitCallback) {
|
||||
var fulfill;
|
||||
var promise = new Promise(x => fulfill = x);
|
||||
var options = {
|
||||
let fulfill;
|
||||
let promise = new Promise(x => fulfill = x);
|
||||
let options = {
|
||||
method: 'GET',
|
||||
host: 'localhost',
|
||||
port: remoteDebuggingPort,
|
||||
path: '/json/list'
|
||||
};
|
||||
var probeTimeout = 100;
|
||||
let probeTimeout = 100;
|
||||
sendRequest();
|
||||
return promise;
|
||||
|
||||
function sendRequest() {
|
||||
var req = http.request(options, res => {
|
||||
let req = http.request(options, res => {
|
||||
fulfill();
|
||||
});
|
||||
req.on('error', e => {
|
||||
|
@ -14,9 +14,9 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
var EventEmitter = require('events');
|
||||
var WebSocket = require('ws');
|
||||
var http = require('http');
|
||||
let EventEmitter = require('events');
|
||||
let WebSocket = require('ws');
|
||||
let http = require('http');
|
||||
const COMMAND_TIMEOUT = 10000;
|
||||
|
||||
class Connection extends EventEmitter {
|
||||
@ -44,8 +44,8 @@ class Connection extends EventEmitter {
|
||||
* @return {!Promise<?Object>}
|
||||
*/
|
||||
send(method, params = {}) {
|
||||
var id = ++this._lastId;
|
||||
var message = JSON.stringify({id, method, params});
|
||||
let id = ++this._lastId;
|
||||
let message = JSON.stringify({id, method, params});
|
||||
this._ws.send(message);
|
||||
return new Promise((resolve, reject) => {
|
||||
this._callbacks.set(id, {resolve, reject, method});
|
||||
@ -56,9 +56,9 @@ class Connection extends EventEmitter {
|
||||
* @param {string} message
|
||||
*/
|
||||
_onMessage(message) {
|
||||
var object = JSON.parse(message);
|
||||
let object = JSON.parse(message);
|
||||
if (object.id && this._callbacks.has(object.id)) {
|
||||
var callback = this._callbacks.get(object.id);
|
||||
let callback = this._callbacks.get(object.id);
|
||||
this._callbacks.delete(object.id);
|
||||
if (object.error)
|
||||
callback.reject(new Error(`Protocol error (${callback.method}): ${object.error.message}`));
|
||||
@ -87,11 +87,11 @@ class Connection extends EventEmitter {
|
||||
* @return {!Promise<!Connection>}
|
||||
*/
|
||||
static async create(port) {
|
||||
var newTab = await runJsonCommand(port, 'new');
|
||||
var url = newTab.webSocketDebuggerUrl;
|
||||
let newTab = await runJsonCommand(port, 'new');
|
||||
let url = newTab.webSocketDebuggerUrl;
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
var ws = new WebSocket(url, { perMessageDeflate: false });
|
||||
let ws = new WebSocket(url, { perMessageDeflate: false });
|
||||
ws.on('open', () => resolve(new Connection(port, newTab.id, ws)));
|
||||
ws.on('error', reject);
|
||||
});
|
||||
@ -112,17 +112,17 @@ class Connection extends EventEmitter {
|
||||
* @return {!Promise<!Object>}
|
||||
*/
|
||||
function runJsonCommand(port, command) {
|
||||
var request = http.get({
|
||||
let request = http.get({
|
||||
hostname: 'localhost',
|
||||
port: port,
|
||||
path: '/json/' + command
|
||||
}, onResponse);
|
||||
request.setTimeout(COMMAND_TIMEOUT, onTimeout);
|
||||
var resolve, reject;
|
||||
let resolve, reject;
|
||||
return new Promise((res, rej) => { resolve = res; reject = rej; });
|
||||
|
||||
function onResponse(response) {
|
||||
var data = '';
|
||||
let data = '';
|
||||
response.on('data', chunk => data += chunk);
|
||||
response.on('end', () => {
|
||||
if (response.statusCode !== 200) {
|
||||
|
@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
var EventEmitter = require('events');
|
||||
let EventEmitter = require('events');
|
||||
|
||||
class FrameManager extends EventEmitter {
|
||||
/**
|
||||
@ -22,7 +22,7 @@ class FrameManager extends EventEmitter {
|
||||
* @return {!FrameManager}
|
||||
*/
|
||||
static async create(client) {
|
||||
var mainFramePayload = await client.send('Page.getResourceTree');
|
||||
let mainFramePayload = await client.send('Page.getResourceTree');
|
||||
return new FrameManager(client, mainFramePayload.frameTree);
|
||||
}
|
||||
|
||||
@ -70,8 +70,8 @@ class FrameManager extends EventEmitter {
|
||||
this._navigateFrame(this._mainFrame, frameId, null);
|
||||
return;
|
||||
}
|
||||
var parentFrame = this._frames.get(parentFrameId);
|
||||
var frame = new Frame(parentFrame, frameId, null);
|
||||
let parentFrame = this._frames.get(parentFrameId);
|
||||
let frame = new Frame(parentFrame, frameId, null);
|
||||
this._frames.set(frame._id, frame);
|
||||
this.emit(FrameManager.Events.FrameAttached, frame);
|
||||
}
|
||||
@ -80,7 +80,7 @@ class FrameManager extends EventEmitter {
|
||||
* @param {!Object} framePayload
|
||||
*/
|
||||
_frameNavigated(framePayload) {
|
||||
var frame = this._frames.get(framePayload.id);
|
||||
let frame = this._frames.get(framePayload.id);
|
||||
if (!frame) {
|
||||
// Simulate missed "frameAttached" for a main frame navigation to the new backend process.
|
||||
console.assert(!framePayload.parentId, 'Main frame shouldn\'t have parent frame id.');
|
||||
@ -93,7 +93,7 @@ class FrameManager extends EventEmitter {
|
||||
* @param {string} frameId
|
||||
*/
|
||||
_frameDetached(frameId) {
|
||||
var frame = this._frames.get(frameId);
|
||||
let frame = this._frames.get(frameId);
|
||||
if (frame)
|
||||
this._removeFramesRecursively(frame);
|
||||
}
|
||||
@ -105,7 +105,7 @@ class FrameManager extends EventEmitter {
|
||||
*/
|
||||
_navigateFrame(frame, newFrameId, newFramePayload) {
|
||||
// Detach all child frames first.
|
||||
for (var child of frame.childFrames())
|
||||
for (let child of frame.childFrames())
|
||||
this._removeFramesRecursively(child);
|
||||
this._frames.delete(frame._id, frame);
|
||||
frame._id = newFrameId;
|
||||
@ -120,11 +120,11 @@ class FrameManager extends EventEmitter {
|
||||
* @return {!Frame}
|
||||
*/
|
||||
_addFramesRecursively(parentFrame, frameTreePayload) {
|
||||
var framePayload = frameTreePayload.frame;
|
||||
var frame = new Frame(parentFrame, framePayload.id, framePayload);
|
||||
let framePayload = frameTreePayload.frame;
|
||||
let frame = new Frame(parentFrame, framePayload.id, framePayload);
|
||||
this._frames.set(frame._id, frame);
|
||||
|
||||
for (var i = 0; frameTreePayload.childFrames && i < frameTreePayload.childFrames.length; ++i)
|
||||
for (let i = 0; frameTreePayload.childFrames && i < frameTreePayload.childFrames.length; ++i)
|
||||
this._addFramesRecursively(frame, frameTreePayload.childFrames[i]);
|
||||
return frame;
|
||||
}
|
||||
@ -133,7 +133,7 @@ class FrameManager extends EventEmitter {
|
||||
* @param {!Frame} frame
|
||||
*/
|
||||
_removeFramesRecursively(frame) {
|
||||
for (var child of frame.childFrames())
|
||||
for (let child of frame.childFrames())
|
||||
this._removeFramesRecursively(child);
|
||||
frame._detach();
|
||||
this._frames.delete(frame._id);
|
||||
|
@ -39,7 +39,7 @@ class Navigator {
|
||||
this._minimumTimer = setTimeout(this._completeNavigation.bind(this, false), this._minTime);
|
||||
let onload = new Promise(fulfill => this._client.once('Page.loadEventFired', fulfill));
|
||||
let networkIdle = new Promise(fulfill => this._navigationLoadCallback = fulfill);
|
||||
var interstitialPromise = new Promise(fulfill => this._client.once('Security.certificateError', fulfill)).then(() => false);
|
||||
let interstitialPromise = new Promise(fulfill => this._client.once('Security.certificateError', fulfill)).then(() => false);
|
||||
|
||||
this._inflightRequests = 0;
|
||||
// Await for the command to throw exception in case of illegal arguments.
|
||||
|
132
lib/Page.js
132
lib/Page.js
@ -14,13 +14,13 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
var fs = require('fs');
|
||||
var EventEmitter = require('events');
|
||||
var mime = require('mime');
|
||||
var Request = require('./Request');
|
||||
var Navigator = require('./Navigator');
|
||||
var Dialog = require('./Dialog');
|
||||
var FrameManager = require('./FrameManager');
|
||||
let fs = require('fs');
|
||||
let EventEmitter = require('events');
|
||||
let mime = require('mime');
|
||||
let Request = require('./Request');
|
||||
let Navigator = require('./Navigator');
|
||||
let Dialog = require('./Dialog');
|
||||
let FrameManager = require('./FrameManager');
|
||||
|
||||
class Page extends EventEmitter {
|
||||
/**
|
||||
@ -34,10 +34,10 @@ class Page extends EventEmitter {
|
||||
client.send('Runtime.enable', {}),
|
||||
client.send('Security.enable', {}),
|
||||
]);
|
||||
var expression = Page._evaluationString(() => window.devicePixelRatio);
|
||||
var {result:{value: screenDPI}} = await client.send('Runtime.evaluate', { expression, returnByValue: true });
|
||||
var frameManager = await FrameManager.create(client);
|
||||
var page = new Page(client, frameManager, screenDPI);
|
||||
let expression = Page._evaluationString(() => window.devicePixelRatio);
|
||||
let {result:{value: screenDPI}} = await client.send('Runtime.evaluate', { expression, returnByValue: true });
|
||||
let frameManager = await FrameManager.create(client);
|
||||
let page = new Page(client, frameManager, screenDPI);
|
||||
// Initialize default page size.
|
||||
await page.setViewportSize({width: 400, height: 300});
|
||||
return page;
|
||||
@ -100,7 +100,7 @@ class Page extends EventEmitter {
|
||||
* @param {!Object} event
|
||||
*/
|
||||
_onRequestIntercepted(event) {
|
||||
var request = new Request(this._client, event.InterceptionId, event.request);
|
||||
let request = new Request(this._client, event.InterceptionId, event.request);
|
||||
this._requestInterceptor(request);
|
||||
}
|
||||
|
||||
@ -115,9 +115,9 @@ class Page extends EventEmitter {
|
||||
* @param {string} url
|
||||
*/
|
||||
function addScriptTag(url) {
|
||||
var script = document.createElement('script');
|
||||
let script = document.createElement('script');
|
||||
script.src = url;
|
||||
var promise = new Promise(x => script.onload = x);
|
||||
let promise = new Promise(x => script.onload = x);
|
||||
document.head.appendChild(script);
|
||||
return promise;
|
||||
}
|
||||
@ -128,9 +128,9 @@ class Page extends EventEmitter {
|
||||
* @return {!Promise}
|
||||
*/
|
||||
async injectFile(filePath) {
|
||||
var callback;
|
||||
var promise = new Promise(fulfill => callback = fulfill);
|
||||
var expression = fs.readFile(filePath, 'utf8', (err, data) => callback({err, data}));
|
||||
let callback;
|
||||
let promise = new Promise(fulfill => callback = fulfill);
|
||||
let expression = fs.readFile(filePath, 'utf8', (err, data) => callback({err, data}));
|
||||
await promise;
|
||||
return this._client.send('Runtime.evaluate', { expression, returnByValue: true });
|
||||
}
|
||||
@ -144,7 +144,7 @@ class Page extends EventEmitter {
|
||||
throw new Error(`Failed to set in-page callback with name ${name}: window['${name}'] already exists!`);
|
||||
this._inPageCallbacks[name] = callback;
|
||||
|
||||
var expression = Page._evaluationString(inPageCallback, name);
|
||||
let expression = Page._evaluationString(inPageCallback, name);
|
||||
await this._client.send('Page.addScriptToEvaluateOnLoad', { scriptSource: expression });
|
||||
await this._client.send('Runtime.evaluate', { expression, returnByValue: true });
|
||||
|
||||
@ -173,7 +173,7 @@ class Page extends EventEmitter {
|
||||
async setExtraHTTPHeaders(headers) {
|
||||
this._extraHeaders = {};
|
||||
// Note: header names are case-insensitive.
|
||||
for (var key of Object.keys(headers))
|
||||
for (let key of Object.keys(headers))
|
||||
this._extraHeaders[key.toLowerCase()] = headers[key];
|
||||
return this._client.send('Network.setExtraHTTPHeaders', { headers });
|
||||
}
|
||||
@ -205,15 +205,15 @@ class Page extends EventEmitter {
|
||||
* @param {!Object} exceptionDetails
|
||||
*/
|
||||
async _handleException(exceptionDetails) {
|
||||
var message = await this._getExceptionMessage(exceptionDetails);
|
||||
let message = await this._getExceptionMessage(exceptionDetails);
|
||||
this.emit(Page.Events.Error, new Error(message));
|
||||
}
|
||||
|
||||
async _onConsoleAPI(event) {
|
||||
if (event.type === 'debug' && event.args.length && event.args[0].value === 'driver:InPageCallback') {
|
||||
var {name, seq, args} = JSON.parse(event.args[1].value);
|
||||
var result = await this._inPageCallbacks[name](...args);
|
||||
var expression = Page._evaluationString(deliverResult, name, seq, result);
|
||||
let {name, seq, args} = JSON.parse(event.args[1].value);
|
||||
let result = await this._inPageCallbacks[name](...args);
|
||||
let expression = Page._evaluationString(deliverResult, name, seq, result);
|
||||
this._client.send('Runtime.evaluate', { expression });
|
||||
|
||||
function deliverResult(name, seq, result) {
|
||||
@ -222,12 +222,12 @@ class Page extends EventEmitter {
|
||||
}
|
||||
return;
|
||||
}
|
||||
var values = event.args.map(arg => arg.value || arg.description || '');
|
||||
let values = event.args.map(arg => arg.value || arg.description || '');
|
||||
this.emit(Page.Events.ConsoleMessage, values.join(' '));
|
||||
}
|
||||
|
||||
_onDialog(event) {
|
||||
var dialogType = null;
|
||||
let dialogType = null;
|
||||
if (event.type === 'alert')
|
||||
dialogType = Dialog.Type.Alert;
|
||||
else if (event.type === 'confirm')
|
||||
@ -237,7 +237,7 @@ class Page extends EventEmitter {
|
||||
else if (event.type === 'beforeunload')
|
||||
dialogType = Dialog.Type.BeforeUnload;
|
||||
console.assert(dialogType, 'Unknown javascript dialog type: ' + event.type);
|
||||
var dialog = new Dialog(this._client, dialogType, event.message);
|
||||
let dialog = new Dialog(this._client, dialogType, event.message);
|
||||
this.emit(Page.Events.Dialog, dialog);
|
||||
}
|
||||
|
||||
@ -275,9 +275,9 @@ class Page extends EventEmitter {
|
||||
*/
|
||||
async setViewportSize(size) {
|
||||
this._viewportSize = size;
|
||||
var width = size.width;
|
||||
var height = size.height;
|
||||
var zoom = this._screenDPI;
|
||||
let width = size.width;
|
||||
let height = size.height;
|
||||
let zoom = this._screenDPI;
|
||||
return Promise.all([
|
||||
this._client.send('Emulation.setDeviceMetricsOverride', {
|
||||
width,
|
||||
@ -307,11 +307,11 @@ class Page extends EventEmitter {
|
||||
* @return {!Promise<(!Object|undefined)>}
|
||||
*/
|
||||
async evaluate(fun, ...args) {
|
||||
var syncExpression = Page._evaluationString(fun, ...args);
|
||||
var expression = `Promise.resolve(${syncExpression})`;
|
||||
var { exceptionDetails, result: remoteObject } = await this._client.send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true });
|
||||
let syncExpression = Page._evaluationString(fun, ...args);
|
||||
let expression = `Promise.resolve(${syncExpression})`;
|
||||
let { exceptionDetails, result: remoteObject } = await this._client.send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true });
|
||||
if (exceptionDetails) {
|
||||
var message = await this._getExceptionMessage(exceptionDetails);
|
||||
let message = await this._getExceptionMessage(exceptionDetails);
|
||||
throw new Error('Evaluation failed: ' + message);
|
||||
}
|
||||
return remoteObject.value;
|
||||
@ -322,10 +322,10 @@ class Page extends EventEmitter {
|
||||
* @return {string}
|
||||
*/
|
||||
async _getExceptionMessage(exceptionDetails) {
|
||||
var message = '';
|
||||
var exception = exceptionDetails.exception;
|
||||
let message = '';
|
||||
let exception = exceptionDetails.exception;
|
||||
if (exception) {
|
||||
var response = await this._client.send('Runtime.callFunctionOn', {
|
||||
let response = await this._client.send('Runtime.callFunctionOn', {
|
||||
objectId: exception.objectId,
|
||||
functionDeclaration: 'function() { return this.message; }',
|
||||
returnByValue: true,
|
||||
@ -336,9 +336,9 @@ class Page extends EventEmitter {
|
||||
}
|
||||
|
||||
if (exceptionDetails.stackTrace) {
|
||||
for (var callframe of exceptionDetails.stackTrace.callFrames) {
|
||||
var location = callframe.url + ':' + callframe.lineNumber + ':' + callframe.columnNumber;
|
||||
var functionName = callframe.functionName || '<anonymous>';
|
||||
for (let callframe of exceptionDetails.stackTrace.callFrames) {
|
||||
let location = callframe.url + ':' + callframe.lineNumber + ':' + callframe.columnNumber;
|
||||
let functionName = callframe.functionName || '<anonymous>';
|
||||
message += `\n at ${functionName} (${location})`;
|
||||
}
|
||||
}
|
||||
@ -351,7 +351,7 @@ class Page extends EventEmitter {
|
||||
* @return {!Promise}
|
||||
*/
|
||||
async evaluateOnInitialized(fun, ...args) {
|
||||
var scriptSource = Page._evaluationString(fun, ...args);
|
||||
let scriptSource = Page._evaluationString(fun, ...args);
|
||||
await this._client.send('Page.addScriptToEvaluateOnLoad', { scriptSource });
|
||||
}
|
||||
|
||||
@ -370,9 +370,9 @@ class Page extends EventEmitter {
|
||||
*/
|
||||
async screenshot(options) {
|
||||
options = options || {};
|
||||
var screenshotType = null;
|
||||
let screenshotType = null;
|
||||
if (options.path) {
|
||||
var mimeType = mime.lookup(options.path);
|
||||
let mimeType = mime.lookup(options.path);
|
||||
if (mimeType === 'image/png')
|
||||
screenshotType = 'png';
|
||||
else if (mimeType === 'image/jpeg')
|
||||
@ -423,7 +423,7 @@ class Page extends EventEmitter {
|
||||
})
|
||||
]);
|
||||
} else if (options.fullPage) {
|
||||
var response = await this._client.send('Page.getLayoutMetrics');
|
||||
let response = await this._client.send('Page.getLayoutMetrics');
|
||||
await Promise.all([
|
||||
this._client.send('Emulation.setVisibleSize', {
|
||||
width: Math.ceil(response.contentSize.width / this._screenDPI),
|
||||
@ -436,7 +436,7 @@ class Page extends EventEmitter {
|
||||
})
|
||||
]);
|
||||
}
|
||||
var result = await this._client.send('Page.captureScreenshot', {
|
||||
let result = await this._client.send('Page.captureScreenshot', {
|
||||
fromSurface: true,
|
||||
format: screenshotType,
|
||||
quality: options.quality
|
||||
@ -447,7 +447,7 @@ class Page extends EventEmitter {
|
||||
this._client.send('Emulation.resetViewport')
|
||||
]);
|
||||
}
|
||||
var buffer = new Buffer(result.data, 'base64');
|
||||
let buffer = new Buffer(result.data, 'base64');
|
||||
if (options.path)
|
||||
fs.writeFileSync(options.path, buffer);
|
||||
return buffer;
|
||||
@ -461,16 +461,16 @@ class Page extends EventEmitter {
|
||||
async printToPDF(filePath, options) {
|
||||
options = options || {};
|
||||
|
||||
var scale = options.scale || 1;
|
||||
var displayHeaderFooter = options.displayHeaderFooter || false;
|
||||
var printBackground = options.printBackground || true;
|
||||
var landscape = options.landscape || false;
|
||||
var pageRanges = options.pageRanges || '';
|
||||
let scale = options.scale || 1;
|
||||
let displayHeaderFooter = options.displayHeaderFooter || false;
|
||||
let printBackground = options.printBackground || true;
|
||||
let landscape = options.landscape || false;
|
||||
let pageRanges = options.pageRanges || '';
|
||||
|
||||
var paperWidth = 8.5;
|
||||
var paperHeight = 11;
|
||||
let paperWidth = 8.5;
|
||||
let paperHeight = 11;
|
||||
if (options.format) {
|
||||
var format = Page.PaperFormats[options.format];
|
||||
let format = Page.PaperFormats[options.format];
|
||||
console.assert(format, 'Unknown paper format: ' + options.format);
|
||||
paperWidth = format.width;
|
||||
paperHeight = format.height;
|
||||
@ -479,13 +479,13 @@ class Page extends EventEmitter {
|
||||
paperHeight = convertPrintParameterToInches(options.height) || paperHeight;
|
||||
}
|
||||
|
||||
var marginOptions = options.margin || {};
|
||||
var marginTop = convertPrintParameterToInches(marginOptions.top) || 0;
|
||||
var marginLeft = convertPrintParameterToInches(marginOptions.left) || 0;
|
||||
var marginBottom = convertPrintParameterToInches(marginOptions.bottom) || 0;
|
||||
var marginRight = convertPrintParameterToInches(marginOptions.right) || 0;
|
||||
let marginOptions = options.margin || {};
|
||||
let marginTop = convertPrintParameterToInches(marginOptions.top) || 0;
|
||||
let marginLeft = convertPrintParameterToInches(marginOptions.left) || 0;
|
||||
let marginBottom = convertPrintParameterToInches(marginOptions.bottom) || 0;
|
||||
let marginRight = convertPrintParameterToInches(marginOptions.right) || 0;
|
||||
|
||||
var result = await this._client.send('Page.printToPDF', {
|
||||
let result = await this._client.send('Page.printToPDF', {
|
||||
landscape: landscape,
|
||||
displayHeaderFooter: displayHeaderFooter,
|
||||
printBackground: printBackground,
|
||||
@ -498,7 +498,7 @@ class Page extends EventEmitter {
|
||||
marginRight: marginRight,
|
||||
pageRanges: pageRanges
|
||||
});
|
||||
var buffer = new Buffer(result.data, 'base64');
|
||||
let buffer = new Buffer(result.data, 'base64');
|
||||
fs.writeFileSync(filePath, buffer);
|
||||
}
|
||||
|
||||
@ -538,7 +538,7 @@ Page.PaperFormats = {
|
||||
A5: {width: 5.83, height: 8.27 },
|
||||
};
|
||||
|
||||
var unitToPixels = {
|
||||
let unitToPixels = {
|
||||
'px': 1,
|
||||
'in': 96,
|
||||
'cm': 37.8,
|
||||
@ -552,14 +552,14 @@ var unitToPixels = {
|
||||
function convertPrintParameterToInches(parameter) {
|
||||
if (typeof parameter === 'undefined')
|
||||
return undefined;
|
||||
var pixels;
|
||||
let pixels;
|
||||
if (typeof parameter === 'number') {
|
||||
// Treat numbers as pixel values to be aligned with phantom's paperSize.
|
||||
pixels = /** @type {number} */ (parameter);
|
||||
} else if (typeof parameter === 'string') {
|
||||
var text = parameter;
|
||||
var unit = text.substring(text.length - 2).toLowerCase();
|
||||
var valueText = '';
|
||||
let text = parameter;
|
||||
let unit = text.substring(text.length - 2).toLowerCase();
|
||||
let valueText = '';
|
||||
if (unitToPixels.hasOwnProperty(unit)) {
|
||||
valueText = text.substring(0, text.length - 2);
|
||||
} else {
|
||||
@ -568,7 +568,7 @@ function convertPrintParameterToInches(parameter) {
|
||||
unit = 'px';
|
||||
valueText = text;
|
||||
}
|
||||
var value = Number(valueText);
|
||||
let value = Number(valueText);
|
||||
console.assert(!isNaN(value), 'Failed to parse parameter value: ' + text);
|
||||
pixels = value * unitToPixels[unit];
|
||||
} else {
|
||||
|
@ -14,11 +14,11 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
var path = require('path');
|
||||
var fs = require('fs');
|
||||
var deasync = require('deasync');
|
||||
var removeRecursive = require('rimraf').sync;
|
||||
var copyRecursive = deasync(require('ncp').ncp);
|
||||
let path = require('path');
|
||||
let fs = require('fs');
|
||||
let deasync = require('deasync');
|
||||
let removeRecursive = require('rimraf').sync;
|
||||
let copyRecursive = deasync(require('ncp').ncp);
|
||||
|
||||
class FileSystem {
|
||||
constructor() {
|
||||
@ -68,7 +68,7 @@ class FileSystem {
|
||||
* @param {string} toPath
|
||||
*/
|
||||
copy(fromPath, toPath) {
|
||||
var content = fs.readFileSync(fromPath);
|
||||
let content = fs.readFileSync(fromPath);
|
||||
fs.writeFileSync(toPath, content);
|
||||
}
|
||||
|
||||
@ -77,7 +77,7 @@ class FileSystem {
|
||||
* @param {string} toPath
|
||||
*/
|
||||
move(fromPath, toPath) {
|
||||
var content = fs.readFileSync(fromPath);
|
||||
let content = fs.readFileSync(fromPath);
|
||||
fs.writeFileSync(toPath, content);
|
||||
fs.unlinkSync(fromPath);
|
||||
}
|
||||
@ -170,7 +170,7 @@ class FileSystem {
|
||||
* @param {string} mode
|
||||
*/
|
||||
write(filePath, data, mode) {
|
||||
var fd = new FileDescriptor(filePath, mode, 'utf8');
|
||||
let fd = new FileDescriptor(filePath, mode, 'utf8');
|
||||
fd.write(data);
|
||||
fd.close();
|
||||
}
|
||||
@ -288,8 +288,8 @@ class FileSystem {
|
||||
}
|
||||
}
|
||||
|
||||
var fdwrite = deasync(fs.write);
|
||||
var fdread = deasync(fs.read);
|
||||
let fdwrite = deasync(fs.write);
|
||||
let fdread = deasync(fs.read);
|
||||
|
||||
class FileDescriptor {
|
||||
/**
|
||||
@ -318,8 +318,8 @@ class FileDescriptor {
|
||||
* @param {string} data
|
||||
*/
|
||||
write(data) {
|
||||
var buffer = Buffer.from(data, this._encoding);
|
||||
var written = fdwrite(this._fd, buffer, 0, buffer.length, this._position);
|
||||
let buffer = Buffer.from(data, this._encoding);
|
||||
let written = fdwrite(this._fd, buffer, 0, buffer.length, this._position);
|
||||
this._position += written;
|
||||
}
|
||||
|
||||
@ -339,13 +339,13 @@ class FileDescriptor {
|
||||
* @return {string}
|
||||
*/
|
||||
read(size) {
|
||||
var position = this._position;
|
||||
let position = this._position;
|
||||
if (!size) {
|
||||
size = fs.fstatSync(this._fd).size;
|
||||
position = 0;
|
||||
}
|
||||
var buffer = new Buffer(size);
|
||||
var bytesRead = fdread(this._fd, buffer, 0, size, position);
|
||||
let buffer = new Buffer(size);
|
||||
let bytesRead = fdread(this._fd, buffer, 0, size, position);
|
||||
this._position += bytesRead;
|
||||
return buffer.toString(this._encoding);
|
||||
}
|
||||
|
@ -14,17 +14,17 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
var fs = require('fs');
|
||||
var path = require('path');
|
||||
var vm = require('vm');
|
||||
var url = require('url');
|
||||
let fs = require('fs');
|
||||
let path = require('path');
|
||||
let vm = require('vm');
|
||||
let url = require('url');
|
||||
|
||||
/**
|
||||
* @param {!Object} context
|
||||
* @param {string} scriptPath
|
||||
*/
|
||||
module.exports.create = function(context, scriptPath) {
|
||||
var phantom = {
|
||||
const phantom = {
|
||||
page: {
|
||||
onConsoleMessage: null,
|
||||
},
|
||||
@ -82,7 +82,7 @@ module.exports.create = function(context, scriptPath) {
|
||||
* @return {!{major: number, minor: number, patch: number}}
|
||||
*/
|
||||
get version() {
|
||||
var versionParts = require('../package.json').version.split('.');
|
||||
let versionParts = require('../package.json').version.split('.');
|
||||
return {
|
||||
major: parseInt(versionParts[0], 10),
|
||||
minor: parseInt(versionParts[1], 10),
|
||||
@ -105,7 +105,7 @@ module.exports.create = function(context, scriptPath) {
|
||||
filePath = path.resolve(phantom.libraryPath, filePath);
|
||||
if (!fs.existsSync(filePath))
|
||||
return false;
|
||||
var code = fs.readFileSync(filePath, 'utf8');
|
||||
let code = fs.readFileSync(filePath, 'utf8');
|
||||
if (code.startsWith('#!'))
|
||||
code = code.substring(code.indexOf('\n'));
|
||||
vm.runInContext(code, context, {
|
||||
@ -120,7 +120,7 @@ module.exports.create = function(context, scriptPath) {
|
||||
* @param {string} filename
|
||||
*/
|
||||
loadModule: function(moduleSource, filename) {
|
||||
var code = [
|
||||
let code = [
|
||||
'(function(require, exports, module) {\n',
|
||||
moduleSource,
|
||||
'\n}.call({},',
|
||||
|
@ -14,9 +14,9 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
var readline = require('readline');
|
||||
var await = require('./utilities').await;
|
||||
var os = require('os');
|
||||
let readline = require('readline');
|
||||
let await = require('./utilities').await;
|
||||
let os = require('os');
|
||||
|
||||
class System {
|
||||
/**
|
||||
@ -61,7 +61,7 @@ class StandardInput {
|
||||
if (this._closed && !this._lines.length)
|
||||
return '';
|
||||
if (!this._lines.length) {
|
||||
var linePromise = new Promise(fulfill => this._readline.once('line', fulfill));
|
||||
let linePromise = new Promise(fulfill => this._readline.once('line', fulfill));
|
||||
await(linePromise);
|
||||
}
|
||||
return this._lines.shift();
|
||||
@ -72,10 +72,10 @@ class StandardInput {
|
||||
*/
|
||||
read() {
|
||||
if (!this._closed) {
|
||||
var closePromise = new Promise(fulfill => this._readline.once('close', fulfill));
|
||||
let closePromise = new Promise(fulfill => this._readline.once('close', fulfill));
|
||||
await(closePromise);
|
||||
}
|
||||
var text = this._lines.join('\n');
|
||||
let text = this._lines.join('\n');
|
||||
this._lines = [];
|
||||
return text;
|
||||
}
|
||||
|
@ -14,13 +14,13 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
var await = require('./utilities').await;
|
||||
var EventEmitter = require('events');
|
||||
var fs = require('fs');
|
||||
var path = require('path');
|
||||
var PageEvents = require('../lib/Page').Events;
|
||||
let await = require('./utilities').await;
|
||||
let EventEmitter = require('events');
|
||||
let fs = require('fs');
|
||||
let path = require('path');
|
||||
let PageEvents = require('../lib/Page').Events;
|
||||
|
||||
var noop = function() { };
|
||||
let noop = function() { };
|
||||
|
||||
class WebPage {
|
||||
/**
|
||||
@ -82,7 +82,7 @@ class WebPage {
|
||||
* @param {!Request} request
|
||||
*/
|
||||
function resourceInterceptor(request) {
|
||||
var requestData = {
|
||||
let requestData = {
|
||||
url: request.url(),
|
||||
headers: request.headers()
|
||||
};
|
||||
@ -95,8 +95,8 @@ class WebPage {
|
||||
_onResponseReceived(response) {
|
||||
if (!this.onResourceReceived)
|
||||
return;
|
||||
var headers = [];
|
||||
for (var key in response.headers) {
|
||||
let headers = [];
|
||||
for (let key in response.headers) {
|
||||
headers.push({
|
||||
name: key,
|
||||
value: response.headers[key]
|
||||
@ -217,7 +217,7 @@ class WebPage {
|
||||
this._onAlertCallback.call(null, dialog.message());
|
||||
await(dialog.accept());
|
||||
} else if (dialog.type === 'confirm' && this._onConfirmCallback) {
|
||||
var result = this._onConfirmCallback.call(null, dialog.message());
|
||||
let result = this._onConfirmCallback.call(null, dialog.message());
|
||||
await(result ? dialog.accept() : dialog.dismiss());
|
||||
}
|
||||
}
|
||||
@ -247,7 +247,7 @@ class WebPage {
|
||||
this.onInitialized();
|
||||
this._deferEvaluate = false;
|
||||
this._page.navigate(url).then(result => {
|
||||
var status = result ? 'success' : 'fail';
|
||||
let status = result ? 'success' : 'fail';
|
||||
if (!result) {
|
||||
this.onResourceError.call(null, {
|
||||
url,
|
||||
@ -283,8 +283,8 @@ class WebPage {
|
||||
*/
|
||||
render(fileName) {
|
||||
if (fileName.endsWith('pdf')) {
|
||||
var options = {};
|
||||
var paperSize = this.paperSize || {};
|
||||
let options = {};
|
||||
let paperSize = this.paperSize || {};
|
||||
options.margin = paperSize.margin;
|
||||
options.format = paperSize.format;
|
||||
options.landscape = paperSize.orientation === 'landscape';
|
||||
@ -292,7 +292,7 @@ class WebPage {
|
||||
options.height = paperSize.height;
|
||||
await(this._page.printToPDF(fileName, options));
|
||||
} else {
|
||||
var options = {};
|
||||
let options = {};
|
||||
if (this.clipRect && (this.clipRect.left || this.clipRect.top || this.clipRect.width || this.clipRect.height)) {
|
||||
options.clip = {
|
||||
x: this.clipRect.left,
|
||||
@ -362,7 +362,7 @@ class AsyncEmitter extends EventEmitter {
|
||||
|
||||
_onListenerAdded(event, listener) {
|
||||
// Async listener calls original listener on next tick.
|
||||
var asyncListener = (...args) => {
|
||||
let asyncListener = (...args) => {
|
||||
process.nextTick(() => listener.apply(null, args));
|
||||
};
|
||||
listener[this._symbol] = asyncListener;
|
||||
|
@ -14,8 +14,8 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
var http = require('http');
|
||||
var await = require('./utilities').await;
|
||||
let http = require('http');
|
||||
let await = require('./utilities').await;
|
||||
|
||||
class WebServer {
|
||||
constructor() {
|
||||
@ -47,17 +47,17 @@ class WebServer {
|
||||
return false;
|
||||
this.newRequest = callback;
|
||||
this._server.listen(port);
|
||||
var errorPromise = new Promise(x => this._server.once('error', x));
|
||||
var successPromise = new Promise(x => this._server.once('listening', x));
|
||||
let errorPromise = new Promise(x => this._server.once('error', x));
|
||||
let successPromise = new Promise(x => this._server.once('listening', x));
|
||||
await(Promise.race([errorPromise, successPromise]));
|
||||
if (!this._server.listening)
|
||||
return false;
|
||||
|
||||
this._server.on('request', (req, res) => {
|
||||
res.close = res.end.bind(res);
|
||||
var headers = res.getHeaders();
|
||||
let headers = res.getHeaders();
|
||||
res.headers = [];
|
||||
for (var key in headers) {
|
||||
for (let key in headers) {
|
||||
res.headers.push({
|
||||
name: key,
|
||||
value: headers[key]
|
||||
@ -65,7 +65,7 @@ class WebServer {
|
||||
}
|
||||
res.header = res.getHeader;
|
||||
res.setHeaders = headers => {
|
||||
for (var key in headers)
|
||||
for (let key in headers)
|
||||
res.setHeader(key, headers[key]);
|
||||
};
|
||||
Object.defineProperty(res, 'statusCode', {
|
||||
|
@ -15,18 +15,18 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
var vm = require('vm');
|
||||
var path = require('path');
|
||||
var fs = require('fs');
|
||||
var Phantom = require('./Phantom');
|
||||
var FileSystem = require('./FileSystem');
|
||||
var System = require('./System');
|
||||
var WebPage = require('./WebPage');
|
||||
var WebServer = require('./WebServer');
|
||||
var child_process = require('child_process');
|
||||
var Browser = require('..').Browser;
|
||||
var version = require('../package.json').version;
|
||||
var argv = require('minimist')(process.argv.slice(2), {
|
||||
let vm = require('vm');
|
||||
let path = require('path');
|
||||
let fs = require('fs');
|
||||
let Phantom = require('./Phantom');
|
||||
let FileSystem = require('./FileSystem');
|
||||
let System = require('./System');
|
||||
let WebPage = require('./WebPage');
|
||||
let WebServer = require('./WebServer');
|
||||
let child_process = require('child_process');
|
||||
let Browser = require('..').Browser;
|
||||
let version = require('../package.json').version;
|
||||
let argv = require('minimist')(process.argv.slice(2), {
|
||||
alias: { v: 'version' },
|
||||
boolean: ['headless'],
|
||||
default: {'headless': true },
|
||||
@ -43,27 +43,27 @@ if (argv['ssl-certificates-path']) {
|
||||
return;
|
||||
}
|
||||
|
||||
var scriptArguments = argv._;
|
||||
let scriptArguments = argv._;
|
||||
if (!scriptArguments.length) {
|
||||
console.log(__filename.split('/').pop() + ' [scriptfile]');
|
||||
return;
|
||||
}
|
||||
|
||||
var scriptPath = path.resolve(process.cwd(), scriptArguments[0]);
|
||||
let scriptPath = path.resolve(process.cwd(), scriptArguments[0]);
|
||||
if (!fs.existsSync(scriptPath)) {
|
||||
console.error(`script not found: ${scriptPath}`);
|
||||
process.exit(1);
|
||||
return;
|
||||
}
|
||||
|
||||
var browser = new Browser({
|
||||
let browser = new Browser({
|
||||
remoteDebuggingPort: 9229,
|
||||
headless: argv.headless,
|
||||
args: ['--no-sandbox']
|
||||
});
|
||||
|
||||
var context = createPhantomContext(browser, scriptPath, argv);
|
||||
var scriptContent = fs.readFileSync(scriptPath, 'utf8');
|
||||
let context = createPhantomContext(browser, scriptPath, argv);
|
||||
let scriptContent = fs.readFileSync(scriptPath, 'utf8');
|
||||
vm.runInContext(scriptContent, context);
|
||||
|
||||
/**
|
||||
@ -73,7 +73,7 @@ vm.runInContext(scriptContent, context);
|
||||
* @return {!Object}
|
||||
*/
|
||||
function createPhantomContext(browser, scriptPath, argv) {
|
||||
var context = {};
|
||||
let context = {};
|
||||
context.setInterval = setInterval;
|
||||
context.setTimeout = setTimeout;
|
||||
context.clearInterval = clearInterval;
|
||||
@ -86,7 +86,7 @@ function createPhantomContext(browser, scriptPath, argv) {
|
||||
|
||||
vm.createContext(context);
|
||||
|
||||
var nativeExports = {
|
||||
let nativeExports = {
|
||||
fs: new FileSystem(),
|
||||
system: new System(argv._),
|
||||
webpage: {
|
||||
@ -100,8 +100,8 @@ function createPhantomContext(browser, scriptPath, argv) {
|
||||
},
|
||||
child_process: child_process
|
||||
};
|
||||
var bootstrapPath = path.join(__dirname, '..', 'third_party', 'phantomjs', 'bootstrap.js');
|
||||
var bootstrapCode = fs.readFileSync(bootstrapPath, 'utf8');
|
||||
let bootstrapPath = path.join(__dirname, '..', 'third_party', 'phantomjs', 'bootstrap.js');
|
||||
let bootstrapCode = fs.readFileSync(bootstrapPath, 'utf8');
|
||||
vm.runInContext(bootstrapCode, context, {
|
||||
filename: 'bootstrap.js'
|
||||
})(nativeExports);
|
||||
|
@ -14,13 +14,13 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
var loopWhile = require('deasync').loopWhile;
|
||||
let loopWhile = require('deasync').loopWhile;
|
||||
|
||||
module.exports = {
|
||||
await: function(promise) {
|
||||
var error;
|
||||
var result;
|
||||
var done = false;
|
||||
let error;
|
||||
let result;
|
||||
let done = false;
|
||||
promise.then(r => result = r)
|
||||
.catch(err => error = err)
|
||||
.then(() => done = true);
|
||||
|
@ -14,11 +14,11 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
var http = require('http');
|
||||
var url = require('url');
|
||||
var fs = require('fs');
|
||||
var path = require('path');
|
||||
var mime = require('mime');
|
||||
let http = require('http');
|
||||
let url = require('url');
|
||||
let fs = require('fs');
|
||||
let path = require('path');
|
||||
let mime = require('mime');
|
||||
|
||||
class StaticServer {
|
||||
/**
|
||||
@ -36,7 +36,7 @@ class StaticServer {
|
||||
}
|
||||
|
||||
_onRequest(request, response) {
|
||||
var pathName = url.parse(request.url).path;
|
||||
let pathName = url.parse(request.url).path;
|
||||
if (pathName === '/')
|
||||
pathName = '/index.html';
|
||||
pathName = path.join(this._dirPath, pathName.substring(1));
|
||||
|
@ -1,4 +1,4 @@
|
||||
var utils = module.exports = {
|
||||
const utils = module.exports = {
|
||||
/**
|
||||
* @param {!Page} page
|
||||
* @param {string} frameId
|
||||
@ -9,7 +9,7 @@ var utils = module.exports = {
|
||||
await page.evaluate(attachFrame, frameId, url);
|
||||
|
||||
function attachFrame(frameId, url) {
|
||||
var frame = document.createElement('iframe');
|
||||
let frame = document.createElement('iframe');
|
||||
frame.src = url;
|
||||
frame.id = frameId;
|
||||
document.body.appendChild(frame);
|
||||
@ -26,7 +26,7 @@ var utils = module.exports = {
|
||||
await page.evaluate(detachFrame, frameId);
|
||||
|
||||
function detachFrame(frameId) {
|
||||
var frame = document.getElementById(frameId);
|
||||
let frame = document.getElementById(frameId);
|
||||
frame.remove();
|
||||
}
|
||||
},
|
||||
@ -41,7 +41,7 @@ var utils = module.exports = {
|
||||
await page.evaluate(navigateFrame, frameId, url);
|
||||
|
||||
function navigateFrame(frameId, url) {
|
||||
var frame = document.getElementById(frameId);
|
||||
let frame = document.getElementById(frameId);
|
||||
frame.src = url;
|
||||
return new Promise(x => frame.onload = x);
|
||||
}
|
||||
@ -54,8 +54,8 @@ var utils = module.exports = {
|
||||
*/
|
||||
dumpFrames: function(frame, indentation) {
|
||||
indentation = indentation || '';
|
||||
var result = indentation + frame.url();
|
||||
for (var child of frame.childFrames())
|
||||
let result = indentation + frame.url();
|
||||
for (let child of frame.childFrames())
|
||||
result += '\n' + utils.dumpFrames(child, ' ' + indentation);
|
||||
return result;
|
||||
},
|
||||
|
@ -13,16 +13,16 @@
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
var path = require('path');
|
||||
var fs = require('fs');
|
||||
var Diff = require('text-diff');
|
||||
var mime = require('mime');
|
||||
var PNG = require('pngjs').PNG;
|
||||
var pixelmatch = require('pixelmatch');
|
||||
var rm = require('rimraf').sync;
|
||||
let path = require('path');
|
||||
let fs = require('fs');
|
||||
let Diff = require('text-diff');
|
||||
let mime = require('mime');
|
||||
let PNG = require('pngjs').PNG;
|
||||
let pixelmatch = require('pixelmatch');
|
||||
let rm = require('rimraf').sync;
|
||||
|
||||
var GOLDEN_DIR = path.join(__dirname, 'golden');
|
||||
var OUTPUT_DIR = path.join(__dirname, 'output');
|
||||
let GOLDEN_DIR = path.join(__dirname, 'golden');
|
||||
let OUTPUT_DIR = path.join(__dirname, 'output');
|
||||
|
||||
module.exports = {
|
||||
addMatchers: function(jasmine) {
|
||||
@ -35,7 +35,7 @@ module.exports = {
|
||||
},
|
||||
};
|
||||
|
||||
var GoldenComparators = {
|
||||
let GoldenComparators = {
|
||||
'image/png': compareImages,
|
||||
'text/plain': compareText
|
||||
};
|
||||
@ -49,15 +49,15 @@ function compareImages(actualBuffer, expectedBuffer) {
|
||||
if (!actualBuffer || !(actualBuffer instanceof Buffer))
|
||||
return { errorMessage: 'Actual result should be Buffer.' };
|
||||
|
||||
var actual = PNG.sync.read(actualBuffer);
|
||||
var expected = PNG.sync.read(expectedBuffer);
|
||||
let actual = PNG.sync.read(actualBuffer);
|
||||
let expected = PNG.sync.read(expectedBuffer);
|
||||
if (expected.width !== actual.width || expected.height !== actual.height) {
|
||||
return {
|
||||
errorMessage: `Sizes differ: expected image ${expected.width}px X ${expected.height}px, but got ${actual.width}px X ${actual.height}px. `
|
||||
};
|
||||
}
|
||||
var diff = new PNG({width: expected.width, height: expected.height});
|
||||
var count = pixelmatch(expected.data, actual.data, diff.data, expected.width, expected.height, {threshold: 0.1});
|
||||
let diff = new PNG({width: expected.width, height: expected.height});
|
||||
let count = pixelmatch(expected.data, actual.data, diff.data, expected.width, expected.height, {threshold: 0.1});
|
||||
return count > 0 ? { diff: PNG.sync.write(diff) } : null;
|
||||
}
|
||||
|
||||
@ -69,14 +69,14 @@ function compareImages(actualBuffer, expectedBuffer) {
|
||||
function compareText(actual, expectedBuffer) {
|
||||
if (typeof actual !== 'string')
|
||||
return { errorMessage: 'Actual result should be string' };
|
||||
var expected = expectedBuffer.toString('utf-8');
|
||||
let expected = expectedBuffer.toString('utf-8');
|
||||
if (expected === actual)
|
||||
return null;
|
||||
var diff = new Diff();
|
||||
var result = diff.main(expected, actual);
|
||||
let diff = new Diff();
|
||||
let result = diff.main(expected, actual);
|
||||
diff.cleanupSemantic(result);
|
||||
var html = diff.prettyHtml(result);
|
||||
var diffStylePath = path.join(__dirname, 'diffstyle.css');
|
||||
let html = diff.prettyHtml(result);
|
||||
let diffStylePath = path.join(__dirname, 'diffstyle.css');
|
||||
html = `<link rel="stylesheet" href="file://${diffStylePath}">` + html;
|
||||
return {
|
||||
diff: html,
|
||||
@ -84,7 +84,7 @@ function compareText(actual, expectedBuffer) {
|
||||
};
|
||||
}
|
||||
|
||||
var customMatchers = {
|
||||
let customMatchers = {
|
||||
toBeGolden: function(util, customEqualityTesters) {
|
||||
return {
|
||||
/**
|
||||
@ -93,10 +93,10 @@ var customMatchers = {
|
||||
* @return {!{pass: boolean, message: (undefined|string)}}
|
||||
*/
|
||||
compare: function(actual, goldenName) {
|
||||
var expectedPath = path.join(GOLDEN_DIR, goldenName);
|
||||
var actualPath = path.join(OUTPUT_DIR, goldenName);
|
||||
let expectedPath = path.join(GOLDEN_DIR, goldenName);
|
||||
let actualPath = path.join(OUTPUT_DIR, goldenName);
|
||||
|
||||
var messageSuffix = 'Output is saved in "' + path.basename(OUTPUT_DIR + '" directory');
|
||||
let messageSuffix = 'Output is saved in "' + path.basename(OUTPUT_DIR + '" directory');
|
||||
|
||||
if (!fs.existsSync(expectedPath)) {
|
||||
ensureOutputDir();
|
||||
@ -106,15 +106,15 @@ var customMatchers = {
|
||||
message: goldenName + ' is missing in golden results. ' + messageSuffix
|
||||
};
|
||||
}
|
||||
var expected = fs.readFileSync(expectedPath);
|
||||
var comparator = GoldenComparators[mime.lookup(goldenName)];
|
||||
let expected = fs.readFileSync(expectedPath);
|
||||
let comparator = GoldenComparators[mime.lookup(goldenName)];
|
||||
if (!comparator) {
|
||||
return {
|
||||
pass: false,
|
||||
message: 'Failed to find comparator with type ' + mime.lookup(goldenName) + ': ' + goldenName
|
||||
};
|
||||
}
|
||||
var result = comparator(actual, expected);
|
||||
let result = comparator(actual, expected);
|
||||
if (!result)
|
||||
return { pass: true };
|
||||
ensureOutputDir();
|
||||
@ -122,11 +122,11 @@ var customMatchers = {
|
||||
// Copy expected to the output/ folder for convenience.
|
||||
fs.writeFileSync(addSuffix(actualPath, '-expected'), expected);
|
||||
if (result.diff) {
|
||||
var diffPath = addSuffix(actualPath, '-diff', result.diffExtension);
|
||||
let diffPath = addSuffix(actualPath, '-diff', result.diffExtension);
|
||||
fs.writeFileSync(diffPath, result.diff);
|
||||
}
|
||||
|
||||
var message = goldenName + ' mismatch!';
|
||||
let message = goldenName + ' mismatch!';
|
||||
if (result.errorMessage)
|
||||
message += ' ' + result.errorMessage;
|
||||
return {
|
||||
@ -150,8 +150,8 @@ var customMatchers = {
|
||||
* @return {string}
|
||||
*/
|
||||
function addSuffix(filePath, suffix, customExtension) {
|
||||
var dirname = path.dirname(filePath);
|
||||
var ext = path.extname(filePath);
|
||||
var name = path.basename(filePath, ext);
|
||||
let dirname = path.dirname(filePath);
|
||||
let ext = path.extname(filePath);
|
||||
let name = path.basename(filePath, ext);
|
||||
return path.join(dirname, name + suffix + (customExtension || ext));
|
||||
}
|
||||
|
88
test/test.js
88
test/test.js
@ -14,21 +14,21 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
var path = require('path');
|
||||
var Browser = require('../lib/Browser');
|
||||
var StaticServer = require('./StaticServer');
|
||||
var GoldenUtils = require('./golden-utils');
|
||||
let path = require('path');
|
||||
let Browser = require('../lib/Browser');
|
||||
let StaticServer = require('./StaticServer');
|
||||
let GoldenUtils = require('./golden-utils');
|
||||
|
||||
var PORT = 8907;
|
||||
var STATIC_PREFIX = 'http://localhost:' + PORT;
|
||||
var EMPTY_PAGE = STATIC_PREFIX + '/empty.html';
|
||||
let PORT = 8907;
|
||||
let STATIC_PREFIX = 'http://localhost:' + PORT;
|
||||
let EMPTY_PAGE = STATIC_PREFIX + '/empty.html';
|
||||
|
||||
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10 * 1000;
|
||||
|
||||
describe('Puppeteer', function() {
|
||||
var browser;
|
||||
var staticServer;
|
||||
var page;
|
||||
let browser;
|
||||
let staticServer;
|
||||
let page;
|
||||
|
||||
beforeAll(function() {
|
||||
browser = new Browser({args: ['--no-sandbox']});
|
||||
@ -52,11 +52,11 @@ describe('Puppeteer', function() {
|
||||
|
||||
describe('Page.evaluate', function() {
|
||||
it('should work', SX(async function() {
|
||||
var result = await page.evaluate(() => 7 * 3);
|
||||
let result = await page.evaluate(() => 7 * 3);
|
||||
expect(result).toBe(21);
|
||||
}));
|
||||
it('should await promise', SX(async function() {
|
||||
var result = await page.evaluate(() => Promise.resolve(8 * 7));
|
||||
let result = await page.evaluate(() => Promise.resolve(8 * 7));
|
||||
expect(result).toBe(56);
|
||||
}));
|
||||
it('should work from-inside inPageCallback', SX(async function() {
|
||||
@ -64,13 +64,13 @@ describe('Puppeteer', function() {
|
||||
await page.setInPageCallback('callController', async function(a, b) {
|
||||
return await page.evaluate((a, b) => a * b, a, b);
|
||||
});
|
||||
var result = await page.evaluate(async function() {
|
||||
let result = await page.evaluate(async function() {
|
||||
return await callController(9, 3);
|
||||
});
|
||||
expect(result).toBe(27);
|
||||
}));
|
||||
it('should reject promise with exception', SX(async function() {
|
||||
var error = null;
|
||||
let error = null;
|
||||
try {
|
||||
await page.evaluate(() => not.existing.object.property);
|
||||
} catch (e) {
|
||||
@ -82,7 +82,7 @@ describe('Puppeteer', function() {
|
||||
});
|
||||
|
||||
it('Page Events: ConsoleMessage', SX(async function() {
|
||||
var msgs = [];
|
||||
let msgs = [];
|
||||
page.on('consolemessage', msg => msgs.push(msg));
|
||||
await page.evaluate(() => console.log('Message!'));
|
||||
expect(msgs).toEqual(['Message!']);
|
||||
@ -90,11 +90,11 @@ describe('Puppeteer', function() {
|
||||
|
||||
describe('Page.navigate', function() {
|
||||
it('should fail when navigating to bad url', SX(async function() {
|
||||
var success = await page.navigate('asdfasdf');
|
||||
let success = await page.navigate('asdfasdf');
|
||||
expect(success).toBe(false);
|
||||
}));
|
||||
it('should succeed when navigating to good url', SX(async function() {
|
||||
var success = await page.navigate(EMPTY_PAGE);
|
||||
let success = await page.navigate(EMPTY_PAGE);
|
||||
expect(success).toBe(true);
|
||||
}));
|
||||
});
|
||||
@ -104,7 +104,7 @@ describe('Puppeteer', function() {
|
||||
await page.setInPageCallback('callController', function(a, b) {
|
||||
return a * b;
|
||||
});
|
||||
var result = await page.evaluate(async function() {
|
||||
let result = await page.evaluate(async function() {
|
||||
return await callController(9, 4);
|
||||
});
|
||||
expect(result).toBe(36);
|
||||
@ -115,7 +115,7 @@ describe('Puppeteer', function() {
|
||||
});
|
||||
|
||||
await page.navigate(EMPTY_PAGE);
|
||||
var result = await page.evaluate(async function() {
|
||||
let result = await page.evaluate(async function() {
|
||||
return await callController(9, 4);
|
||||
});
|
||||
expect(result).toBe(36);
|
||||
@ -125,7 +125,7 @@ describe('Puppeteer', function() {
|
||||
return Promise.resolve(a * b);
|
||||
});
|
||||
|
||||
var result = await page.evaluate(async function() {
|
||||
let result = await page.evaluate(async function() {
|
||||
return await callController(3, 5);
|
||||
});
|
||||
expect(result).toBe(15);
|
||||
@ -141,7 +141,7 @@ describe('Puppeteer', function() {
|
||||
expect(request.postData()).toBe(undefined);
|
||||
request.continue();
|
||||
});
|
||||
var success = await page.navigate(EMPTY_PAGE);
|
||||
let success = await page.navigate(EMPTY_PAGE);
|
||||
expect(success).toBe(true);
|
||||
}));
|
||||
it('should show extraHTTPHeaders', SX(async function() {
|
||||
@ -152,7 +152,7 @@ describe('Puppeteer', function() {
|
||||
expect(request.headers()['foo']).toBe('bar');
|
||||
request.continue();
|
||||
});
|
||||
var success = await page.navigate(EMPTY_PAGE);
|
||||
let success = await page.navigate(EMPTY_PAGE);
|
||||
expect(success).toBe(true);
|
||||
}));
|
||||
it('should be abortable', SX(async function() {
|
||||
@ -162,9 +162,9 @@ describe('Puppeteer', function() {
|
||||
else
|
||||
request.continue();
|
||||
});
|
||||
var failedResources = 0;
|
||||
let failedResources = 0;
|
||||
page.on('resourceloadingfailed', event => ++failedResources);
|
||||
var success = await page.navigate(STATIC_PREFIX + '/one-style.html');
|
||||
let success = await page.navigate(STATIC_PREFIX + '/one-style.html');
|
||||
expect(success).toBe(true);
|
||||
expect(failedResources).toBe(1);
|
||||
}));
|
||||
@ -186,7 +186,7 @@ describe('Puppeteer', function() {
|
||||
expect(dialog.message()).toBe('question?');
|
||||
dialog.accept('answer!');
|
||||
});
|
||||
var result = await page.evaluate(() => prompt('question?'));
|
||||
let result = await page.evaluate(() => prompt('question?'));
|
||||
expect(result).toBe('answer!');
|
||||
}));
|
||||
});
|
||||
@ -205,13 +205,13 @@ describe('Puppeteer', function() {
|
||||
it('should work', SX(async function() {
|
||||
await page.setViewportSize({width: 500, height: 500});
|
||||
await page.navigate(STATIC_PREFIX + '/grid.html');
|
||||
var screenshot = await page.screenshot();
|
||||
let screenshot = await page.screenshot();
|
||||
expect(screenshot).toBeGolden('screenshot-sanity.png');
|
||||
}));
|
||||
it('should clip rect', SX(async function() {
|
||||
await page.setViewportSize({width: 500, height: 500});
|
||||
await page.navigate(STATIC_PREFIX + '/grid.html');
|
||||
var screenshot = await page.screenshot({
|
||||
let screenshot = await page.screenshot({
|
||||
clip: {
|
||||
x: 50,
|
||||
y: 100,
|
||||
@ -224,7 +224,7 @@ describe('Puppeteer', function() {
|
||||
it('should work for offscreen clip', SX(async function() {
|
||||
await page.setViewportSize({width: 500, height: 500});
|
||||
await page.navigate(STATIC_PREFIX + '/grid.html');
|
||||
var screenshot = await page.screenshot({
|
||||
let screenshot = await page.screenshot({
|
||||
clip: {
|
||||
x: 50,
|
||||
y: 600,
|
||||
@ -237,8 +237,8 @@ describe('Puppeteer', function() {
|
||||
it('should run in parallel', SX(async function() {
|
||||
await page.setViewportSize({width: 500, height: 500});
|
||||
await page.navigate(STATIC_PREFIX + '/grid.html');
|
||||
var promises = [];
|
||||
for (var i = 0; i < 3; ++i) {
|
||||
let promises = [];
|
||||
for (let i = 0; i < 3; ++i) {
|
||||
promises.push(page.screenshot({
|
||||
clip: {
|
||||
x: 50 * i,
|
||||
@ -248,13 +248,13 @@ describe('Puppeteer', function() {
|
||||
}
|
||||
}));
|
||||
}
|
||||
var screenshot = await promises[1];
|
||||
let screenshot = await promises[1];
|
||||
expect(screenshot).toBeGolden('screenshot-parallel-calls.png');
|
||||
}));
|
||||
it('should take fullPage screenshots', SX(async function() {
|
||||
await page.setViewportSize({width: 500, height: 500});
|
||||
await page.navigate(STATIC_PREFIX + '/grid.html');
|
||||
var screenshot = await page.screenshot({
|
||||
let screenshot = await page.screenshot({
|
||||
fullPage: true
|
||||
});
|
||||
expect(screenshot).toBeGolden('screenshot-grid-fullpage.png');
|
||||
@ -262,7 +262,7 @@ describe('Puppeteer', function() {
|
||||
});
|
||||
|
||||
describe('Frame Management', function() {
|
||||
var FrameUtils = require('./frame-utils');
|
||||
let FrameUtils = require('./frame-utils');
|
||||
it('should handle nested frames', SX(async function() {
|
||||
await page.navigate(STATIC_PREFIX + '/frames/nested-frames.html');
|
||||
expect(FrameUtils.dumpFrames(page.mainFrame())).toBeGolden('nested-frames.txt');
|
||||
@ -270,21 +270,21 @@ describe('Puppeteer', function() {
|
||||
it('should send events when frames are manipulated dynamically', SX(async function() {
|
||||
await page.navigate(EMPTY_PAGE);
|
||||
// validate frameattached events
|
||||
var attachedFrames = [];
|
||||
let attachedFrames = [];
|
||||
page.on('frameattached', frame => attachedFrames.push(frame));
|
||||
await FrameUtils.attachFrame(page, 'frame1', './assets/frame.html');
|
||||
expect(attachedFrames.length).toBe(1);
|
||||
expect(attachedFrames[0].url()).toContain('/assets/frame.html');
|
||||
|
||||
// validate framenavigated events
|
||||
var navigatedFrames = [];
|
||||
let navigatedFrames = [];
|
||||
page.on('framenavigated', frame => navigatedFrames.push(frame));
|
||||
await FrameUtils.navigateFrame(page, 'frame1', './empty.html');
|
||||
expect(navigatedFrames.length).toBe(1);
|
||||
expect(navigatedFrames[0].url()).toContain('/empty.html');
|
||||
|
||||
// validate framedetached events
|
||||
var detachedFrames = [];
|
||||
let detachedFrames = [];
|
||||
page.on('framedetached', frame => detachedFrames.push(frame));
|
||||
await FrameUtils.detachFrame(page, 'frame1');
|
||||
expect(detachedFrames.length).toBe(1);
|
||||
@ -292,21 +292,21 @@ describe('Puppeteer', function() {
|
||||
}));
|
||||
it('should persist mainFrame on cross-process navigation', SX(async function() {
|
||||
await page.navigate(EMPTY_PAGE);
|
||||
var mainFrame = page.mainFrame();
|
||||
let mainFrame = page.mainFrame();
|
||||
await page.navigate('http://127.0.0.1:' + PORT + '/empty.html');
|
||||
expect(page.mainFrame() === mainFrame).toBeTruthy();
|
||||
}));
|
||||
it('should not send attach/detach events for main frame', SX(async function() {
|
||||
var hasEvents = false;
|
||||
let hasEvents = false;
|
||||
page.on('frameattached', frame => hasEvents = true);
|
||||
page.on('framedetached', frame => hasEvents = true);
|
||||
await page.navigate(EMPTY_PAGE);
|
||||
expect(hasEvents).toBe(false);
|
||||
}));
|
||||
it('should detach child frames on navigation', SX(async function() {
|
||||
var attachedFrames = [];
|
||||
var detachedFrames = [];
|
||||
var navigatedFrames = [];
|
||||
let attachedFrames = [];
|
||||
let detachedFrames = [];
|
||||
let navigatedFrames = [];
|
||||
page.on('frameattached', frame => attachedFrames.push(frame));
|
||||
page.on('framedetached', frame => detachedFrames.push(frame));
|
||||
page.on('framenavigated', frame => navigatedFrames.push(frame));
|
||||
@ -315,9 +315,9 @@ describe('Puppeteer', function() {
|
||||
expect(detachedFrames.length).toBe(0);
|
||||
expect(navigatedFrames.length).toBe(5);
|
||||
|
||||
var attachedFrames = [];
|
||||
var detachedFrames = [];
|
||||
var navigatedFrames = [];
|
||||
attachedFrames = [];
|
||||
detachedFrames = [];
|
||||
navigatedFrames = [];
|
||||
await page.navigate(EMPTY_PAGE);
|
||||
expect(attachedFrames.length).toBe(0);
|
||||
expect(detachedFrames.length).toBe(4);
|
||||
|
@ -14,17 +14,17 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
var os = require('os');
|
||||
var https = require('https');
|
||||
var fs = require('fs');
|
||||
var path = require('path');
|
||||
var extract = require('extract-zip');
|
||||
var util = require('util');
|
||||
var URL = require('url');
|
||||
let os = require('os');
|
||||
let https = require('https');
|
||||
let fs = require('fs');
|
||||
let path = require('path');
|
||||
let extract = require('extract-zip');
|
||||
let util = require('util');
|
||||
let URL = require('url');
|
||||
|
||||
var CHROMIUM_PATH = path.join(__dirname, '..', '.local-chromium');
|
||||
let CHROMIUM_PATH = path.join(__dirname, '..', '.local-chromium');
|
||||
|
||||
var downloadURLs = {
|
||||
let downloadURLs = {
|
||||
linux: 'https://storage.googleapis.com/chromium-browser-snapshots/Linux_x64/%d/chrome-linux.zip',
|
||||
mac: 'https://storage.googleapis.com/chromium-browser-snapshots/Mac/%d/chrome-mac.zip',
|
||||
win32: 'https://storage.googleapis.com/chromium-browser-snapshots/Win/%d/chrome-win32.zip',
|
||||
@ -43,7 +43,7 @@ module.exports = {
|
||||
* @return {string}
|
||||
*/
|
||||
currentPlatform: function() {
|
||||
var platform = os.platform();
|
||||
let platform = os.platform();
|
||||
if (platform === 'darwin')
|
||||
return 'mac';
|
||||
if (platform === 'linux')
|
||||
@ -60,15 +60,15 @@ module.exports = {
|
||||
*/
|
||||
canDownloadRevision: function(platform, revision) {
|
||||
console.assert(downloadURLs[platform], 'Unknown platform: ' + platform);
|
||||
var url = URL.parse(util.format(downloadURLs[platform], revision));
|
||||
var options = {
|
||||
let url = URL.parse(util.format(downloadURLs[platform], revision));
|
||||
let options = {
|
||||
method: 'HEAD',
|
||||
host: url.host,
|
||||
path: url.pathname,
|
||||
};
|
||||
var resolve;
|
||||
var promise = new Promise(x => resolve = x);
|
||||
var request = https.request(options, response => {
|
||||
let resolve;
|
||||
let promise = new Promise(x => resolve = x);
|
||||
let request = https.request(options, response => {
|
||||
resolve(response.statusCode === 200);
|
||||
});
|
||||
request.on('error', error => {
|
||||
@ -86,11 +86,11 @@ module.exports = {
|
||||
* @return {!Promise}
|
||||
*/
|
||||
downloadRevision: async function(platform, revision, progressCallback) {
|
||||
var url = downloadURLs[platform];
|
||||
let url = downloadURLs[platform];
|
||||
console.assert(url, `Unsupported platform: ${platform}`);
|
||||
url = util.format(url, revision);
|
||||
var zipPath = path.join(CHROMIUM_PATH, `download-${platform}-${revision}.zip`);
|
||||
var folderPath = getFolderPath(platform, revision);
|
||||
let zipPath = path.join(CHROMIUM_PATH, `download-${platform}-${revision}.zip`);
|
||||
let folderPath = getFolderPath(platform, revision);
|
||||
if (fs.existsSync(folderPath))
|
||||
return;
|
||||
try {
|
||||
@ -110,10 +110,10 @@ module.exports = {
|
||||
* @return {?{executablePath: string}}
|
||||
*/
|
||||
revisionInfo: function(platform, revision) {
|
||||
var folderPath = getFolderPath(platform, revision);
|
||||
let folderPath = getFolderPath(platform, revision);
|
||||
if (!fs.existsSync(folderPath))
|
||||
return null;
|
||||
var executablePath = '';
|
||||
let executablePath = '';
|
||||
if (platform === 'mac')
|
||||
executablePath = path.join(folderPath, 'chrome-mac', 'Chromium.app', 'Contents', 'MacOS', 'Chromium');
|
||||
else if (platform === 'linux')
|
||||
@ -144,21 +144,21 @@ function getFolderPath(platform, revision) {
|
||||
* @return {!Promise}
|
||||
*/
|
||||
function downloadFile(url, destinationPath, progressCallback) {
|
||||
var fulfill, reject;
|
||||
var promise = new Promise((x, y) => { fulfill = x; reject = y; });
|
||||
var request = https.get(url, response => {
|
||||
let fulfill, reject;
|
||||
let promise = new Promise((x, y) => { fulfill = x; reject = y; });
|
||||
let request = https.get(url, response => {
|
||||
if (response.statusCode !== 200) {
|
||||
var error = new Error(`Download failed: server returned code ${response.statusCode}. URL: ${url}`);
|
||||
let error = new Error(`Download failed: server returned code ${response.statusCode}. URL: ${url}`);
|
||||
// consume response data to free up memory
|
||||
response.resume();
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
var file = fs.createWriteStream(destinationPath);
|
||||
let file = fs.createWriteStream(destinationPath);
|
||||
file.on('finish', () => fulfill());
|
||||
file.on('error', error => reject(error));
|
||||
response.pipe(file);
|
||||
var totalBytes = parseInt(response.headers['content-length'], 10);
|
||||
let totalBytes = parseInt(response.headers['content-length'], 10);
|
||||
if (progressCallback)
|
||||
response.on('data', onData.bind(null, totalBytes));
|
||||
});
|
||||
|
@ -15,11 +15,11 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
var Downloader = require('./ChromiumDownloader');
|
||||
var https = require('https');
|
||||
var OMAHA_PROXY = 'https://omahaproxy.appspot.com/all.json';
|
||||
let Downloader = require('./ChromiumDownloader');
|
||||
let https = require('https');
|
||||
let OMAHA_PROXY = 'https://omahaproxy.appspot.com/all.json';
|
||||
|
||||
var colors = {
|
||||
let colors = {
|
||||
reset: '\x1b[0m',
|
||||
red: '\x1b[31m',
|
||||
green: '\x1b[32m',
|
||||
@ -39,8 +39,8 @@ class Table {
|
||||
*/
|
||||
drawRow(values) {
|
||||
console.assert(values.length === this.widths.length);
|
||||
var row = '';
|
||||
for (var i = 0; i < values.length; ++i)
|
||||
let row = '';
|
||||
for (let i = 0; i < values.length; ++i)
|
||||
row += padCenter(values[i], this.widths[i]);
|
||||
console.log(row);
|
||||
}
|
||||
@ -59,8 +59,8 @@ Running command without arguments will check against omahaproxy revisions.`);
|
||||
return;
|
||||
}
|
||||
|
||||
var fromRevision = parseInt(process.argv[2], 10);
|
||||
var toRevision = parseInt(process.argv[3], 10);
|
||||
let fromRevision = parseInt(process.argv[2], 10);
|
||||
let toRevision = parseInt(process.argv[3], 10);
|
||||
checkRangeAvailability(fromRevision, toRevision);
|
||||
|
||||
/**
|
||||
@ -68,23 +68,23 @@ checkRangeAvailability(fromRevision, toRevision);
|
||||
*/
|
||||
async function checkOmahaProxyAvailability() {
|
||||
console.log('Fetching revisions from ' + OMAHA_PROXY);
|
||||
var platforms = await loadJSON(OMAHA_PROXY);
|
||||
let platforms = await loadJSON(OMAHA_PROXY);
|
||||
if (!platforms) {
|
||||
console.error('ERROR: failed to fetch chromium revisions from omahaproxy.');
|
||||
return;
|
||||
}
|
||||
var table = new Table([27, 7, 7, 7, 7]);
|
||||
let table = new Table([27, 7, 7, 7, 7]);
|
||||
table.drawRow([''].concat(Downloader.supportedPlatforms()));
|
||||
for (var platform of platforms) {
|
||||
for (let platform of platforms) {
|
||||
// Trust only to the main platforms.
|
||||
if (platform.os !== 'mac' && platform.os !== 'win' && platform.os !== 'win64' && platform.os !== 'linux')
|
||||
continue;
|
||||
var osName = platform.os === 'win' ? 'win32' : platform.os;
|
||||
for (var version of platform.versions) {
|
||||
let osName = platform.os === 'win' ? 'win32' : platform.os;
|
||||
for (let version of platform.versions) {
|
||||
if (version.channel !== 'dev' && version.channel !== 'beta' && version.channel !== 'canary' && version.channel !== 'stable')
|
||||
continue;
|
||||
var revisionName = padLeft('[' + osName + ' ' + version.channel + ']', 15);
|
||||
var revision = parseInt(version.branch_base_position, 10);
|
||||
let revisionName = padLeft('[' + osName + ' ' + version.channel + ']', 15);
|
||||
let revision = parseInt(version.branch_base_position, 10);
|
||||
await checkAndDrawRevisionAvailability(table, revisionName, revision);
|
||||
}
|
||||
}
|
||||
@ -96,10 +96,10 @@ async function checkOmahaProxyAvailability() {
|
||||
* @return {!Promise}
|
||||
*/
|
||||
async function checkRangeAvailability(fromRevision, toRevision) {
|
||||
var table = new Table([10, 7, 7, 7, 7]);
|
||||
let table = new Table([10, 7, 7, 7, 7]);
|
||||
table.drawRow([''].concat(Downloader.supportedPlatforms()));
|
||||
var inc = fromRevision < toRevision ? 1 : -1;
|
||||
for (var revision = fromRevision; revision !== toRevision; revision += inc)
|
||||
let inc = fromRevision < toRevision ? 1 : -1;
|
||||
for (let revision = fromRevision; revision !== toRevision; revision += inc)
|
||||
await checkAndDrawRevisionAvailability(table, '', revision);
|
||||
}
|
||||
|
||||
@ -110,15 +110,15 @@ async function checkRangeAvailability(fromRevision, toRevision) {
|
||||
* @return {!Promise}
|
||||
*/
|
||||
async function checkAndDrawRevisionAvailability(table, name, revision) {
|
||||
var promises = [];
|
||||
for (var platform of Downloader.supportedPlatforms())
|
||||
let promises = [];
|
||||
for (let platform of Downloader.supportedPlatforms())
|
||||
promises.push(Downloader.canDownloadRevision(platform, revision));
|
||||
var availability = await Promise.all(promises);
|
||||
var allAvailable = availability.every(e => !!e);
|
||||
var values = [name + ' ' + (allAvailable ? colors.green + revision + colors.reset : revision)];
|
||||
for (var i = 0; i < availability.length; ++i) {
|
||||
var decoration = availability[i] ? '+' : '-';
|
||||
var color = availability[i] ? colors.green : colors.red;
|
||||
let availability = await Promise.all(promises);
|
||||
let allAvailable = availability.every(e => !!e);
|
||||
let values = [name + ' ' + (allAvailable ? colors.green + revision + colors.reset : revision)];
|
||||
for (let i = 0; i < availability.length; ++i) {
|
||||
let decoration = availability[i] ? '+' : '-';
|
||||
let color = availability[i] ? colors.green : colors.red;
|
||||
values.push(color + decoration + colors.reset);
|
||||
}
|
||||
table.drawRow(values);
|
||||
@ -129,19 +129,19 @@ async function checkAndDrawRevisionAvailability(table, name, revision) {
|
||||
* @return {!Promise<?Object>}
|
||||
*/
|
||||
function loadJSON(url) {
|
||||
var resolve;
|
||||
var promise = new Promise(x => resolve = x);
|
||||
let resolve;
|
||||
let promise = new Promise(x => resolve = x);
|
||||
https.get(url, response => {
|
||||
if (response.statusCode !== 200) {
|
||||
resolve(null);
|
||||
return;
|
||||
}
|
||||
var body = '';
|
||||
let body = '';
|
||||
response.on('data', function(chunk){
|
||||
body += chunk;
|
||||
});
|
||||
response.on('end', function(){
|
||||
var json = JSON.parse(body);
|
||||
let json = JSON.parse(body);
|
||||
resolve(json);
|
||||
});
|
||||
}).on('error', function(e){
|
||||
@ -164,8 +164,8 @@ function spaceString(size) {
|
||||
* @return {string}
|
||||
*/
|
||||
function filterOutColors(text) {
|
||||
for (var colorName in colors) {
|
||||
var color = colors[colorName];
|
||||
for (let colorName in colors) {
|
||||
let color = colors[colorName];
|
||||
text = text.replace(color, '');
|
||||
}
|
||||
return text;
|
||||
@ -177,7 +177,7 @@ function filterOutColors(text) {
|
||||
* @return {string}
|
||||
*/
|
||||
function padLeft(text, length) {
|
||||
var printableCharacters = filterOutColors(text);
|
||||
let printableCharacters = filterOutColors(text);
|
||||
return printableCharacters.length >= length ? text : spaceString(length - text.length) + text;
|
||||
}
|
||||
|
||||
@ -187,10 +187,10 @@ function padLeft(text, length) {
|
||||
* @return {string}
|
||||
*/
|
||||
function padCenter(text, length) {
|
||||
var printableCharacters = filterOutColors(text);
|
||||
let printableCharacters = filterOutColors(text);
|
||||
if (printableCharacters.length >= length)
|
||||
return text;
|
||||
var left = Math.floor((length - printableCharacters.length) / 2);
|
||||
var right = Math.ceil((length - printableCharacters.length) / 2);
|
||||
let left = Math.floor((length - printableCharacters.length) / 2);
|
||||
let right = Math.ceil((length - printableCharacters.length) / 2);
|
||||
return spaceString(left) + text + spaceString(right);
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user