Skip to content

Commit

Permalink
Change let into const (puppeteer#457)
Browse files Browse the repository at this point in the history
This patch:
- changes `let` into `const` throughout codebase
- adds eslint check to prefer const over let
  • Loading branch information
ebidel authored and aslushnikov committed Aug 21, 2017
1 parent 5d6d3e0 commit 1f9b4fb
Show file tree
Hide file tree
Showing 37 changed files with 495 additions and 494 deletions.
1 change: 1 addition & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ module.exports = {
"new-parens": 2,
"func-call-spacing": 2,
"arrow-parens": [2, "as-needed"],
"prefer-const": 2,

// anti-patterns
"no-var": 2,
Expand Down
2 changes: 1 addition & 1 deletion DeviceDescriptors.js
Original file line number Diff line number Diff line change
Expand Up @@ -628,5 +628,5 @@ module.exports = [
}
}
];
for (let device of module.exports)
for (const device of module.exports)
module.exports[device.name] = device;
4 changes: 2 additions & 2 deletions install.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ const revisionInfo = Downloader.revisionInfo(platform, revision);
if (revisionInfo.downloaded)
return;

let allRevisions = Downloader.downloadedRevisions();
const allRevisions = Downloader.downloadedRevisions();
Downloader.downloadRevision(platform, revision, onProgress)
// Remove previous chromium revisions.
.then(() => Promise.all(allRevisions.map(({platform, revision}) => Downloader.removeRevision(platform, revision))))
Expand Down Expand Up @@ -52,7 +52,7 @@ function onProgress(bytesTotal, delta) {
}

function toMegabytes(bytes) {
let mb = bytes / 1024 / 1024;
const mb = bytes / 1024 / 1024;
return `${Math.round(mb * 10) / 10} Mb`;
}

2 changes: 1 addition & 1 deletion lib/Browser.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ class Browser {
* @return {!Promise<string>}
*/
async version() {
let version = await this._connection.send('Browser.getVersion');
const version = await this._connection.send('Browser.getVersion');
return version.product;
}

Expand Down
26 changes: 13 additions & 13 deletions lib/Connection.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ class Connection extends EventEmitter {
*/
static async create(url, delay = 0) {
return new Promise((resolve, reject) => {
let ws = new WebSocket(url, { perMessageDeflate: false });
const ws = new WebSocket(url, { perMessageDeflate: false });
ws.on('open', () => resolve(new Connection(url, ws, delay)));
ws.on('error', reject);
});
Expand Down Expand Up @@ -66,8 +66,8 @@ class Connection extends EventEmitter {
* @return {!Promise<?Object>}
*/
send(method, params = {}) {
let id = ++this._lastId;
let message = JSON.stringify({id, method, params});
const id = ++this._lastId;
const message = JSON.stringify({id, method, params});
debugProtocol('SEND ► ' + message);
this._ws.send(message);
return new Promise((resolve, reject) => {
Expand All @@ -82,9 +82,9 @@ class Connection extends EventEmitter {
if (this._delay)
await new Promise(f => setTimeout(f, this._delay));
debugProtocol('◀ RECV ' + message);
let object = JSON.parse(message);
const object = JSON.parse(message);
if (object.id && this._callbacks.has(object.id)) {
let callback = this._callbacks.get(object.id);
const 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} ${object.error.data}`));
Expand All @@ -109,10 +109,10 @@ class Connection extends EventEmitter {

_onClose() {
this._ws.removeAllListeners();
for (let callback of this._callbacks.values())
for (const callback of this._callbacks.values())
callback.reject(new Error(`Protocol error (${callback.method}): Target closed.`));
this._callbacks.clear();
for (let session of this._sessions.values())
for (const session of this._sessions.values())
session._onClosed();
this._sessions.clear();
}
Expand Down Expand Up @@ -168,14 +168,14 @@ class Session extends EventEmitter {
send(method, params = {}) {
if (!this._connection)
return Promise.reject(new Error(`Protocol error (${method}): Session closed. Most likely the page has been closed.`));
let id = ++this._lastId;
let message = JSON.stringify({id, method, params});
const id = ++this._lastId;
const message = JSON.stringify({id, method, params});
debugSession('SEND ► ' + message);
this._connection.send('Target.sendMessageToTarget', {sessionId: this._sessionId, message}).catch(e => {
// The response from target might have been already dispatched.
if (!this._callbacks.has(id))
return;
let callback = this._callbacks.get(id);
const callback = this._callbacks.get(id);
this._callbacks.delete(object.id);
callback.reject(e);
});
Expand All @@ -189,9 +189,9 @@ class Session extends EventEmitter {
*/
_onMessage(message) {
debugSession('◀ RECV ' + message);
let object = JSON.parse(message);
const object = JSON.parse(message);
if (object.id && this._callbacks.has(object.id)) {
let callback = this._callbacks.get(object.id);
const 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} ${object.error.data}`));
Expand All @@ -211,7 +211,7 @@ class Session extends EventEmitter {
}

_onClosed() {
for (let callback of this._callbacks.values())
for (const callback of this._callbacks.values())
callback.reject(new Error(`Protocol error (${callback.method}): Target closed.`));
this._callbacks.clear();
this._connection = null;
Expand Down
16 changes: 8 additions & 8 deletions lib/ElementHandle.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,11 @@ class ElementHandle {
console.assert(!this._disposed, 'ElementHandle is disposed!');
console.assert(typeof pageFunction === 'function', 'First argument to ElementHandle.evaluate must be a function!');

let stringifiedArgs = ['this'];
const stringifiedArgs = ['this'];
stringifiedArgs.push(...args.map(x => JSON.stringify(x)));
let functionDeclaration = `function() { return (${pageFunction})(${stringifiedArgs.join(',')}) }`;
const functionDeclaration = `function() { return (${pageFunction})(${stringifiedArgs.join(',')}) }`;
const objectId = this._remoteObject.objectId;
let { exceptionDetails, result: remoteObject } = await this._client.send('Runtime.callFunctionOn', { objectId, functionDeclaration, returnByValue: false, awaitPromise: true});
const { exceptionDetails, result: remoteObject } = await this._client.send('Runtime.callFunctionOn', { objectId, functionDeclaration, returnByValue: false, awaitPromise: true});
if (exceptionDetails)
throw new Error('Evaluation failed: ' + helper.getExceptionMessage(exceptionDetails));
return await helper.serializeRemoteObject(this._client, remoteObject);
Expand All @@ -62,11 +62,11 @@ class ElementHandle {
* @return {!Promise<{x: number, y: number}>}
*/
async _visibleCenter() {
let center = await this.evaluate(element => {
const center = await this.evaluate(element => {
if (!element.ownerDocument.contains(element))
return null;
element.scrollIntoViewIfNeeded();
let rect = element.getBoundingClientRect();
const rect = element.getBoundingClientRect();
return {
x: (Math.max(rect.left, 0) + Math.min(rect.right, window.innerWidth)) / 2,
y: (Math.max(rect.top, 0) + Math.min(rect.bottom, window.innerHeight)) / 2
Expand All @@ -81,7 +81,7 @@ class ElementHandle {
* @return {!Promise}
*/
async hover() {
let {x, y} = await this._visibleCenter();
const {x, y} = await this._visibleCenter();
await this._mouse.move(x, y);
}

Expand All @@ -90,7 +90,7 @@ class ElementHandle {
* @return {!Promise}
*/
async click(options) {
let {x, y} = await this._visibleCenter();
const {x, y} = await this._visibleCenter();
await this._mouse.click(x, y, options);
}

Expand All @@ -99,7 +99,7 @@ class ElementHandle {
* @return {!Promise}
*/
async uploadFile(...filePaths) {
let files = filePaths.map(filePath => path.resolve(filePath));
const files = filePaths.map(filePath => path.resolve(filePath));
const objectId = this._remoteObject.objectId;
return this._client.send('DOM.setFileInputFiles', { objectId, files });
}
Expand Down
26 changes: 13 additions & 13 deletions lib/FrameManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,8 @@ class FrameManager extends EventEmitter {
if (this._frames.has(frameId))
return;
console.assert(parentFrameId);
let parentFrame = this._frames.get(parentFrameId);
let frame = new Frame(this._client, this._mouse, parentFrame, frameId);
const parentFrame = this._frames.get(parentFrameId);
const frame = new Frame(this._client, this._mouse, parentFrame, frameId);
this._frames.set(frame._id, frame);
this.emit(FrameManager.Events.FrameAttached, frame);
}
Expand All @@ -77,7 +77,7 @@ class FrameManager extends EventEmitter {

// Detach all child frames first.
if (frame) {
for (let child of frame.childFrames())
for (const child of frame.childFrames())
this._removeFramesRecursively(child);
}

Expand Down Expand Up @@ -105,7 +105,7 @@ class FrameManager extends EventEmitter {
* @param {string} frameId
*/
_onFrameDetached(frameId) {
let frame = this._frames.get(frameId);
const frame = this._frames.get(frameId);
if (frame)
this._removeFramesRecursively(frame);
}
Expand All @@ -116,15 +116,15 @@ class FrameManager extends EventEmitter {
if (!frame)
return;
frame._defaultContextId = context.id;
for (let waitTask of frame._waitTasks)
for (const waitTask of frame._waitTasks)
waitTask.rerun();
}

/**
* @param {!Frame} frame
*/
_removeFramesRecursively(frame) {
for (let child of frame.childFrames())
for (const child of frame.childFrames())
this._removeFramesRecursively(child);
frame._detach();
this._frames.delete(frame._id);
Expand Down Expand Up @@ -179,7 +179,7 @@ class Frame {
* @return {!Promise<(!Object|undefined)>}
*/
async evaluate(pageFunction, ...args) {
let remoteObject = await this._rawEvaluate(pageFunction, ...args);
const remoteObject = await this._rawEvaluate(pageFunction, ...args);
return await helper.serializeRemoteObject(this._client, remoteObject);
}

Expand All @@ -188,7 +188,7 @@ class Frame {
* @return {!Promise<?ElementHandle>}
*/
async $(selector) {
let remoteObject = await this._rawEvaluate(selector => document.querySelector(selector), selector);
const remoteObject = await this._rawEvaluate(selector => document.querySelector(selector), selector);
if (remoteObject.subtype === 'node')
return new ElementHandle(this._client, remoteObject, this._mouse);
helper.releaseObject(this._client, remoteObject);
Expand All @@ -201,9 +201,9 @@ class Frame {
* @return {!Promise<(!Object|undefined)>}
*/
async _rawEvaluate(pageFunction, ...args) {
let expression = helper.evaluationString(pageFunction, ...args);
const expression = helper.evaluationString(pageFunction, ...args);
const contextId = this._defaultContextId;
let { exceptionDetails, result: remoteObject } = await this._client.send('Runtime.evaluate', { expression, contextId, returnByValue: false, awaitPromise: true});
const { exceptionDetails, result: remoteObject } = await this._client.send('Runtime.evaluate', { expression, contextId, returnByValue: false, awaitPromise: true});
if (exceptionDetails)
throw new Error('Evaluation failed: ' + helper.getExceptionMessage(exceptionDetails));
return remoteObject;
Expand Down Expand Up @@ -270,9 +270,9 @@ class Frame {
* @param {string} url
*/
function addScriptTag(url) {
let script = document.createElement('script');
const script = document.createElement('script');
script.src = url;
let promise = new Promise(x => script.onload = x);
const promise = new Promise(x => script.onload = x);
document.head.appendChild(script);
return promise;
}
Expand Down Expand Up @@ -349,7 +349,7 @@ class Frame {
}

_detach() {
for (let waitTask of this._waitTasks)
for (const waitTask of this._waitTasks)
waitTask.terminate(new Error('waitForSelector failed: frame got detached.'));
this._detached = true;
if (this._parentFrame)
Expand Down
2 changes: 1 addition & 1 deletion lib/Input.js
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ class Mouse {
}
}

let keys = {
const keys = {
'Cancel': 3,
'Help': 6,
'Backspace': 8,
Expand Down
6 changes: 3 additions & 3 deletions lib/Launcher.js
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ class Launcher {
* @return {!Promise<!Browser>}
*/
static async connect({browserWSEndpoint, ignoreHTTPSErrors = false}) {
let connection = await Connection.create(browserWSEndpoint);
const connection = await Connection.create(browserWSEndpoint);
return new Browser(connection, !!ignoreHTTPSErrors);
}
}
Expand All @@ -127,12 +127,12 @@ function waitForWSEndpoint(chromeProcess, timeout) {
return new Promise((resolve, reject) => {
const rl = readline.createInterface({ input: chromeProcess.stderr });
let stderr = '';
let listeners = [
const listeners = [
helper.addEventListener(rl, 'line', onLine),
helper.addEventListener(rl, 'close', onClose),
helper.addEventListener(chromeProcess, 'exit', onClose)
];
let timeoutId = timeout ? setTimeout(onTimeout, timeout) : 0;
const timeoutId = timeout ? setTimeout(onTimeout, timeout) : 0;

function onClose() {
cleanup();
Expand Down
12 changes: 6 additions & 6 deletions lib/Multimap.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ class Multimap {
* @return {boolean}
*/
hasValue(key, value) {
let set = this._map.get(key);
const set = this._map.get(key);
if (!set)
return false;
return set.has(value);
Expand All @@ -80,8 +80,8 @@ class Multimap {
* @return {boolean}
*/
delete(key, value) {
let values = this.get(key);
let result = values.delete(value);
const values = this.get(key);
const result = values.delete(value);
if (!values.size)
this._map.delete(key);
return result;
Expand All @@ -99,7 +99,7 @@ class Multimap {
* @return {?V} value
*/
firstValue(key) {
let set = this._map.get(key);
const set = this._map.get(key);
if (!set)
return null;
return set.values().next().value;
Expand All @@ -116,8 +116,8 @@ class Multimap {
* @return {!Array<!V>}
*/
valuesArray() {
let result = [];
for (let key of this._map.keys())
const result = [];
for (const key of this._map.keys())
result.push(...Array.from(this._map.get(key).values()));
return result;
}
Expand Down
10 changes: 5 additions & 5 deletions lib/NavigatorWatcher.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,19 +40,19 @@ class NavigatorWatcher {

this._eventListeners = [];

let watchdog = new Promise(fulfill => this._maximumTimer = setTimeout(fulfill, this._timeout))
const watchdog = new Promise(fulfill => this._maximumTimer = setTimeout(fulfill, this._timeout))
.then(() => 'Navigation Timeout Exceeded: ' + this._timeout + 'ms exceeded');
let navigationPromises = [watchdog];
const navigationPromises = [watchdog];

if (!this._ignoreHTTPSErrors) {
let certificateError = new Promise(fulfill => {
const certificateError = new Promise(fulfill => {
this._eventListeners.push(helper.addEventListener(this._client, 'Security.certificateError', fulfill));
}).then(error => 'SSL Certificate error: ' + error.errorType);
navigationPromises.push(certificateError);
}

if (this._waitUntil === 'load') {
let loadEventFired = new Promise(fulfill => {
const loadEventFired = new Promise(fulfill => {
this._eventListeners.push(helper.addEventListener(this._client, 'Page.loadEventFired', fulfill));
}).then(() => null);
navigationPromises.push(loadEventFired);
Expand All @@ -64,7 +64,7 @@ class NavigatorWatcher {
helper.addEventListener(this._client, 'Network.webSocketCreated', this._onLoadingStarted.bind(this)),
helper.addEventListener(this._client, 'Network.webSocketClosed', this._onLoadingCompleted.bind(this)),
]);
let networkIdle = new Promise(fulfill => this._networkIdleCallback = fulfill).then(() => null);
const networkIdle = new Promise(fulfill => this._networkIdleCallback = fulfill).then(() => null);
navigationPromises.push(networkIdle);
}

Expand Down
Loading

0 comments on commit 1f9b4fb

Please sign in to comment.